PackageManagerService.java revision 8a1bc54ab050daac935536f7fc5a8b9130e3eed3
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            // Collected privileged vendor packages.
2452            final File privilegedVendorAppDir = new File(Environment.getVendorDirectory(), "priv-app");
2453            scanDirLI(privilegedVendorAppDir, PackageParser.PARSE_IS_SYSTEM
2454                    | PackageParser.PARSE_IS_SYSTEM_DIR
2455                    | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0);
2456
2457            // Collect all vendor packages.
2458            File vendorAppDir = new File(Environment.getVendorDirectory(), "app");
2459            try {
2460                vendorAppDir = vendorAppDir.getCanonicalFile();
2461            } catch (IOException e) {
2462                // failed to look up canonical path, continue with original one
2463            }
2464            scanDirTracedLI(vendorAppDir, mDefParseFlags
2465                    | PackageParser.PARSE_IS_SYSTEM
2466                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2467
2468            // Collect all OEM packages.
2469            final File oemAppDir = new File(Environment.getOemDirectory(), "app");
2470            scanDirTracedLI(oemAppDir, mDefParseFlags
2471                    | PackageParser.PARSE_IS_SYSTEM
2472                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2473
2474            // Prune any system packages that no longer exist.
2475            final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>();
2476            if (!mOnlyCore) {
2477                Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
2478                while (psit.hasNext()) {
2479                    PackageSetting ps = psit.next();
2480
2481                    /*
2482                     * If this is not a system app, it can't be a
2483                     * disable system app.
2484                     */
2485                    if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
2486                        continue;
2487                    }
2488
2489                    /*
2490                     * If the package is scanned, it's not erased.
2491                     */
2492                    final PackageParser.Package scannedPkg = mPackages.get(ps.name);
2493                    if (scannedPkg != null) {
2494                        /*
2495                         * If the system app is both scanned and in the
2496                         * disabled packages list, then it must have been
2497                         * added via OTA. Remove it from the currently
2498                         * scanned package so the previously user-installed
2499                         * application can be scanned.
2500                         */
2501                        if (mSettings.isDisabledSystemPackageLPr(ps.name)) {
2502                            logCriticalInfo(Log.WARN, "Expecting better updated system app for "
2503                                    + ps.name + "; removing system app.  Last known codePath="
2504                                    + ps.codePathString + ", installStatus=" + ps.installStatus
2505                                    + ", versionCode=" + ps.versionCode + "; scanned versionCode="
2506                                    + scannedPkg.mVersionCode);
2507                            removePackageLI(scannedPkg, true);
2508                            mExpectingBetter.put(ps.name, ps.codePath);
2509                        }
2510
2511                        continue;
2512                    }
2513
2514                    if (!mSettings.isDisabledSystemPackageLPr(ps.name)) {
2515                        psit.remove();
2516                        logCriticalInfo(Log.WARN, "System package " + ps.name
2517                                + " no longer exists; it's data will be wiped");
2518                        // Actual deletion of code and data will be handled by later
2519                        // reconciliation step
2520                    } else {
2521                        final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name);
2522                        if (disabledPs.codePath == null || !disabledPs.codePath.exists()) {
2523                            possiblyDeletedUpdatedSystemApps.add(ps.name);
2524                        }
2525                    }
2526                }
2527            }
2528
2529            //look for any incomplete package installations
2530            ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr();
2531            for (int i = 0; i < deletePkgsList.size(); i++) {
2532                // Actual deletion of code and data will be handled by later
2533                // reconciliation step
2534                final String packageName = deletePkgsList.get(i).name;
2535                logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + packageName);
2536                synchronized (mPackages) {
2537                    mSettings.removePackageLPw(packageName);
2538                }
2539            }
2540
2541            //delete tmp files
2542            deleteTempPackageFiles();
2543
2544            // Remove any shared userIDs that have no associated packages
2545            mSettings.pruneSharedUsersLPw();
2546
2547            if (!mOnlyCore) {
2548                EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
2549                        SystemClock.uptimeMillis());
2550                scanDirTracedLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0);
2551
2552                scanDirTracedLI(mDrmAppPrivateInstallDir, mDefParseFlags
2553                        | PackageParser.PARSE_FORWARD_LOCK,
2554                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2555
2556                scanDirLI(mEphemeralInstallDir, mDefParseFlags
2557                        | PackageParser.PARSE_IS_EPHEMERAL,
2558                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2559
2560                /**
2561                 * Remove disable package settings for any updated system
2562                 * apps that were removed via an OTA. If they're not a
2563                 * previously-updated app, remove them completely.
2564                 * Otherwise, just revoke their system-level permissions.
2565                 */
2566                for (String deletedAppName : possiblyDeletedUpdatedSystemApps) {
2567                    PackageParser.Package deletedPkg = mPackages.get(deletedAppName);
2568                    mSettings.removeDisabledSystemPackageLPw(deletedAppName);
2569
2570                    String msg;
2571                    if (deletedPkg == null) {
2572                        msg = "Updated system package " + deletedAppName
2573                                + " no longer exists; it's data will be wiped";
2574                        // Actual deletion of code and data will be handled by later
2575                        // reconciliation step
2576                    } else {
2577                        msg = "Updated system app + " + deletedAppName
2578                                + " no longer present; removing system privileges for "
2579                                + deletedAppName;
2580
2581                        deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM;
2582
2583                        PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName);
2584                        deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM;
2585                    }
2586                    logCriticalInfo(Log.WARN, msg);
2587                }
2588
2589                /**
2590                 * Make sure all system apps that we expected to appear on
2591                 * the userdata partition actually showed up. If they never
2592                 * appeared, crawl back and revive the system version.
2593                 */
2594                for (int i = 0; i < mExpectingBetter.size(); i++) {
2595                    final String packageName = mExpectingBetter.keyAt(i);
2596                    if (!mPackages.containsKey(packageName)) {
2597                        final File scanFile = mExpectingBetter.valueAt(i);
2598
2599                        logCriticalInfo(Log.WARN, "Expected better " + packageName
2600                                + " but never showed up; reverting to system");
2601
2602                        int reparseFlags = mDefParseFlags;
2603                        if (FileUtils.contains(privilegedAppDir, scanFile)) {
2604                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2605                                    | PackageParser.PARSE_IS_SYSTEM_DIR
2606                                    | PackageParser.PARSE_IS_PRIVILEGED;
2607                        } else if (FileUtils.contains(systemAppDir, scanFile)) {
2608                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2609                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2610                        } else if (FileUtils.contains(vendorAppDir, scanFile)) {
2611                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2612                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2613                        } else if (FileUtils.contains(oemAppDir, scanFile)) {
2614                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2615                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2616                        } else {
2617                            Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile);
2618                            continue;
2619                        }
2620
2621                        mSettings.enableSystemPackageLPw(packageName);
2622
2623                        try {
2624                            scanPackageTracedLI(scanFile, reparseFlags, scanFlags, 0, null);
2625                        } catch (PackageManagerException e) {
2626                            Slog.e(TAG, "Failed to parse original system package: "
2627                                    + e.getMessage());
2628                        }
2629                    }
2630                }
2631            }
2632            mExpectingBetter.clear();
2633
2634            // Resolve protected action filters. Only the setup wizard is allowed to
2635            // have a high priority filter for these actions.
2636            mSetupWizardPackage = getSetupWizardPackageName();
2637            if (mProtectedFilters.size() > 0) {
2638                if (DEBUG_FILTERS && mSetupWizardPackage == null) {
2639                    Slog.i(TAG, "No setup wizard;"
2640                        + " All protected intents capped to priority 0");
2641                }
2642                for (ActivityIntentInfo filter : mProtectedFilters) {
2643                    if (filter.activity.info.packageName.equals(mSetupWizardPackage)) {
2644                        if (DEBUG_FILTERS) {
2645                            Slog.i(TAG, "Found setup wizard;"
2646                                + " allow priority " + filter.getPriority() + ";"
2647                                + " package: " + filter.activity.info.packageName
2648                                + " activity: " + filter.activity.className
2649                                + " priority: " + filter.getPriority());
2650                        }
2651                        // skip setup wizard; allow it to keep the high priority filter
2652                        continue;
2653                    }
2654                    Slog.w(TAG, "Protected action; cap priority to 0;"
2655                            + " package: " + filter.activity.info.packageName
2656                            + " activity: " + filter.activity.className
2657                            + " origPrio: " + filter.getPriority());
2658                    filter.setPriority(0);
2659                }
2660            }
2661            mDeferProtectedFilters = false;
2662            mProtectedFilters.clear();
2663
2664            // Now that we know all of the shared libraries, update all clients to have
2665            // the correct library paths.
2666            updateAllSharedLibrariesLPw();
2667
2668            for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) {
2669                // NOTE: We ignore potential failures here during a system scan (like
2670                // the rest of the commands above) because there's precious little we
2671                // can do about it. A settings error is reported, though.
2672                adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */,
2673                        false /* boot complete */);
2674            }
2675
2676            // Now that we know all the packages we are keeping,
2677            // read and update their last usage times.
2678            mPackageUsage.readLP();
2679
2680            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
2681                    SystemClock.uptimeMillis());
2682            Slog.i(TAG, "Time to scan packages: "
2683                    + ((SystemClock.uptimeMillis()-startTime)/1000f)
2684                    + " seconds");
2685
2686            // If the platform SDK has changed since the last time we booted,
2687            // we need to re-grant app permission to catch any new ones that
2688            // appear.  This is really a hack, and means that apps can in some
2689            // cases get permissions that the user didn't initially explicitly
2690            // allow...  it would be nice to have some better way to handle
2691            // this situation.
2692            int updateFlags = UPDATE_PERMISSIONS_ALL;
2693            if (ver.sdkVersion != mSdkVersion) {
2694                Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to "
2695                        + mSdkVersion + "; regranting permissions for internal storage");
2696                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
2697            }
2698            updatePermissionsLPw(null, null, StorageManager.UUID_PRIVATE_INTERNAL, updateFlags);
2699            ver.sdkVersion = mSdkVersion;
2700
2701            // If this is the first boot or an update from pre-M, and it is a normal
2702            // boot, then we need to initialize the default preferred apps across
2703            // all defined users.
2704            if (!onlyCore && (mPromoteSystemApps || !mRestoredSettings)) {
2705                for (UserInfo user : sUserManager.getUsers(true)) {
2706                    mSettings.applyDefaultPreferredAppsLPw(this, user.id);
2707                    applyFactoryDefaultBrowserLPw(user.id);
2708                    primeDomainVerificationsLPw(user.id);
2709                }
2710            }
2711
2712            // Prepare storage for system user really early during boot,
2713            // since core system apps like SettingsProvider and SystemUI
2714            // can't wait for user to start
2715            final int storageFlags;
2716            if (StorageManager.isFileEncryptedNativeOrEmulated()) {
2717                storageFlags = StorageManager.FLAG_STORAGE_DE;
2718            } else {
2719                storageFlags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
2720            }
2721            reconcileAppsDataLI(StorageManager.UUID_PRIVATE_INTERNAL, UserHandle.USER_SYSTEM,
2722                    storageFlags);
2723
2724            // If this is first boot after an OTA, and a normal boot, then
2725            // we need to clear code cache directories.
2726            // Note that we do *not* clear the application profiles. These remain valid
2727            // across OTAs and are used to drive profile verification (post OTA) and
2728            // profile compilation (without waiting to collect a fresh set of profiles).
2729            if (mIsUpgrade && !onlyCore) {
2730                Slog.i(TAG, "Build fingerprint changed; clearing code caches");
2731                for (int i = 0; i < mSettings.mPackages.size(); i++) {
2732                    final PackageSetting ps = mSettings.mPackages.valueAt(i);
2733                    if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) {
2734                        // No apps are running this early, so no need to freeze
2735                        clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
2736                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
2737                                        | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
2738                    }
2739                }
2740                ver.fingerprint = Build.FINGERPRINT;
2741            }
2742
2743            checkDefaultBrowser();
2744
2745            // clear only after permissions and other defaults have been updated
2746            mExistingSystemPackages.clear();
2747            mPromoteSystemApps = false;
2748
2749            // All the changes are done during package scanning.
2750            ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION;
2751
2752            // can downgrade to reader
2753            mSettings.writeLPr();
2754
2755            // Perform dexopt on all apps that mark themselves as coreApps. We do this pretty
2756            // early on (before the package manager declares itself as early) because other
2757            // components in the system server might ask for package contexts for these apps.
2758            //
2759            // Note that "onlyCore" in this context means the system is encrypted or encrypting
2760            // (i.e, that the data partition is unavailable).
2761            if ((isFirstBoot() || isUpgrade() || VMRuntime.didPruneDalvikCache()) && !onlyCore) {
2762                long start = System.nanoTime();
2763                List<PackageParser.Package> coreApps = new ArrayList<>();
2764                for (PackageParser.Package pkg : mPackages.values()) {
2765                    if (pkg.coreApp) {
2766                        coreApps.add(pkg);
2767                    }
2768                }
2769
2770                int[] stats = performDexOpt(coreApps, false,
2771                        getCompilerFilterForReason(REASON_CORE_APP));
2772
2773                final int elapsedTimeSeconds =
2774                        (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - start);
2775                MetricsLogger.histogram(mContext, "opt_coreapps_time_s", elapsedTimeSeconds);
2776
2777                if (DEBUG_DEXOPT) {
2778                    Slog.i(TAG, "Dex-opt core apps took : " + elapsedTimeSeconds + " seconds (" +
2779                            stats[0] + ", " + stats[1] + ", " + stats[2] + ")");
2780                }
2781
2782
2783                // TODO: Should we log these stats to tron too ?
2784                // MetricsLogger.histogram(mContext, "opt_coreapps_num_dexopted", stats[0]);
2785                // MetricsLogger.histogram(mContext, "opt_coreapps_num_skipped", stats[1]);
2786                // MetricsLogger.histogram(mContext, "opt_coreapps_num_failed", stats[2]);
2787                // MetricsLogger.histogram(mContext, "opt_coreapps_num_total", coreApps.size());
2788            }
2789
2790            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
2791                    SystemClock.uptimeMillis());
2792
2793            if (!mOnlyCore) {
2794                mRequiredVerifierPackage = getRequiredButNotReallyRequiredVerifierLPr();
2795                mRequiredInstallerPackage = getRequiredInstallerLPr();
2796                mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr();
2797                mIntentFilterVerifier = new IntentVerifierProxy(mContext,
2798                        mIntentFilterVerifierComponent);
2799                mServicesSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
2800                        PackageManager.SYSTEM_SHARED_LIBRARY_SERVICES);
2801                mSharedSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
2802                        PackageManager.SYSTEM_SHARED_LIBRARY_SHARED);
2803            } else {
2804                mRequiredVerifierPackage = null;
2805                mRequiredInstallerPackage = null;
2806                mIntentFilterVerifierComponent = null;
2807                mIntentFilterVerifier = null;
2808                mServicesSystemSharedLibraryPackageName = null;
2809                mSharedSystemSharedLibraryPackageName = null;
2810            }
2811
2812            mInstallerService = new PackageInstallerService(context, this);
2813
2814            final ComponentName ephemeralResolverComponent = getEphemeralResolverLPr();
2815            final ComponentName ephemeralInstallerComponent = getEphemeralInstallerLPr();
2816            // both the installer and resolver must be present to enable ephemeral
2817            if (ephemeralInstallerComponent != null && ephemeralResolverComponent != null) {
2818                if (DEBUG_EPHEMERAL) {
2819                    Slog.i(TAG, "Ephemeral activated; resolver: " + ephemeralResolverComponent
2820                            + " installer:" + ephemeralInstallerComponent);
2821                }
2822                mEphemeralResolverComponent = ephemeralResolverComponent;
2823                mEphemeralInstallerComponent = ephemeralInstallerComponent;
2824                setUpEphemeralInstallerActivityLP(mEphemeralInstallerComponent);
2825                mEphemeralResolverConnection =
2826                        new EphemeralResolverConnection(mContext, mEphemeralResolverComponent);
2827            } else {
2828                if (DEBUG_EPHEMERAL) {
2829                    final String missingComponent =
2830                            (ephemeralResolverComponent == null)
2831                            ? (ephemeralInstallerComponent == null)
2832                                    ? "resolver and installer"
2833                                    : "resolver"
2834                            : "installer";
2835                    Slog.i(TAG, "Ephemeral deactivated; missing " + missingComponent);
2836                }
2837                mEphemeralResolverComponent = null;
2838                mEphemeralInstallerComponent = null;
2839                mEphemeralResolverConnection = null;
2840            }
2841
2842            mEphemeralApplicationRegistry = new EphemeralApplicationRegistry(this);
2843        } // synchronized (mPackages)
2844        } // synchronized (mInstallLock)
2845
2846        // Now after opening every single application zip, make sure they
2847        // are all flushed.  Not really needed, but keeps things nice and
2848        // tidy.
2849        Runtime.getRuntime().gc();
2850
2851        // The initial scanning above does many calls into installd while
2852        // holding the mPackages lock, but we're mostly interested in yelling
2853        // once we have a booted system.
2854        mInstaller.setWarnIfHeld(mPackages);
2855
2856        // Expose private service for system components to use.
2857        LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl());
2858    }
2859
2860    @Override
2861    public boolean isFirstBoot() {
2862        return !mRestoredSettings;
2863    }
2864
2865    @Override
2866    public boolean isOnlyCoreApps() {
2867        return mOnlyCore;
2868    }
2869
2870    @Override
2871    public boolean isUpgrade() {
2872        return mIsUpgrade;
2873    }
2874
2875    private @Nullable String getRequiredButNotReallyRequiredVerifierLPr() {
2876        final Intent intent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
2877
2878        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
2879                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
2880                UserHandle.USER_SYSTEM);
2881        if (matches.size() == 1) {
2882            return matches.get(0).getComponentInfo().packageName;
2883        } else {
2884            Log.e(TAG, "There should probably be exactly one verifier; found " + matches);
2885            return null;
2886        }
2887    }
2888
2889    private @NonNull String getRequiredSharedLibraryLPr(String libraryName) {
2890        synchronized (mPackages) {
2891            SharedLibraryEntry libraryEntry = mSharedLibraries.get(libraryName);
2892            if (libraryEntry == null) {
2893                throw new IllegalStateException("Missing required shared library:" + libraryName);
2894            }
2895            return libraryEntry.apk;
2896        }
2897    }
2898
2899    private @NonNull String getRequiredInstallerLPr() {
2900        final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
2901        intent.addCategory(Intent.CATEGORY_DEFAULT);
2902        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
2903
2904        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
2905                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
2906                UserHandle.USER_SYSTEM);
2907        if (matches.size() == 1) {
2908            ResolveInfo resolveInfo = matches.get(0);
2909            if (!resolveInfo.activityInfo.applicationInfo.isPrivilegedApp()) {
2910                throw new RuntimeException("The installer must be a privileged app");
2911            }
2912            return matches.get(0).getComponentInfo().packageName;
2913        } else {
2914            throw new RuntimeException("There must be exactly one installer; found " + matches);
2915        }
2916    }
2917
2918    private @NonNull ComponentName getIntentFilterVerifierComponentNameLPr() {
2919        final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
2920
2921        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
2922                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
2923                UserHandle.USER_SYSTEM);
2924        ResolveInfo best = null;
2925        final int N = matches.size();
2926        for (int i = 0; i < N; i++) {
2927            final ResolveInfo cur = matches.get(i);
2928            final String packageName = cur.getComponentInfo().packageName;
2929            if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
2930                    packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) {
2931                continue;
2932            }
2933
2934            if (best == null || cur.priority > best.priority) {
2935                best = cur;
2936            }
2937        }
2938
2939        if (best != null) {
2940            return best.getComponentInfo().getComponentName();
2941        } else {
2942            throw new RuntimeException("There must be at least one intent filter verifier");
2943        }
2944    }
2945
2946    private @Nullable ComponentName getEphemeralResolverLPr() {
2947        final String[] packageArray =
2948                mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage);
2949        if (packageArray.length == 0) {
2950            if (DEBUG_EPHEMERAL) {
2951                Slog.d(TAG, "Ephemeral resolver NOT found; empty package list");
2952            }
2953            return null;
2954        }
2955
2956        final Intent resolverIntent = new Intent(Intent.ACTION_RESOLVE_EPHEMERAL_PACKAGE);
2957        final List<ResolveInfo> resolvers = queryIntentServicesInternal(resolverIntent, null,
2958                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
2959                UserHandle.USER_SYSTEM);
2960
2961        final int N = resolvers.size();
2962        if (N == 0) {
2963            if (DEBUG_EPHEMERAL) {
2964                Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters");
2965            }
2966            return null;
2967        }
2968
2969        final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray));
2970        for (int i = 0; i < N; i++) {
2971            final ResolveInfo info = resolvers.get(i);
2972
2973            if (info.serviceInfo == null) {
2974                continue;
2975            }
2976
2977            final String packageName = info.serviceInfo.packageName;
2978            if (!possiblePackages.contains(packageName)) {
2979                if (DEBUG_EPHEMERAL) {
2980                    Slog.d(TAG, "Ephemeral resolver not in allowed package list;"
2981                            + " pkg: " + packageName + ", info:" + info);
2982                }
2983                continue;
2984            }
2985
2986            if (DEBUG_EPHEMERAL) {
2987                Slog.v(TAG, "Ephemeral resolver found;"
2988                        + " pkg: " + packageName + ", info:" + info);
2989            }
2990            return new ComponentName(packageName, info.serviceInfo.name);
2991        }
2992        if (DEBUG_EPHEMERAL) {
2993            Slog.v(TAG, "Ephemeral resolver NOT found");
2994        }
2995        return null;
2996    }
2997
2998    private @Nullable ComponentName getEphemeralInstallerLPr() {
2999        final Intent intent = new Intent(Intent.ACTION_INSTALL_EPHEMERAL_PACKAGE);
3000        intent.addCategory(Intent.CATEGORY_DEFAULT);
3001        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
3002
3003        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
3004                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3005                UserHandle.USER_SYSTEM);
3006        if (matches.size() == 0) {
3007            return null;
3008        } else if (matches.size() == 1) {
3009            return matches.get(0).getComponentInfo().getComponentName();
3010        } else {
3011            throw new RuntimeException(
3012                    "There must be at most one ephemeral installer; found " + matches);
3013        }
3014    }
3015
3016    private void primeDomainVerificationsLPw(int userId) {
3017        if (DEBUG_DOMAIN_VERIFICATION) {
3018            Slog.d(TAG, "Priming domain verifications in user " + userId);
3019        }
3020
3021        SystemConfig systemConfig = SystemConfig.getInstance();
3022        ArraySet<String> packages = systemConfig.getLinkedApps();
3023        ArraySet<String> domains = new ArraySet<String>();
3024
3025        for (String packageName : packages) {
3026            PackageParser.Package pkg = mPackages.get(packageName);
3027            if (pkg != null) {
3028                if (!pkg.isSystemApp()) {
3029                    Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>");
3030                    continue;
3031                }
3032
3033                domains.clear();
3034                for (PackageParser.Activity a : pkg.activities) {
3035                    for (ActivityIntentInfo filter : a.intents) {
3036                        if (hasValidDomains(filter)) {
3037                            domains.addAll(filter.getHostsList());
3038                        }
3039                    }
3040                }
3041
3042                if (domains.size() > 0) {
3043                    if (DEBUG_DOMAIN_VERIFICATION) {
3044                        Slog.v(TAG, "      + " + packageName);
3045                    }
3046                    // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual
3047                    // state w.r.t. the formal app-linkage "no verification attempted" state;
3048                    // and then 'always' in the per-user state actually used for intent resolution.
3049                    final IntentFilterVerificationInfo ivi;
3050                    ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName,
3051                            new ArrayList<String>(domains));
3052                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED);
3053                    mSettings.updateIntentFilterVerificationStatusLPw(packageName,
3054                            INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId);
3055                } else {
3056                    Slog.w(TAG, "Sysconfig <app-link> package '" + packageName
3057                            + "' does not handle web links");
3058                }
3059            } else {
3060                Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>");
3061            }
3062        }
3063
3064        scheduleWritePackageRestrictionsLocked(userId);
3065        scheduleWriteSettingsLocked();
3066    }
3067
3068    private void applyFactoryDefaultBrowserLPw(int userId) {
3069        // The default browser app's package name is stored in a string resource,
3070        // with a product-specific overlay used for vendor customization.
3071        String browserPkg = mContext.getResources().getString(
3072                com.android.internal.R.string.default_browser);
3073        if (!TextUtils.isEmpty(browserPkg)) {
3074            // non-empty string => required to be a known package
3075            PackageSetting ps = mSettings.mPackages.get(browserPkg);
3076            if (ps == null) {
3077                Slog.e(TAG, "Product default browser app does not exist: " + browserPkg);
3078                browserPkg = null;
3079            } else {
3080                mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
3081            }
3082        }
3083
3084        // Nothing valid explicitly set? Make the factory-installed browser the explicit
3085        // default.  If there's more than one, just leave everything alone.
3086        if (browserPkg == null) {
3087            calculateDefaultBrowserLPw(userId);
3088        }
3089    }
3090
3091    private void calculateDefaultBrowserLPw(int userId) {
3092        List<String> allBrowsers = resolveAllBrowserApps(userId);
3093        final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null;
3094        mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
3095    }
3096
3097    private List<String> resolveAllBrowserApps(int userId) {
3098        // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set
3099        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
3100                PackageManager.MATCH_ALL, userId);
3101
3102        final int count = list.size();
3103        List<String> result = new ArrayList<String>(count);
3104        for (int i=0; i<count; i++) {
3105            ResolveInfo info = list.get(i);
3106            if (info.activityInfo == null
3107                    || !info.handleAllWebDataURI
3108                    || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0
3109                    || result.contains(info.activityInfo.packageName)) {
3110                continue;
3111            }
3112            result.add(info.activityInfo.packageName);
3113        }
3114
3115        return result;
3116    }
3117
3118    private boolean packageIsBrowser(String packageName, int userId) {
3119        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
3120                PackageManager.MATCH_ALL, userId);
3121        final int N = list.size();
3122        for (int i = 0; i < N; i++) {
3123            ResolveInfo info = list.get(i);
3124            if (packageName.equals(info.activityInfo.packageName)) {
3125                return true;
3126            }
3127        }
3128        return false;
3129    }
3130
3131    private void checkDefaultBrowser() {
3132        final int myUserId = UserHandle.myUserId();
3133        final String packageName = getDefaultBrowserPackageName(myUserId);
3134        if (packageName != null) {
3135            PackageInfo info = getPackageInfo(packageName, 0, myUserId);
3136            if (info == null) {
3137                Slog.w(TAG, "Default browser no longer installed: " + packageName);
3138                synchronized (mPackages) {
3139                    applyFactoryDefaultBrowserLPw(myUserId);    // leaves ambiguous when > 1
3140                }
3141            }
3142        }
3143    }
3144
3145    @Override
3146    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
3147            throws RemoteException {
3148        try {
3149            return super.onTransact(code, data, reply, flags);
3150        } catch (RuntimeException e) {
3151            if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
3152                Slog.wtf(TAG, "Package Manager Crash", e);
3153            }
3154            throw e;
3155        }
3156    }
3157
3158    static int[] appendInts(int[] cur, int[] add) {
3159        if (add == null) return cur;
3160        if (cur == null) return add;
3161        final int N = add.length;
3162        for (int i=0; i<N; i++) {
3163            cur = appendInt(cur, add[i]);
3164        }
3165        return cur;
3166    }
3167
3168    private PackageInfo generatePackageInfo(PackageSetting ps, int flags, int userId) {
3169        if (!sUserManager.exists(userId)) return null;
3170        if (ps == null) {
3171            return null;
3172        }
3173        final PackageParser.Package p = ps.pkg;
3174        if (p == null) {
3175            return null;
3176        }
3177
3178        final PermissionsState permissionsState = ps.getPermissionsState();
3179
3180        final int[] gids = permissionsState.computeGids(userId);
3181        final Set<String> permissions = permissionsState.getPermissions(userId);
3182        final PackageUserState state = ps.readUserState(userId);
3183
3184        return PackageParser.generatePackageInfo(p, gids, flags,
3185                ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId);
3186    }
3187
3188    @Override
3189    public void checkPackageStartable(String packageName, int userId) {
3190        final boolean userKeyUnlocked = StorageManager.isUserKeyUnlocked(userId);
3191
3192        synchronized (mPackages) {
3193            final PackageSetting ps = mSettings.mPackages.get(packageName);
3194            if (ps == null) {
3195                throw new SecurityException("Package " + packageName + " was not found!");
3196            }
3197
3198            if (!ps.getInstalled(userId)) {
3199                throw new SecurityException(
3200                        "Package " + packageName + " was not installed for user " + userId + "!");
3201            }
3202
3203            if (mSafeMode && !ps.isSystem()) {
3204                throw new SecurityException("Package " + packageName + " not a system app!");
3205            }
3206
3207            if (mFrozenPackages.contains(packageName)) {
3208                throw new SecurityException("Package " + packageName + " is currently frozen!");
3209            }
3210
3211            if (!userKeyUnlocked && !(ps.pkg.applicationInfo.isDirectBootAware()
3212                    || ps.pkg.applicationInfo.isPartiallyDirectBootAware())) {
3213                throw new SecurityException("Package " + packageName + " is not encryption aware!");
3214            }
3215        }
3216    }
3217
3218    @Override
3219    public boolean isPackageAvailable(String packageName, int userId) {
3220        if (!sUserManager.exists(userId)) return false;
3221        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3222                false /* requireFullPermission */, false /* checkShell */, "is package available");
3223        synchronized (mPackages) {
3224            PackageParser.Package p = mPackages.get(packageName);
3225            if (p != null) {
3226                final PackageSetting ps = (PackageSetting) p.mExtras;
3227                if (ps != null) {
3228                    final PackageUserState state = ps.readUserState(userId);
3229                    if (state != null) {
3230                        return PackageParser.isAvailable(state);
3231                    }
3232                }
3233            }
3234        }
3235        return false;
3236    }
3237
3238    @Override
3239    public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
3240        if (!sUserManager.exists(userId)) return null;
3241        flags = updateFlagsForPackage(flags, userId, packageName);
3242        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3243                false /* requireFullPermission */, false /* checkShell */, "get package info");
3244        // reader
3245        synchronized (mPackages) {
3246            final boolean matchFactoryOnly = (flags & MATCH_FACTORY_ONLY) != 0;
3247            PackageParser.Package p = null;
3248            if (matchFactoryOnly) {
3249                final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName);
3250                if (ps != null) {
3251                    return generatePackageInfo(ps, flags, userId);
3252                }
3253            }
3254            if (p == null) {
3255                p = mPackages.get(packageName);
3256                if (matchFactoryOnly && p != null && !isSystemApp(p)) {
3257                    return null;
3258                }
3259            }
3260            if (DEBUG_PACKAGE_INFO)
3261                Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
3262            if (p != null) {
3263                return generatePackageInfo((PackageSetting)p.mExtras, flags, userId);
3264            }
3265            if (!matchFactoryOnly && (flags & MATCH_UNINSTALLED_PACKAGES) != 0) {
3266                final PackageSetting ps = mSettings.mPackages.get(packageName);
3267                return generatePackageInfo(ps, flags, userId);
3268            }
3269        }
3270        return null;
3271    }
3272
3273    @Override
3274    public String[] currentToCanonicalPackageNames(String[] names) {
3275        String[] out = new String[names.length];
3276        // reader
3277        synchronized (mPackages) {
3278            for (int i=names.length-1; i>=0; i--) {
3279                PackageSetting ps = mSettings.mPackages.get(names[i]);
3280                out[i] = ps != null && ps.realName != null ? ps.realName : names[i];
3281            }
3282        }
3283        return out;
3284    }
3285
3286    @Override
3287    public String[] canonicalToCurrentPackageNames(String[] names) {
3288        String[] out = new String[names.length];
3289        // reader
3290        synchronized (mPackages) {
3291            for (int i=names.length-1; i>=0; i--) {
3292                String cur = mSettings.mRenamedPackages.get(names[i]);
3293                out[i] = cur != null ? cur : names[i];
3294            }
3295        }
3296        return out;
3297    }
3298
3299    @Override
3300    public int getPackageUid(String packageName, int flags, int userId) {
3301        if (!sUserManager.exists(userId)) return -1;
3302        flags = updateFlagsForPackage(flags, userId, packageName);
3303        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3304                false /* requireFullPermission */, false /* checkShell */, "get package uid");
3305
3306        // reader
3307        synchronized (mPackages) {
3308            final PackageParser.Package p = mPackages.get(packageName);
3309            if (p != null && p.isMatch(flags)) {
3310                return UserHandle.getUid(userId, p.applicationInfo.uid);
3311            }
3312            if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) {
3313                final PackageSetting ps = mSettings.mPackages.get(packageName);
3314                if (ps != null && ps.isMatch(flags)) {
3315                    return UserHandle.getUid(userId, ps.appId);
3316                }
3317            }
3318        }
3319
3320        return -1;
3321    }
3322
3323    @Override
3324    public int[] getPackageGids(String packageName, int flags, int userId) {
3325        if (!sUserManager.exists(userId)) return null;
3326        flags = updateFlagsForPackage(flags, userId, packageName);
3327        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3328                false /* requireFullPermission */, false /* checkShell */,
3329                "getPackageGids");
3330
3331        // reader
3332        synchronized (mPackages) {
3333            final PackageParser.Package p = mPackages.get(packageName);
3334            if (p != null && p.isMatch(flags)) {
3335                PackageSetting ps = (PackageSetting) p.mExtras;
3336                return ps.getPermissionsState().computeGids(userId);
3337            }
3338            if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) {
3339                final PackageSetting ps = mSettings.mPackages.get(packageName);
3340                if (ps != null && ps.isMatch(flags)) {
3341                    return ps.getPermissionsState().computeGids(userId);
3342                }
3343            }
3344        }
3345
3346        return null;
3347    }
3348
3349    static PermissionInfo generatePermissionInfo(BasePermission bp, int flags) {
3350        if (bp.perm != null) {
3351            return PackageParser.generatePermissionInfo(bp.perm, flags);
3352        }
3353        PermissionInfo pi = new PermissionInfo();
3354        pi.name = bp.name;
3355        pi.packageName = bp.sourcePackage;
3356        pi.nonLocalizedLabel = bp.name;
3357        pi.protectionLevel = bp.protectionLevel;
3358        return pi;
3359    }
3360
3361    @Override
3362    public PermissionInfo getPermissionInfo(String name, int flags) {
3363        // reader
3364        synchronized (mPackages) {
3365            final BasePermission p = mSettings.mPermissions.get(name);
3366            if (p != null) {
3367                return generatePermissionInfo(p, flags);
3368            }
3369            return null;
3370        }
3371    }
3372
3373    @Override
3374    public @Nullable ParceledListSlice<PermissionInfo> queryPermissionsByGroup(String group,
3375            int flags) {
3376        // reader
3377        synchronized (mPackages) {
3378            if (group != null && !mPermissionGroups.containsKey(group)) {
3379                // This is thrown as NameNotFoundException
3380                return null;
3381            }
3382
3383            ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
3384            for (BasePermission p : mSettings.mPermissions.values()) {
3385                if (group == null) {
3386                    if (p.perm == null || p.perm.info.group == null) {
3387                        out.add(generatePermissionInfo(p, flags));
3388                    }
3389                } else {
3390                    if (p.perm != null && group.equals(p.perm.info.group)) {
3391                        out.add(PackageParser.generatePermissionInfo(p.perm, flags));
3392                    }
3393                }
3394            }
3395            return new ParceledListSlice<>(out);
3396        }
3397    }
3398
3399    @Override
3400    public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
3401        // reader
3402        synchronized (mPackages) {
3403            return PackageParser.generatePermissionGroupInfo(
3404                    mPermissionGroups.get(name), flags);
3405        }
3406    }
3407
3408    @Override
3409    public @NonNull ParceledListSlice<PermissionGroupInfo> getAllPermissionGroups(int flags) {
3410        // reader
3411        synchronized (mPackages) {
3412            final int N = mPermissionGroups.size();
3413            ArrayList<PermissionGroupInfo> out
3414                    = new ArrayList<PermissionGroupInfo>(N);
3415            for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
3416                out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
3417            }
3418            return new ParceledListSlice<>(out);
3419        }
3420    }
3421
3422    private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
3423            int userId) {
3424        if (!sUserManager.exists(userId)) return null;
3425        PackageSetting ps = mSettings.mPackages.get(packageName);
3426        if (ps != null) {
3427            if (ps.pkg == null) {
3428                final PackageInfo pInfo = generatePackageInfo(ps, flags, userId);
3429                if (pInfo != null) {
3430                    return pInfo.applicationInfo;
3431                }
3432                return null;
3433            }
3434            return PackageParser.generateApplicationInfo(ps.pkg, flags,
3435                    ps.readUserState(userId), userId);
3436        }
3437        return null;
3438    }
3439
3440    @Override
3441    public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
3442        if (!sUserManager.exists(userId)) return null;
3443        flags = updateFlagsForApplication(flags, userId, packageName);
3444        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3445                false /* requireFullPermission */, false /* checkShell */, "get application info");
3446        // writer
3447        synchronized (mPackages) {
3448            PackageParser.Package p = mPackages.get(packageName);
3449            if (DEBUG_PACKAGE_INFO) Log.v(
3450                    TAG, "getApplicationInfo " + packageName
3451                    + ": " + p);
3452            if (p != null) {
3453                PackageSetting ps = mSettings.mPackages.get(packageName);
3454                if (ps == null) return null;
3455                // Note: isEnabledLP() does not apply here - always return info
3456                return PackageParser.generateApplicationInfo(
3457                        p, flags, ps.readUserState(userId), userId);
3458            }
3459            if ("android".equals(packageName)||"system".equals(packageName)) {
3460                return mAndroidApplication;
3461            }
3462            if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) {
3463                return generateApplicationInfoFromSettingsLPw(packageName, flags, userId);
3464            }
3465        }
3466        return null;
3467    }
3468
3469    @Override
3470    public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize,
3471            final IPackageDataObserver observer) {
3472        mContext.enforceCallingOrSelfPermission(
3473                android.Manifest.permission.CLEAR_APP_CACHE, null);
3474        // Queue up an async operation since clearing cache may take a little while.
3475        mHandler.post(new Runnable() {
3476            public void run() {
3477                mHandler.removeCallbacks(this);
3478                boolean success = true;
3479                synchronized (mInstallLock) {
3480                    try {
3481                        mInstaller.freeCache(volumeUuid, freeStorageSize);
3482                    } catch (InstallerException e) {
3483                        Slog.w(TAG, "Couldn't clear application caches: " + e);
3484                        success = false;
3485                    }
3486                }
3487                if (observer != null) {
3488                    try {
3489                        observer.onRemoveCompleted(null, success);
3490                    } catch (RemoteException e) {
3491                        Slog.w(TAG, "RemoveException when invoking call back");
3492                    }
3493                }
3494            }
3495        });
3496    }
3497
3498    @Override
3499    public void freeStorage(final String volumeUuid, final long freeStorageSize,
3500            final IntentSender pi) {
3501        mContext.enforceCallingOrSelfPermission(
3502                android.Manifest.permission.CLEAR_APP_CACHE, null);
3503        // Queue up an async operation since clearing cache may take a little while.
3504        mHandler.post(new Runnable() {
3505            public void run() {
3506                mHandler.removeCallbacks(this);
3507                boolean success = true;
3508                synchronized (mInstallLock) {
3509                    try {
3510                        mInstaller.freeCache(volumeUuid, freeStorageSize);
3511                    } catch (InstallerException e) {
3512                        Slog.w(TAG, "Couldn't clear application caches: " + e);
3513                        success = false;
3514                    }
3515                }
3516                if(pi != null) {
3517                    try {
3518                        // Callback via pending intent
3519                        int code = success ? 1 : 0;
3520                        pi.sendIntent(null, code, null,
3521                                null, null);
3522                    } catch (SendIntentException e1) {
3523                        Slog.i(TAG, "Failed to send pending intent");
3524                    }
3525                }
3526            }
3527        });
3528    }
3529
3530    void freeStorage(String volumeUuid, long freeStorageSize) throws IOException {
3531        synchronized (mInstallLock) {
3532            try {
3533                mInstaller.freeCache(volumeUuid, freeStorageSize);
3534            } catch (InstallerException e) {
3535                throw new IOException("Failed to free enough space", e);
3536            }
3537        }
3538    }
3539
3540    /**
3541     * Update given flags based on encryption status of current user.
3542     */
3543    private int updateFlags(int flags, int userId) {
3544        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
3545                | PackageManager.MATCH_DIRECT_BOOT_AWARE)) != 0) {
3546            // Caller expressed an explicit opinion about what encryption
3547            // aware/unaware components they want to see, so fall through and
3548            // give them what they want
3549        } else {
3550            // Caller expressed no opinion, so match based on user state
3551            if (getUserManagerInternal().isUserUnlockingOrUnlocked(userId)) {
3552                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE;
3553            } else {
3554                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE;
3555            }
3556        }
3557        return flags;
3558    }
3559
3560    private UserManagerInternal getUserManagerInternal() {
3561        if (mUserManagerInternal == null) {
3562            mUserManagerInternal = LocalServices.getService(UserManagerInternal.class);
3563        }
3564        return mUserManagerInternal;
3565    }
3566
3567    /**
3568     * Update given flags when being used to request {@link PackageInfo}.
3569     */
3570    private int updateFlagsForPackage(int flags, int userId, Object cookie) {
3571        boolean triaged = true;
3572        if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS
3573                | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) {
3574            // Caller is asking for component details, so they'd better be
3575            // asking for specific encryption matching behavior, or be triaged
3576            if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
3577                    | PackageManager.MATCH_DIRECT_BOOT_AWARE
3578                    | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
3579                triaged = false;
3580            }
3581        }
3582        if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES
3583                | PackageManager.MATCH_SYSTEM_ONLY
3584                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
3585            triaged = false;
3586        }
3587        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
3588            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
3589                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
3590        }
3591        return updateFlags(flags, userId);
3592    }
3593
3594    /**
3595     * Update given flags when being used to request {@link ApplicationInfo}.
3596     */
3597    private int updateFlagsForApplication(int flags, int userId, Object cookie) {
3598        return updateFlagsForPackage(flags, userId, cookie);
3599    }
3600
3601    /**
3602     * Update given flags when being used to request {@link ComponentInfo}.
3603     */
3604    private int updateFlagsForComponent(int flags, int userId, Object cookie) {
3605        if (cookie instanceof Intent) {
3606            if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) {
3607                flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
3608            }
3609        }
3610
3611        boolean triaged = true;
3612        // Caller is asking for component details, so they'd better be
3613        // asking for specific encryption matching behavior, or be triaged
3614        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
3615                | PackageManager.MATCH_DIRECT_BOOT_AWARE
3616                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
3617            triaged = false;
3618        }
3619        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
3620            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
3621                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
3622        }
3623
3624        return updateFlags(flags, userId);
3625    }
3626
3627    /**
3628     * Update given flags when being used to request {@link ResolveInfo}.
3629     */
3630    int updateFlagsForResolve(int flags, int userId, Object cookie) {
3631        // Safe mode means we shouldn't match any third-party components
3632        if (mSafeMode) {
3633            flags |= PackageManager.MATCH_SYSTEM_ONLY;
3634        }
3635
3636        return updateFlagsForComponent(flags, userId, cookie);
3637    }
3638
3639    @Override
3640    public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
3641        if (!sUserManager.exists(userId)) return null;
3642        flags = updateFlagsForComponent(flags, userId, component);
3643        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3644                false /* requireFullPermission */, false /* checkShell */, "get activity info");
3645        synchronized (mPackages) {
3646            PackageParser.Activity a = mActivities.mActivities.get(component);
3647
3648            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
3649            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
3650                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3651                if (ps == null) return null;
3652                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
3653                        userId);
3654            }
3655            if (mResolveComponentName.equals(component)) {
3656                return PackageParser.generateActivityInfo(mResolveActivity, flags,
3657                        new PackageUserState(), userId);
3658            }
3659        }
3660        return null;
3661    }
3662
3663    @Override
3664    public boolean activitySupportsIntent(ComponentName component, Intent intent,
3665            String resolvedType) {
3666        synchronized (mPackages) {
3667            if (component.equals(mResolveComponentName)) {
3668                // The resolver supports EVERYTHING!
3669                return true;
3670            }
3671            PackageParser.Activity a = mActivities.mActivities.get(component);
3672            if (a == null) {
3673                return false;
3674            }
3675            for (int i=0; i<a.intents.size(); i++) {
3676                if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
3677                        intent.getData(), intent.getCategories(), TAG) >= 0) {
3678                    return true;
3679                }
3680            }
3681            return false;
3682        }
3683    }
3684
3685    @Override
3686    public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
3687        if (!sUserManager.exists(userId)) return null;
3688        flags = updateFlagsForComponent(flags, userId, component);
3689        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3690                false /* requireFullPermission */, false /* checkShell */, "get receiver info");
3691        synchronized (mPackages) {
3692            PackageParser.Activity a = mReceivers.mActivities.get(component);
3693            if (DEBUG_PACKAGE_INFO) Log.v(
3694                TAG, "getReceiverInfo " + component + ": " + a);
3695            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
3696                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3697                if (ps == null) return null;
3698                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
3699                        userId);
3700            }
3701        }
3702        return null;
3703    }
3704
3705    @Override
3706    public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
3707        if (!sUserManager.exists(userId)) return null;
3708        flags = updateFlagsForComponent(flags, userId, component);
3709        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3710                false /* requireFullPermission */, false /* checkShell */, "get service info");
3711        synchronized (mPackages) {
3712            PackageParser.Service s = mServices.mServices.get(component);
3713            if (DEBUG_PACKAGE_INFO) Log.v(
3714                TAG, "getServiceInfo " + component + ": " + s);
3715            if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) {
3716                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3717                if (ps == null) return null;
3718                return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId),
3719                        userId);
3720            }
3721        }
3722        return null;
3723    }
3724
3725    @Override
3726    public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
3727        if (!sUserManager.exists(userId)) return null;
3728        flags = updateFlagsForComponent(flags, userId, component);
3729        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3730                false /* requireFullPermission */, false /* checkShell */, "get provider info");
3731        synchronized (mPackages) {
3732            PackageParser.Provider p = mProviders.mProviders.get(component);
3733            if (DEBUG_PACKAGE_INFO) Log.v(
3734                TAG, "getProviderInfo " + component + ": " + p);
3735            if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
3736                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3737                if (ps == null) return null;
3738                return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId),
3739                        userId);
3740            }
3741        }
3742        return null;
3743    }
3744
3745    @Override
3746    public String[] getSystemSharedLibraryNames() {
3747        Set<String> libSet;
3748        synchronized (mPackages) {
3749            libSet = mSharedLibraries.keySet();
3750            int size = libSet.size();
3751            if (size > 0) {
3752                String[] libs = new String[size];
3753                libSet.toArray(libs);
3754                return libs;
3755            }
3756        }
3757        return null;
3758    }
3759
3760    @Override
3761    public @NonNull String getServicesSystemSharedLibraryPackageName() {
3762        synchronized (mPackages) {
3763            return mServicesSystemSharedLibraryPackageName;
3764        }
3765    }
3766
3767    @Override
3768    public @NonNull String getSharedSystemSharedLibraryPackageName() {
3769        synchronized (mPackages) {
3770            return mSharedSystemSharedLibraryPackageName;
3771        }
3772    }
3773
3774    @Override
3775    public @NonNull ParceledListSlice<FeatureInfo> getSystemAvailableFeatures() {
3776        synchronized (mPackages) {
3777            final ArrayList<FeatureInfo> res = new ArrayList<>(mAvailableFeatures.values());
3778
3779            final FeatureInfo fi = new FeatureInfo();
3780            fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
3781                    FeatureInfo.GL_ES_VERSION_UNDEFINED);
3782            res.add(fi);
3783
3784            return new ParceledListSlice<>(res);
3785        }
3786    }
3787
3788    @Override
3789    public boolean hasSystemFeature(String name, int version) {
3790        synchronized (mPackages) {
3791            final FeatureInfo feat = mAvailableFeatures.get(name);
3792            if (feat == null) {
3793                return false;
3794            } else {
3795                return feat.version >= version;
3796            }
3797        }
3798    }
3799
3800    @Override
3801    public int checkPermission(String permName, String pkgName, int userId) {
3802        if (!sUserManager.exists(userId)) {
3803            return PackageManager.PERMISSION_DENIED;
3804        }
3805
3806        synchronized (mPackages) {
3807            final PackageParser.Package p = mPackages.get(pkgName);
3808            if (p != null && p.mExtras != null) {
3809                final PackageSetting ps = (PackageSetting) p.mExtras;
3810                final PermissionsState permissionsState = ps.getPermissionsState();
3811                if (permissionsState.hasPermission(permName, userId)) {
3812                    return PackageManager.PERMISSION_GRANTED;
3813                }
3814                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
3815                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
3816                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
3817                    return PackageManager.PERMISSION_GRANTED;
3818                }
3819            }
3820        }
3821
3822        return PackageManager.PERMISSION_DENIED;
3823    }
3824
3825    @Override
3826    public int checkUidPermission(String permName, int uid) {
3827        final int userId = UserHandle.getUserId(uid);
3828
3829        if (!sUserManager.exists(userId)) {
3830            return PackageManager.PERMISSION_DENIED;
3831        }
3832
3833        synchronized (mPackages) {
3834            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
3835            if (obj != null) {
3836                final SettingBase ps = (SettingBase) obj;
3837                final PermissionsState permissionsState = ps.getPermissionsState();
3838                if (permissionsState.hasPermission(permName, userId)) {
3839                    return PackageManager.PERMISSION_GRANTED;
3840                }
3841                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
3842                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
3843                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
3844                    return PackageManager.PERMISSION_GRANTED;
3845                }
3846            } else {
3847                ArraySet<String> perms = mSystemPermissions.get(uid);
3848                if (perms != null) {
3849                    if (perms.contains(permName)) {
3850                        return PackageManager.PERMISSION_GRANTED;
3851                    }
3852                    if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms
3853                            .contains(Manifest.permission.ACCESS_FINE_LOCATION)) {
3854                        return PackageManager.PERMISSION_GRANTED;
3855                    }
3856                }
3857            }
3858        }
3859
3860        return PackageManager.PERMISSION_DENIED;
3861    }
3862
3863    @Override
3864    public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) {
3865        if (UserHandle.getCallingUserId() != userId) {
3866            mContext.enforceCallingPermission(
3867                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
3868                    "isPermissionRevokedByPolicy for user " + userId);
3869        }
3870
3871        if (checkPermission(permission, packageName, userId)
3872                == PackageManager.PERMISSION_GRANTED) {
3873            return false;
3874        }
3875
3876        final long identity = Binder.clearCallingIdentity();
3877        try {
3878            final int flags = getPermissionFlags(permission, packageName, userId);
3879            return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0;
3880        } finally {
3881            Binder.restoreCallingIdentity(identity);
3882        }
3883    }
3884
3885    @Override
3886    public String getPermissionControllerPackageName() {
3887        synchronized (mPackages) {
3888            return mRequiredInstallerPackage;
3889        }
3890    }
3891
3892    /**
3893     * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS
3894     * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller.
3895     * @param checkShell whether to prevent shell from access if there's a debugging restriction
3896     * @param message the message to log on security exception
3897     */
3898    void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission,
3899            boolean checkShell, String message) {
3900        if (userId < 0) {
3901            throw new IllegalArgumentException("Invalid userId " + userId);
3902        }
3903        if (checkShell) {
3904            enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId);
3905        }
3906        if (userId == UserHandle.getUserId(callingUid)) return;
3907        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
3908            if (requireFullPermission) {
3909                mContext.enforceCallingOrSelfPermission(
3910                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
3911            } else {
3912                try {
3913                    mContext.enforceCallingOrSelfPermission(
3914                            android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
3915                } catch (SecurityException se) {
3916                    mContext.enforceCallingOrSelfPermission(
3917                            android.Manifest.permission.INTERACT_ACROSS_USERS, message);
3918                }
3919            }
3920        }
3921    }
3922
3923    void enforceShellRestriction(String restriction, int callingUid, int userHandle) {
3924        if (callingUid == Process.SHELL_UID) {
3925            if (userHandle >= 0
3926                    && sUserManager.hasUserRestriction(restriction, userHandle)) {
3927                throw new SecurityException("Shell does not have permission to access user "
3928                        + userHandle);
3929            } else if (userHandle < 0) {
3930                Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t"
3931                        + Debug.getCallers(3));
3932            }
3933        }
3934    }
3935
3936    private BasePermission findPermissionTreeLP(String permName) {
3937        for(BasePermission bp : mSettings.mPermissionTrees.values()) {
3938            if (permName.startsWith(bp.name) &&
3939                    permName.length() > bp.name.length() &&
3940                    permName.charAt(bp.name.length()) == '.') {
3941                return bp;
3942            }
3943        }
3944        return null;
3945    }
3946
3947    private BasePermission checkPermissionTreeLP(String permName) {
3948        if (permName != null) {
3949            BasePermission bp = findPermissionTreeLP(permName);
3950            if (bp != null) {
3951                if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) {
3952                    return bp;
3953                }
3954                throw new SecurityException("Calling uid "
3955                        + Binder.getCallingUid()
3956                        + " is not allowed to add to permission tree "
3957                        + bp.name + " owned by uid " + bp.uid);
3958            }
3959        }
3960        throw new SecurityException("No permission tree found for " + permName);
3961    }
3962
3963    static boolean compareStrings(CharSequence s1, CharSequence s2) {
3964        if (s1 == null) {
3965            return s2 == null;
3966        }
3967        if (s2 == null) {
3968            return false;
3969        }
3970        if (s1.getClass() != s2.getClass()) {
3971            return false;
3972        }
3973        return s1.equals(s2);
3974    }
3975
3976    static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
3977        if (pi1.icon != pi2.icon) return false;
3978        if (pi1.logo != pi2.logo) return false;
3979        if (pi1.protectionLevel != pi2.protectionLevel) return false;
3980        if (!compareStrings(pi1.name, pi2.name)) return false;
3981        if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
3982        // We'll take care of setting this one.
3983        if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
3984        // These are not currently stored in settings.
3985        //if (!compareStrings(pi1.group, pi2.group)) return false;
3986        //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
3987        //if (pi1.labelRes != pi2.labelRes) return false;
3988        //if (pi1.descriptionRes != pi2.descriptionRes) return false;
3989        return true;
3990    }
3991
3992    int permissionInfoFootprint(PermissionInfo info) {
3993        int size = info.name.length();
3994        if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length();
3995        if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length();
3996        return size;
3997    }
3998
3999    int calculateCurrentPermissionFootprintLocked(BasePermission tree) {
4000        int size = 0;
4001        for (BasePermission perm : mSettings.mPermissions.values()) {
4002            if (perm.uid == tree.uid) {
4003                size += perm.name.length() + permissionInfoFootprint(perm.perm.info);
4004            }
4005        }
4006        return size;
4007    }
4008
4009    void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) {
4010        // We calculate the max size of permissions defined by this uid and throw
4011        // if that plus the size of 'info' would exceed our stated maximum.
4012        if (tree.uid != Process.SYSTEM_UID) {
4013            final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree);
4014            if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) {
4015                throw new SecurityException("Permission tree size cap exceeded");
4016            }
4017        }
4018    }
4019
4020    boolean addPermissionLocked(PermissionInfo info, boolean async) {
4021        if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
4022            throw new SecurityException("Label must be specified in permission");
4023        }
4024        BasePermission tree = checkPermissionTreeLP(info.name);
4025        BasePermission bp = mSettings.mPermissions.get(info.name);
4026        boolean added = bp == null;
4027        boolean changed = true;
4028        int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel);
4029        if (added) {
4030            enforcePermissionCapLocked(info, tree);
4031            bp = new BasePermission(info.name, tree.sourcePackage,
4032                    BasePermission.TYPE_DYNAMIC);
4033        } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
4034            throw new SecurityException(
4035                    "Not allowed to modify non-dynamic permission "
4036                    + info.name);
4037        } else {
4038            if (bp.protectionLevel == fixedLevel
4039                    && bp.perm.owner.equals(tree.perm.owner)
4040                    && bp.uid == tree.uid
4041                    && comparePermissionInfos(bp.perm.info, info)) {
4042                changed = false;
4043            }
4044        }
4045        bp.protectionLevel = fixedLevel;
4046        info = new PermissionInfo(info);
4047        info.protectionLevel = fixedLevel;
4048        bp.perm = new PackageParser.Permission(tree.perm.owner, info);
4049        bp.perm.info.packageName = tree.perm.info.packageName;
4050        bp.uid = tree.uid;
4051        if (added) {
4052            mSettings.mPermissions.put(info.name, bp);
4053        }
4054        if (changed) {
4055            if (!async) {
4056                mSettings.writeLPr();
4057            } else {
4058                scheduleWriteSettingsLocked();
4059            }
4060        }
4061        return added;
4062    }
4063
4064    @Override
4065    public boolean addPermission(PermissionInfo info) {
4066        synchronized (mPackages) {
4067            return addPermissionLocked(info, false);
4068        }
4069    }
4070
4071    @Override
4072    public boolean addPermissionAsync(PermissionInfo info) {
4073        synchronized (mPackages) {
4074            return addPermissionLocked(info, true);
4075        }
4076    }
4077
4078    @Override
4079    public void removePermission(String name) {
4080        synchronized (mPackages) {
4081            checkPermissionTreeLP(name);
4082            BasePermission bp = mSettings.mPermissions.get(name);
4083            if (bp != null) {
4084                if (bp.type != BasePermission.TYPE_DYNAMIC) {
4085                    throw new SecurityException(
4086                            "Not allowed to modify non-dynamic permission "
4087                            + name);
4088                }
4089                mSettings.mPermissions.remove(name);
4090                mSettings.writeLPr();
4091            }
4092        }
4093    }
4094
4095    private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(PackageParser.Package pkg,
4096            BasePermission bp) {
4097        int index = pkg.requestedPermissions.indexOf(bp.name);
4098        if (index == -1) {
4099            throw new SecurityException("Package " + pkg.packageName
4100                    + " has not requested permission " + bp.name);
4101        }
4102        if (!bp.isRuntime() && !bp.isDevelopment()) {
4103            throw new SecurityException("Permission " + bp.name
4104                    + " is not a changeable permission type");
4105        }
4106    }
4107
4108    @Override
4109    public void grantRuntimePermission(String packageName, String name, final int userId) {
4110        if (!sUserManager.exists(userId)) {
4111            Log.e(TAG, "No such user:" + userId);
4112            return;
4113        }
4114
4115        mContext.enforceCallingOrSelfPermission(
4116                android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
4117                "grantRuntimePermission");
4118
4119        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4120                true /* requireFullPermission */, true /* checkShell */,
4121                "grantRuntimePermission");
4122
4123        final int uid;
4124        final SettingBase sb;
4125
4126        synchronized (mPackages) {
4127            final PackageParser.Package pkg = mPackages.get(packageName);
4128            if (pkg == null) {
4129                throw new IllegalArgumentException("Unknown package: " + packageName);
4130            }
4131
4132            final BasePermission bp = mSettings.mPermissions.get(name);
4133            if (bp == null) {
4134                throw new IllegalArgumentException("Unknown permission: " + name);
4135            }
4136
4137            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
4138
4139            // If a permission review is required for legacy apps we represent
4140            // their permissions as always granted runtime ones since we need
4141            // to keep the review required permission flag per user while an
4142            // install permission's state is shared across all users.
4143            if (Build.PERMISSIONS_REVIEW_REQUIRED
4144                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
4145                    && bp.isRuntime()) {
4146                return;
4147            }
4148
4149            uid = UserHandle.getUid(userId, pkg.applicationInfo.uid);
4150            sb = (SettingBase) pkg.mExtras;
4151            if (sb == null) {
4152                throw new IllegalArgumentException("Unknown package: " + packageName);
4153            }
4154
4155            final PermissionsState permissionsState = sb.getPermissionsState();
4156
4157            final int flags = permissionsState.getPermissionFlags(name, userId);
4158            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
4159                throw new SecurityException("Cannot grant system fixed permission "
4160                        + name + " for package " + packageName);
4161            }
4162
4163            if (bp.isDevelopment()) {
4164                // Development permissions must be handled specially, since they are not
4165                // normal runtime permissions.  For now they apply to all users.
4166                if (permissionsState.grantInstallPermission(bp) !=
4167                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
4168                    scheduleWriteSettingsLocked();
4169                }
4170                return;
4171            }
4172
4173            if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
4174                Slog.w(TAG, "Cannot grant runtime permission to a legacy app");
4175                return;
4176            }
4177
4178            final int result = permissionsState.grantRuntimePermission(bp, userId);
4179            switch (result) {
4180                case PermissionsState.PERMISSION_OPERATION_FAILURE: {
4181                    return;
4182                }
4183
4184                case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
4185                    final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
4186                    mHandler.post(new Runnable() {
4187                        @Override
4188                        public void run() {
4189                            killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED);
4190                        }
4191                    });
4192                }
4193                break;
4194            }
4195
4196            mOnPermissionChangeListeners.onPermissionsChanged(uid);
4197
4198            // Not critical if that is lost - app has to request again.
4199            mSettings.writeRuntimePermissionsForUserLPr(userId, false);
4200        }
4201
4202        // Only need to do this if user is initialized. Otherwise it's a new user
4203        // and there are no processes running as the user yet and there's no need
4204        // to make an expensive call to remount processes for the changed permissions.
4205        if (READ_EXTERNAL_STORAGE.equals(name)
4206                || WRITE_EXTERNAL_STORAGE.equals(name)) {
4207            final long token = Binder.clearCallingIdentity();
4208            try {
4209                if (sUserManager.isInitialized(userId)) {
4210                    MountServiceInternal mountServiceInternal = LocalServices.getService(
4211                            MountServiceInternal.class);
4212                    mountServiceInternal.onExternalStoragePolicyChanged(uid, packageName);
4213                }
4214            } finally {
4215                Binder.restoreCallingIdentity(token);
4216            }
4217        }
4218    }
4219
4220    @Override
4221    public void revokeRuntimePermission(String packageName, String name, int userId) {
4222        if (!sUserManager.exists(userId)) {
4223            Log.e(TAG, "No such user:" + userId);
4224            return;
4225        }
4226
4227        mContext.enforceCallingOrSelfPermission(
4228                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
4229                "revokeRuntimePermission");
4230
4231        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4232                true /* requireFullPermission */, true /* checkShell */,
4233                "revokeRuntimePermission");
4234
4235        final int appId;
4236
4237        synchronized (mPackages) {
4238            final PackageParser.Package pkg = mPackages.get(packageName);
4239            if (pkg == null) {
4240                throw new IllegalArgumentException("Unknown package: " + packageName);
4241            }
4242
4243            final BasePermission bp = mSettings.mPermissions.get(name);
4244            if (bp == null) {
4245                throw new IllegalArgumentException("Unknown permission: " + name);
4246            }
4247
4248            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
4249
4250            // If a permission review is required for legacy apps we represent
4251            // their permissions as always granted runtime ones since we need
4252            // to keep the review required permission flag per user while an
4253            // install permission's state is shared across all users.
4254            if (Build.PERMISSIONS_REVIEW_REQUIRED
4255                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
4256                    && bp.isRuntime()) {
4257                return;
4258            }
4259
4260            SettingBase sb = (SettingBase) pkg.mExtras;
4261            if (sb == null) {
4262                throw new IllegalArgumentException("Unknown package: " + packageName);
4263            }
4264
4265            final PermissionsState permissionsState = sb.getPermissionsState();
4266
4267            final int flags = permissionsState.getPermissionFlags(name, userId);
4268            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
4269                throw new SecurityException("Cannot revoke system fixed permission "
4270                        + name + " for package " + packageName);
4271            }
4272
4273            if (bp.isDevelopment()) {
4274                // Development permissions must be handled specially, since they are not
4275                // normal runtime permissions.  For now they apply to all users.
4276                if (permissionsState.revokeInstallPermission(bp) !=
4277                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
4278                    scheduleWriteSettingsLocked();
4279                }
4280                return;
4281            }
4282
4283            if (permissionsState.revokeRuntimePermission(bp, userId) ==
4284                    PermissionsState.PERMISSION_OPERATION_FAILURE) {
4285                return;
4286            }
4287
4288            mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid);
4289
4290            // Critical, after this call app should never have the permission.
4291            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
4292
4293            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
4294        }
4295
4296        killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
4297    }
4298
4299    @Override
4300    public void resetRuntimePermissions() {
4301        mContext.enforceCallingOrSelfPermission(
4302                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
4303                "revokeRuntimePermission");
4304
4305        int callingUid = Binder.getCallingUid();
4306        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
4307            mContext.enforceCallingOrSelfPermission(
4308                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
4309                    "resetRuntimePermissions");
4310        }
4311
4312        synchronized (mPackages) {
4313            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL);
4314            for (int userId : UserManagerService.getInstance().getUserIds()) {
4315                final int packageCount = mPackages.size();
4316                for (int i = 0; i < packageCount; i++) {
4317                    PackageParser.Package pkg = mPackages.valueAt(i);
4318                    if (!(pkg.mExtras instanceof PackageSetting)) {
4319                        continue;
4320                    }
4321                    PackageSetting ps = (PackageSetting) pkg.mExtras;
4322                    resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
4323                }
4324            }
4325        }
4326    }
4327
4328    @Override
4329    public int getPermissionFlags(String name, String packageName, int userId) {
4330        if (!sUserManager.exists(userId)) {
4331            return 0;
4332        }
4333
4334        enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags");
4335
4336        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4337                true /* requireFullPermission */, false /* checkShell */,
4338                "getPermissionFlags");
4339
4340        synchronized (mPackages) {
4341            final PackageParser.Package pkg = mPackages.get(packageName);
4342            if (pkg == null) {
4343                return 0;
4344            }
4345
4346            final BasePermission bp = mSettings.mPermissions.get(name);
4347            if (bp == null) {
4348                return 0;
4349            }
4350
4351            SettingBase sb = (SettingBase) pkg.mExtras;
4352            if (sb == null) {
4353                return 0;
4354            }
4355
4356            PermissionsState permissionsState = sb.getPermissionsState();
4357            return permissionsState.getPermissionFlags(name, userId);
4358        }
4359    }
4360
4361    @Override
4362    public void updatePermissionFlags(String name, String packageName, int flagMask,
4363            int flagValues, int userId) {
4364        if (!sUserManager.exists(userId)) {
4365            return;
4366        }
4367
4368        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags");
4369
4370        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4371                true /* requireFullPermission */, true /* checkShell */,
4372                "updatePermissionFlags");
4373
4374        // Only the system can change these flags and nothing else.
4375        if (getCallingUid() != Process.SYSTEM_UID) {
4376            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4377            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4378            flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
4379            flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
4380            flagValues &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
4381        }
4382
4383        synchronized (mPackages) {
4384            final PackageParser.Package pkg = mPackages.get(packageName);
4385            if (pkg == null) {
4386                throw new IllegalArgumentException("Unknown package: " + packageName);
4387            }
4388
4389            final BasePermission bp = mSettings.mPermissions.get(name);
4390            if (bp == null) {
4391                throw new IllegalArgumentException("Unknown permission: " + name);
4392            }
4393
4394            SettingBase sb = (SettingBase) pkg.mExtras;
4395            if (sb == null) {
4396                throw new IllegalArgumentException("Unknown package: " + packageName);
4397            }
4398
4399            PermissionsState permissionsState = sb.getPermissionsState();
4400
4401            boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null;
4402
4403            if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) {
4404                // Install and runtime permissions are stored in different places,
4405                // so figure out what permission changed and persist the change.
4406                if (permissionsState.getInstallPermissionState(name) != null) {
4407                    scheduleWriteSettingsLocked();
4408                } else if (permissionsState.getRuntimePermissionState(name, userId) != null
4409                        || hadState) {
4410                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
4411                }
4412            }
4413        }
4414    }
4415
4416    /**
4417     * Update the permission flags for all packages and runtime permissions of a user in order
4418     * to allow device or profile owner to remove POLICY_FIXED.
4419     */
4420    @Override
4421    public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) {
4422        if (!sUserManager.exists(userId)) {
4423            return;
4424        }
4425
4426        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps");
4427
4428        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4429                true /* requireFullPermission */, true /* checkShell */,
4430                "updatePermissionFlagsForAllApps");
4431
4432        // Only the system can change system fixed flags.
4433        if (getCallingUid() != Process.SYSTEM_UID) {
4434            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4435            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4436        }
4437
4438        synchronized (mPackages) {
4439            boolean changed = false;
4440            final int packageCount = mPackages.size();
4441            for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) {
4442                final PackageParser.Package pkg = mPackages.valueAt(pkgIndex);
4443                SettingBase sb = (SettingBase) pkg.mExtras;
4444                if (sb == null) {
4445                    continue;
4446                }
4447                PermissionsState permissionsState = sb.getPermissionsState();
4448                changed |= permissionsState.updatePermissionFlagsForAllPermissions(
4449                        userId, flagMask, flagValues);
4450            }
4451            if (changed) {
4452                mSettings.writeRuntimePermissionsForUserLPr(userId, false);
4453            }
4454        }
4455    }
4456
4457    private void enforceGrantRevokeRuntimePermissionPermissions(String message) {
4458        if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS)
4459                != PackageManager.PERMISSION_GRANTED
4460            && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS)
4461                != PackageManager.PERMISSION_GRANTED) {
4462            throw new SecurityException(message + " requires "
4463                    + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or "
4464                    + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS);
4465        }
4466    }
4467
4468    @Override
4469    public boolean shouldShowRequestPermissionRationale(String permissionName,
4470            String packageName, int userId) {
4471        if (UserHandle.getCallingUserId() != userId) {
4472            mContext.enforceCallingPermission(
4473                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
4474                    "canShowRequestPermissionRationale for user " + userId);
4475        }
4476
4477        final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId);
4478        if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) {
4479            return false;
4480        }
4481
4482        if (checkPermission(permissionName, packageName, userId)
4483                == PackageManager.PERMISSION_GRANTED) {
4484            return false;
4485        }
4486
4487        final int flags;
4488
4489        final long identity = Binder.clearCallingIdentity();
4490        try {
4491            flags = getPermissionFlags(permissionName,
4492                    packageName, userId);
4493        } finally {
4494            Binder.restoreCallingIdentity(identity);
4495        }
4496
4497        final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
4498                | PackageManager.FLAG_PERMISSION_POLICY_FIXED
4499                | PackageManager.FLAG_PERMISSION_USER_FIXED;
4500
4501        if ((flags & fixedFlags) != 0) {
4502            return false;
4503        }
4504
4505        return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0;
4506    }
4507
4508    @Override
4509    public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
4510        mContext.enforceCallingOrSelfPermission(
4511                Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS,
4512                "addOnPermissionsChangeListener");
4513
4514        synchronized (mPackages) {
4515            mOnPermissionChangeListeners.addListenerLocked(listener);
4516        }
4517    }
4518
4519    @Override
4520    public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
4521        synchronized (mPackages) {
4522            mOnPermissionChangeListeners.removeListenerLocked(listener);
4523        }
4524    }
4525
4526    @Override
4527    public boolean isProtectedBroadcast(String actionName) {
4528        synchronized (mPackages) {
4529            if (mProtectedBroadcasts.contains(actionName)) {
4530                return true;
4531            } else if (actionName != null) {
4532                // TODO: remove these terrible hacks
4533                if (actionName.startsWith("android.net.netmon.lingerExpired")
4534                        || actionName.startsWith("com.android.server.sip.SipWakeupTimer")
4535                        || actionName.startsWith("com.android.internal.telephony.data-reconnect")
4536                        || actionName.startsWith("android.net.netmon.launchCaptivePortalApp")) {
4537                    return true;
4538                }
4539            }
4540        }
4541        return false;
4542    }
4543
4544    @Override
4545    public int checkSignatures(String pkg1, String pkg2) {
4546        synchronized (mPackages) {
4547            final PackageParser.Package p1 = mPackages.get(pkg1);
4548            final PackageParser.Package p2 = mPackages.get(pkg2);
4549            if (p1 == null || p1.mExtras == null
4550                    || p2 == null || p2.mExtras == null) {
4551                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4552            }
4553            return compareSignatures(p1.mSignatures, p2.mSignatures);
4554        }
4555    }
4556
4557    @Override
4558    public int checkUidSignatures(int uid1, int uid2) {
4559        // Map to base uids.
4560        uid1 = UserHandle.getAppId(uid1);
4561        uid2 = UserHandle.getAppId(uid2);
4562        // reader
4563        synchronized (mPackages) {
4564            Signature[] s1;
4565            Signature[] s2;
4566            Object obj = mSettings.getUserIdLPr(uid1);
4567            if (obj != null) {
4568                if (obj instanceof SharedUserSetting) {
4569                    s1 = ((SharedUserSetting)obj).signatures.mSignatures;
4570                } else if (obj instanceof PackageSetting) {
4571                    s1 = ((PackageSetting)obj).signatures.mSignatures;
4572                } else {
4573                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4574                }
4575            } else {
4576                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4577            }
4578            obj = mSettings.getUserIdLPr(uid2);
4579            if (obj != null) {
4580                if (obj instanceof SharedUserSetting) {
4581                    s2 = ((SharedUserSetting)obj).signatures.mSignatures;
4582                } else if (obj instanceof PackageSetting) {
4583                    s2 = ((PackageSetting)obj).signatures.mSignatures;
4584                } else {
4585                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4586                }
4587            } else {
4588                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4589            }
4590            return compareSignatures(s1, s2);
4591        }
4592    }
4593
4594    /**
4595     * This method should typically only be used when granting or revoking
4596     * permissions, since the app may immediately restart after this call.
4597     * <p>
4598     * If you're doing surgery on app code/data, use {@link PackageFreezer} to
4599     * guard your work against the app being relaunched.
4600     */
4601    private void killUid(int appId, int userId, String reason) {
4602        final long identity = Binder.clearCallingIdentity();
4603        try {
4604            IActivityManager am = ActivityManagerNative.getDefault();
4605            if (am != null) {
4606                try {
4607                    am.killUid(appId, userId, reason);
4608                } catch (RemoteException e) {
4609                    /* ignore - same process */
4610                }
4611            }
4612        } finally {
4613            Binder.restoreCallingIdentity(identity);
4614        }
4615    }
4616
4617    /**
4618     * Compares two sets of signatures. Returns:
4619     * <br />
4620     * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null,
4621     * <br />
4622     * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null,
4623     * <br />
4624     * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null,
4625     * <br />
4626     * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical,
4627     * <br />
4628     * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ.
4629     */
4630    static int compareSignatures(Signature[] s1, Signature[] s2) {
4631        if (s1 == null) {
4632            return s2 == null
4633                    ? PackageManager.SIGNATURE_NEITHER_SIGNED
4634                    : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
4635        }
4636
4637        if (s2 == null) {
4638            return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
4639        }
4640
4641        if (s1.length != s2.length) {
4642            return PackageManager.SIGNATURE_NO_MATCH;
4643        }
4644
4645        // Since both signature sets are of size 1, we can compare without HashSets.
4646        if (s1.length == 1) {
4647            return s1[0].equals(s2[0]) ?
4648                    PackageManager.SIGNATURE_MATCH :
4649                    PackageManager.SIGNATURE_NO_MATCH;
4650        }
4651
4652        ArraySet<Signature> set1 = new ArraySet<Signature>();
4653        for (Signature sig : s1) {
4654            set1.add(sig);
4655        }
4656        ArraySet<Signature> set2 = new ArraySet<Signature>();
4657        for (Signature sig : s2) {
4658            set2.add(sig);
4659        }
4660        // Make sure s2 contains all signatures in s1.
4661        if (set1.equals(set2)) {
4662            return PackageManager.SIGNATURE_MATCH;
4663        }
4664        return PackageManager.SIGNATURE_NO_MATCH;
4665    }
4666
4667    /**
4668     * If the database version for this type of package (internal storage or
4669     * external storage) is less than the version where package signatures
4670     * were updated, return true.
4671     */
4672    private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
4673        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
4674        return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY;
4675    }
4676
4677    /**
4678     * Used for backward compatibility to make sure any packages with
4679     * certificate chains get upgraded to the new style. {@code existingSigs}
4680     * will be in the old format (since they were stored on disk from before the
4681     * system upgrade) and {@code scannedSigs} will be in the newer format.
4682     */
4683    private int compareSignaturesCompat(PackageSignatures existingSigs,
4684            PackageParser.Package scannedPkg) {
4685        if (!isCompatSignatureUpdateNeeded(scannedPkg)) {
4686            return PackageManager.SIGNATURE_NO_MATCH;
4687        }
4688
4689        ArraySet<Signature> existingSet = new ArraySet<Signature>();
4690        for (Signature sig : existingSigs.mSignatures) {
4691            existingSet.add(sig);
4692        }
4693        ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>();
4694        for (Signature sig : scannedPkg.mSignatures) {
4695            try {
4696                Signature[] chainSignatures = sig.getChainSignatures();
4697                for (Signature chainSig : chainSignatures) {
4698                    scannedCompatSet.add(chainSig);
4699                }
4700            } catch (CertificateEncodingException e) {
4701                scannedCompatSet.add(sig);
4702            }
4703        }
4704        /*
4705         * Make sure the expanded scanned set contains all signatures in the
4706         * existing one.
4707         */
4708        if (scannedCompatSet.equals(existingSet)) {
4709            // Migrate the old signatures to the new scheme.
4710            existingSigs.assignSignatures(scannedPkg.mSignatures);
4711            // The new KeySets will be re-added later in the scanning process.
4712            synchronized (mPackages) {
4713                mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName);
4714            }
4715            return PackageManager.SIGNATURE_MATCH;
4716        }
4717        return PackageManager.SIGNATURE_NO_MATCH;
4718    }
4719
4720    private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
4721        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
4722        return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER;
4723    }
4724
4725    private int compareSignaturesRecover(PackageSignatures existingSigs,
4726            PackageParser.Package scannedPkg) {
4727        if (!isRecoverSignatureUpdateNeeded(scannedPkg)) {
4728            return PackageManager.SIGNATURE_NO_MATCH;
4729        }
4730
4731        String msg = null;
4732        try {
4733            if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) {
4734                logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for "
4735                        + scannedPkg.packageName);
4736                return PackageManager.SIGNATURE_MATCH;
4737            }
4738        } catch (CertificateException e) {
4739            msg = e.getMessage();
4740        }
4741
4742        logCriticalInfo(Log.INFO,
4743                "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg);
4744        return PackageManager.SIGNATURE_NO_MATCH;
4745    }
4746
4747    @Override
4748    public List<String> getAllPackages() {
4749        synchronized (mPackages) {
4750            return new ArrayList<String>(mPackages.keySet());
4751        }
4752    }
4753
4754    @Override
4755    public String[] getPackagesForUid(int uid) {
4756        uid = UserHandle.getAppId(uid);
4757        // reader
4758        synchronized (mPackages) {
4759            Object obj = mSettings.getUserIdLPr(uid);
4760            if (obj instanceof SharedUserSetting) {
4761                final SharedUserSetting sus = (SharedUserSetting) obj;
4762                final int N = sus.packages.size();
4763                final String[] res = new String[N];
4764                for (int i = 0; i < N; i++) {
4765                    res[i] = sus.packages.valueAt(i).name;
4766                }
4767                return res;
4768            } else if (obj instanceof PackageSetting) {
4769                final PackageSetting ps = (PackageSetting) obj;
4770                return new String[] { ps.name };
4771            }
4772        }
4773        return null;
4774    }
4775
4776    @Override
4777    public String getNameForUid(int uid) {
4778        // reader
4779        synchronized (mPackages) {
4780            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4781            if (obj instanceof SharedUserSetting) {
4782                final SharedUserSetting sus = (SharedUserSetting) obj;
4783                return sus.name + ":" + sus.userId;
4784            } else if (obj instanceof PackageSetting) {
4785                final PackageSetting ps = (PackageSetting) obj;
4786                return ps.name;
4787            }
4788        }
4789        return null;
4790    }
4791
4792    @Override
4793    public int getUidForSharedUser(String sharedUserName) {
4794        if(sharedUserName == null) {
4795            return -1;
4796        }
4797        // reader
4798        synchronized (mPackages) {
4799            final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false);
4800            if (suid == null) {
4801                return -1;
4802            }
4803            return suid.userId;
4804        }
4805    }
4806
4807    @Override
4808    public int getFlagsForUid(int uid) {
4809        synchronized (mPackages) {
4810            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4811            if (obj instanceof SharedUserSetting) {
4812                final SharedUserSetting sus = (SharedUserSetting) obj;
4813                return sus.pkgFlags;
4814            } else if (obj instanceof PackageSetting) {
4815                final PackageSetting ps = (PackageSetting) obj;
4816                return ps.pkgFlags;
4817            }
4818        }
4819        return 0;
4820    }
4821
4822    @Override
4823    public int getPrivateFlagsForUid(int uid) {
4824        synchronized (mPackages) {
4825            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4826            if (obj instanceof SharedUserSetting) {
4827                final SharedUserSetting sus = (SharedUserSetting) obj;
4828                return sus.pkgPrivateFlags;
4829            } else if (obj instanceof PackageSetting) {
4830                final PackageSetting ps = (PackageSetting) obj;
4831                return ps.pkgPrivateFlags;
4832            }
4833        }
4834        return 0;
4835    }
4836
4837    @Override
4838    public boolean isUidPrivileged(int uid) {
4839        uid = UserHandle.getAppId(uid);
4840        // reader
4841        synchronized (mPackages) {
4842            Object obj = mSettings.getUserIdLPr(uid);
4843            if (obj instanceof SharedUserSetting) {
4844                final SharedUserSetting sus = (SharedUserSetting) obj;
4845                final Iterator<PackageSetting> it = sus.packages.iterator();
4846                while (it.hasNext()) {
4847                    if (it.next().isPrivileged()) {
4848                        return true;
4849                    }
4850                }
4851            } else if (obj instanceof PackageSetting) {
4852                final PackageSetting ps = (PackageSetting) obj;
4853                return ps.isPrivileged();
4854            }
4855        }
4856        return false;
4857    }
4858
4859    @Override
4860    public String[] getAppOpPermissionPackages(String permissionName) {
4861        synchronized (mPackages) {
4862            ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName);
4863            if (pkgs == null) {
4864                return null;
4865            }
4866            return pkgs.toArray(new String[pkgs.size()]);
4867        }
4868    }
4869
4870    @Override
4871    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
4872            int flags, int userId) {
4873        try {
4874            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveIntent");
4875
4876            if (!sUserManager.exists(userId)) return null;
4877            flags = updateFlagsForResolve(flags, userId, intent);
4878            enforceCrossUserPermission(Binder.getCallingUid(), userId,
4879                    false /*requireFullPermission*/, false /*checkShell*/, "resolve intent");
4880
4881            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
4882            final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType,
4883                    flags, userId);
4884            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
4885
4886            final ResolveInfo bestChoice =
4887                    chooseBestActivity(intent, resolvedType, flags, query, userId);
4888
4889            if (isEphemeralAllowed(intent, query, userId)) {
4890                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveEphemeral");
4891                final EphemeralResolveInfo ai =
4892                        getEphemeralResolveInfo(intent, resolvedType, userId);
4893                if (ai != null) {
4894                    if (DEBUG_EPHEMERAL) {
4895                        Slog.v(TAG, "Returning an EphemeralResolveInfo");
4896                    }
4897                    bestChoice.ephemeralInstaller = mEphemeralInstallerInfo;
4898                    bestChoice.ephemeralResolveInfo = ai;
4899                }
4900                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
4901            }
4902            return bestChoice;
4903        } finally {
4904            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
4905        }
4906    }
4907
4908    @Override
4909    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
4910            IntentFilter filter, int match, ComponentName activity) {
4911        final int userId = UserHandle.getCallingUserId();
4912        if (DEBUG_PREFERRED) {
4913            Log.v(TAG, "setLastChosenActivity intent=" + intent
4914                + " resolvedType=" + resolvedType
4915                + " flags=" + flags
4916                + " filter=" + filter
4917                + " match=" + match
4918                + " activity=" + activity);
4919            filter.dump(new PrintStreamPrinter(System.out), "    ");
4920        }
4921        intent.setComponent(null);
4922        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
4923                userId);
4924        // Find any earlier preferred or last chosen entries and nuke them
4925        findPreferredActivity(intent, resolvedType,
4926                flags, query, 0, false, true, false, userId);
4927        // Add the new activity as the last chosen for this filter
4928        addPreferredActivityInternal(filter, match, null, activity, false, userId,
4929                "Setting last chosen");
4930    }
4931
4932    @Override
4933    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
4934        final int userId = UserHandle.getCallingUserId();
4935        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
4936        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
4937                userId);
4938        return findPreferredActivity(intent, resolvedType, flags, query, 0,
4939                false, false, false, userId);
4940    }
4941
4942
4943    private boolean isEphemeralAllowed(
4944            Intent intent, List<ResolveInfo> resolvedActivites, int userId) {
4945        // Short circuit and return early if possible.
4946        if (DISABLE_EPHEMERAL_APPS) {
4947            return false;
4948        }
4949        final int callingUser = UserHandle.getCallingUserId();
4950        if (callingUser != UserHandle.USER_SYSTEM) {
4951            return false;
4952        }
4953        if (mEphemeralResolverConnection == null) {
4954            return false;
4955        }
4956        if (intent.getComponent() != null) {
4957            return false;
4958        }
4959        if (intent.getPackage() != null) {
4960            return false;
4961        }
4962        final boolean isWebUri = hasWebURI(intent);
4963        if (!isWebUri) {
4964            return false;
4965        }
4966        // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution.
4967        synchronized (mPackages) {
4968            final int count = resolvedActivites.size();
4969            for (int n = 0; n < count; n++) {
4970                ResolveInfo info = resolvedActivites.get(n);
4971                String packageName = info.activityInfo.packageName;
4972                PackageSetting ps = mSettings.mPackages.get(packageName);
4973                if (ps != null) {
4974                    // Try to get the status from User settings first
4975                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
4976                    int status = (int) (packedStatus >> 32);
4977                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS
4978                            || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
4979                        if (DEBUG_EPHEMERAL) {
4980                            Slog.v(TAG, "DENY ephemeral apps;"
4981                                + " pkg: " + packageName + ", status: " + status);
4982                        }
4983                        return false;
4984                    }
4985                }
4986            }
4987        }
4988        // We've exhausted all ways to deny ephemeral application; let the system look for them.
4989        return true;
4990    }
4991
4992    private EphemeralResolveInfo getEphemeralResolveInfo(Intent intent, String resolvedType,
4993            int userId) {
4994        MessageDigest digest = null;
4995        try {
4996            digest = MessageDigest.getInstance(EphemeralResolveInfo.SHA_ALGORITHM);
4997        } catch (NoSuchAlgorithmException e) {
4998            // If we can't create a digest, ignore ephemeral apps.
4999            return null;
5000        }
5001
5002        final byte[] hostBytes = intent.getData().getHost().getBytes();
5003        final byte[] digestBytes = digest.digest(hostBytes);
5004        int shaPrefix =
5005                digestBytes[0] << 24
5006                | digestBytes[1] << 16
5007                | digestBytes[2] << 8
5008                | digestBytes[3] << 0;
5009        final List<EphemeralResolveInfo> ephemeralResolveInfoList =
5010                mEphemeralResolverConnection.getEphemeralResolveInfoList(shaPrefix);
5011        if (ephemeralResolveInfoList == null || ephemeralResolveInfoList.size() == 0) {
5012            // No hash prefix match; there are no ephemeral apps for this domain.
5013            return null;
5014        }
5015        for (int i = ephemeralResolveInfoList.size() - 1; i >= 0; --i) {
5016            EphemeralResolveInfo ephemeralApplication = ephemeralResolveInfoList.get(i);
5017            if (!Arrays.equals(digestBytes, ephemeralApplication.getDigestBytes())) {
5018                continue;
5019            }
5020            final List<IntentFilter> filters = ephemeralApplication.getFilters();
5021            // No filters; this should never happen.
5022            if (filters.isEmpty()) {
5023                continue;
5024            }
5025            // We have a domain match; resolve the filters to see if anything matches.
5026            final EphemeralIntentResolver ephemeralResolver = new EphemeralIntentResolver();
5027            for (int j = filters.size() - 1; j >= 0; --j) {
5028                final EphemeralResolveIntentInfo intentInfo =
5029                        new EphemeralResolveIntentInfo(filters.get(j), ephemeralApplication);
5030                ephemeralResolver.addFilter(intentInfo);
5031            }
5032            List<EphemeralResolveInfo> matchedResolveInfoList = ephemeralResolver.queryIntent(
5033                    intent, resolvedType, false /*defaultOnly*/, userId);
5034            if (!matchedResolveInfoList.isEmpty()) {
5035                return matchedResolveInfoList.get(0);
5036            }
5037        }
5038        // Hash or filter mis-match; no ephemeral apps for this domain.
5039        return null;
5040    }
5041
5042    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
5043            int flags, List<ResolveInfo> query, int userId) {
5044        if (query != null) {
5045            final int N = query.size();
5046            if (N == 1) {
5047                return query.get(0);
5048            } else if (N > 1) {
5049                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
5050                // If there is more than one activity with the same priority,
5051                // then let the user decide between them.
5052                ResolveInfo r0 = query.get(0);
5053                ResolveInfo r1 = query.get(1);
5054                if (DEBUG_INTENT_MATCHING || debug) {
5055                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
5056                            + r1.activityInfo.name + "=" + r1.priority);
5057                }
5058                // If the first activity has a higher priority, or a different
5059                // default, then it is always desirable to pick it.
5060                if (r0.priority != r1.priority
5061                        || r0.preferredOrder != r1.preferredOrder
5062                        || r0.isDefault != r1.isDefault) {
5063                    return query.get(0);
5064                }
5065                // If we have saved a preference for a preferred activity for
5066                // this Intent, use that.
5067                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
5068                        flags, query, r0.priority, true, false, debug, userId);
5069                if (ri != null) {
5070                    return ri;
5071                }
5072                ri = new ResolveInfo(mResolveInfo);
5073                ri.activityInfo = new ActivityInfo(ri.activityInfo);
5074                ri.activityInfo.labelRes = ResolverActivity.getLabelRes(intent.getAction());
5075                // If all of the options come from the same package, show the application's
5076                // label and icon instead of the generic resolver's.
5077                // Some calls like Intent.resolveActivityInfo query the ResolveInfo from here
5078                // and then throw away the ResolveInfo itself, meaning that the caller loses
5079                // the resolvePackageName. Therefore the activityInfo.labelRes above provides
5080                // a fallback for this case; we only set the target package's resources on
5081                // the ResolveInfo, not the ActivityInfo.
5082                final String intentPackage = intent.getPackage();
5083                if (!TextUtils.isEmpty(intentPackage) && allHavePackage(query, intentPackage)) {
5084                    final ApplicationInfo appi = query.get(0).activityInfo.applicationInfo;
5085                    ri.resolvePackageName = intentPackage;
5086                    if (userNeedsBadging(userId)) {
5087                        ri.noResourceId = true;
5088                    } else {
5089                        ri.icon = appi.icon;
5090                    }
5091                    ri.iconResourceId = appi.icon;
5092                    ri.labelRes = appi.labelRes;
5093                }
5094                ri.activityInfo.applicationInfo = new ApplicationInfo(
5095                        ri.activityInfo.applicationInfo);
5096                if (userId != 0) {
5097                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
5098                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
5099                }
5100                // Make sure that the resolver is displayable in car mode
5101                if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle();
5102                ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true);
5103                return ri;
5104            }
5105        }
5106        return null;
5107    }
5108
5109    /**
5110     * Return true if the given list is not empty and all of its contents have
5111     * an activityInfo with the given package name.
5112     */
5113    private boolean allHavePackage(List<ResolveInfo> list, String packageName) {
5114        if (ArrayUtils.isEmpty(list)) {
5115            return false;
5116        }
5117        for (int i = 0, N = list.size(); i < N; i++) {
5118            final ResolveInfo ri = list.get(i);
5119            final ActivityInfo ai = ri != null ? ri.activityInfo : null;
5120            if (ai == null || !packageName.equals(ai.packageName)) {
5121                return false;
5122            }
5123        }
5124        return true;
5125    }
5126
5127    private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
5128            int flags, List<ResolveInfo> query, boolean debug, int userId) {
5129        final int N = query.size();
5130        PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
5131                .get(userId);
5132        // Get the list of persistent preferred activities that handle the intent
5133        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
5134        List<PersistentPreferredActivity> pprefs = ppir != null
5135                ? ppir.queryIntent(intent, resolvedType,
5136                        (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
5137                : null;
5138        if (pprefs != null && pprefs.size() > 0) {
5139            final int M = pprefs.size();
5140            for (int i=0; i<M; i++) {
5141                final PersistentPreferredActivity ppa = pprefs.get(i);
5142                if (DEBUG_PREFERRED || debug) {
5143                    Slog.v(TAG, "Checking PersistentPreferredActivity ds="
5144                            + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
5145                            + "\n  component=" + ppa.mComponent);
5146                    ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
5147                }
5148                final ActivityInfo ai = getActivityInfo(ppa.mComponent,
5149                        flags | MATCH_DISABLED_COMPONENTS, userId);
5150                if (DEBUG_PREFERRED || debug) {
5151                    Slog.v(TAG, "Found persistent preferred activity:");
5152                    if (ai != null) {
5153                        ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
5154                    } else {
5155                        Slog.v(TAG, "  null");
5156                    }
5157                }
5158                if (ai == null) {
5159                    // This previously registered persistent preferred activity
5160                    // component is no longer known. Ignore it and do NOT remove it.
5161                    continue;
5162                }
5163                for (int j=0; j<N; j++) {
5164                    final ResolveInfo ri = query.get(j);
5165                    if (!ri.activityInfo.applicationInfo.packageName
5166                            .equals(ai.applicationInfo.packageName)) {
5167                        continue;
5168                    }
5169                    if (!ri.activityInfo.name.equals(ai.name)) {
5170                        continue;
5171                    }
5172                    //  Found a persistent preference that can handle the intent.
5173                    if (DEBUG_PREFERRED || debug) {
5174                        Slog.v(TAG, "Returning persistent preferred activity: " +
5175                                ri.activityInfo.packageName + "/" + ri.activityInfo.name);
5176                    }
5177                    return ri;
5178                }
5179            }
5180        }
5181        return null;
5182    }
5183
5184    // TODO: handle preferred activities missing while user has amnesia
5185    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
5186            List<ResolveInfo> query, int priority, boolean always,
5187            boolean removeMatches, boolean debug, int userId) {
5188        if (!sUserManager.exists(userId)) return null;
5189        flags = updateFlagsForResolve(flags, userId, intent);
5190        // writer
5191        synchronized (mPackages) {
5192            if (intent.getSelector() != null) {
5193                intent = intent.getSelector();
5194            }
5195            if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
5196
5197            // Try to find a matching persistent preferred activity.
5198            ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
5199                    debug, userId);
5200
5201            // If a persistent preferred activity matched, use it.
5202            if (pri != null) {
5203                return pri;
5204            }
5205
5206            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
5207            // Get the list of preferred activities that handle the intent
5208            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
5209            List<PreferredActivity> prefs = pir != null
5210                    ? pir.queryIntent(intent, resolvedType,
5211                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
5212                    : null;
5213            if (prefs != null && prefs.size() > 0) {
5214                boolean changed = false;
5215                try {
5216                    // First figure out how good the original match set is.
5217                    // We will only allow preferred activities that came
5218                    // from the same match quality.
5219                    int match = 0;
5220
5221                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
5222
5223                    final int N = query.size();
5224                    for (int j=0; j<N; j++) {
5225                        final ResolveInfo ri = query.get(j);
5226                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
5227                                + ": 0x" + Integer.toHexString(match));
5228                        if (ri.match > match) {
5229                            match = ri.match;
5230                        }
5231                    }
5232
5233                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
5234                            + Integer.toHexString(match));
5235
5236                    match &= IntentFilter.MATCH_CATEGORY_MASK;
5237                    final int M = prefs.size();
5238                    for (int i=0; i<M; i++) {
5239                        final PreferredActivity pa = prefs.get(i);
5240                        if (DEBUG_PREFERRED || debug) {
5241                            Slog.v(TAG, "Checking PreferredActivity ds="
5242                                    + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
5243                                    + "\n  component=" + pa.mPref.mComponent);
5244                            pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
5245                        }
5246                        if (pa.mPref.mMatch != match) {
5247                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
5248                                    + Integer.toHexString(pa.mPref.mMatch));
5249                            continue;
5250                        }
5251                        // If it's not an "always" type preferred activity and that's what we're
5252                        // looking for, skip it.
5253                        if (always && !pa.mPref.mAlways) {
5254                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
5255                            continue;
5256                        }
5257                        final ActivityInfo ai = getActivityInfo(
5258                                pa.mPref.mComponent, flags | MATCH_DISABLED_COMPONENTS
5259                                        | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
5260                                userId);
5261                        if (DEBUG_PREFERRED || debug) {
5262                            Slog.v(TAG, "Found preferred activity:");
5263                            if (ai != null) {
5264                                ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
5265                            } else {
5266                                Slog.v(TAG, "  null");
5267                            }
5268                        }
5269                        if (ai == null) {
5270                            // This previously registered preferred activity
5271                            // component is no longer known.  Most likely an update
5272                            // to the app was installed and in the new version this
5273                            // component no longer exists.  Clean it up by removing
5274                            // it from the preferred activities list, and skip it.
5275                            Slog.w(TAG, "Removing dangling preferred activity: "
5276                                    + pa.mPref.mComponent);
5277                            pir.removeFilter(pa);
5278                            changed = true;
5279                            continue;
5280                        }
5281                        for (int j=0; j<N; j++) {
5282                            final ResolveInfo ri = query.get(j);
5283                            if (!ri.activityInfo.applicationInfo.packageName
5284                                    .equals(ai.applicationInfo.packageName)) {
5285                                continue;
5286                            }
5287                            if (!ri.activityInfo.name.equals(ai.name)) {
5288                                continue;
5289                            }
5290
5291                            if (removeMatches) {
5292                                pir.removeFilter(pa);
5293                                changed = true;
5294                                if (DEBUG_PREFERRED) {
5295                                    Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
5296                                }
5297                                break;
5298                            }
5299
5300                            // Okay we found a previously set preferred or last chosen app.
5301                            // If the result set is different from when this
5302                            // was created, we need to clear it and re-ask the
5303                            // user their preference, if we're looking for an "always" type entry.
5304                            if (always && !pa.mPref.sameSet(query)) {
5305                                Slog.i(TAG, "Result set changed, dropping preferred activity for "
5306                                        + intent + " type " + resolvedType);
5307                                if (DEBUG_PREFERRED) {
5308                                    Slog.v(TAG, "Removing preferred activity since set changed "
5309                                            + pa.mPref.mComponent);
5310                                }
5311                                pir.removeFilter(pa);
5312                                // Re-add the filter as a "last chosen" entry (!always)
5313                                PreferredActivity lastChosen = new PreferredActivity(
5314                                        pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
5315                                pir.addFilter(lastChosen);
5316                                changed = true;
5317                                return null;
5318                            }
5319
5320                            // Yay! Either the set matched or we're looking for the last chosen
5321                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
5322                                    + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
5323                            return ri;
5324                        }
5325                    }
5326                } finally {
5327                    if (changed) {
5328                        if (DEBUG_PREFERRED) {
5329                            Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions");
5330                        }
5331                        scheduleWritePackageRestrictionsLocked(userId);
5332                    }
5333                }
5334            }
5335        }
5336        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
5337        return null;
5338    }
5339
5340    /*
5341     * Returns if intent can be forwarded from the sourceUserId to the targetUserId
5342     */
5343    @Override
5344    public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
5345            int targetUserId) {
5346        mContext.enforceCallingOrSelfPermission(
5347                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
5348        List<CrossProfileIntentFilter> matches =
5349                getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
5350        if (matches != null) {
5351            int size = matches.size();
5352            for (int i = 0; i < size; i++) {
5353                if (matches.get(i).getTargetUserId() == targetUserId) return true;
5354            }
5355        }
5356        if (hasWebURI(intent)) {
5357            // cross-profile app linking works only towards the parent.
5358            final UserInfo parent = getProfileParent(sourceUserId);
5359            synchronized(mPackages) {
5360                int flags = updateFlagsForResolve(0, parent.id, intent);
5361                CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr(
5362                        intent, resolvedType, flags, sourceUserId, parent.id);
5363                return xpDomainInfo != null;
5364            }
5365        }
5366        return false;
5367    }
5368
5369    private UserInfo getProfileParent(int userId) {
5370        final long identity = Binder.clearCallingIdentity();
5371        try {
5372            return sUserManager.getProfileParent(userId);
5373        } finally {
5374            Binder.restoreCallingIdentity(identity);
5375        }
5376    }
5377
5378    private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
5379            String resolvedType, int userId) {
5380        CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
5381        if (resolver != null) {
5382            return resolver.queryIntent(intent, resolvedType, false, userId);
5383        }
5384        return null;
5385    }
5386
5387    @Override
5388    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivities(Intent intent,
5389            String resolvedType, int flags, int userId) {
5390        try {
5391            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
5392
5393            return new ParceledListSlice<>(
5394                    queryIntentActivitiesInternal(intent, resolvedType, flags, userId));
5395        } finally {
5396            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
5397        }
5398    }
5399
5400    private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent,
5401            String resolvedType, int flags, int userId) {
5402        if (!sUserManager.exists(userId)) return Collections.emptyList();
5403        flags = updateFlagsForResolve(flags, userId, intent);
5404        enforceCrossUserPermission(Binder.getCallingUid(), userId,
5405                false /* requireFullPermission */, false /* checkShell */,
5406                "query intent activities");
5407        ComponentName comp = intent.getComponent();
5408        if (comp == null) {
5409            if (intent.getSelector() != null) {
5410                intent = intent.getSelector();
5411                comp = intent.getComponent();
5412            }
5413        }
5414
5415        if (comp != null) {
5416            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5417            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
5418            if (ai != null) {
5419                final ResolveInfo ri = new ResolveInfo();
5420                ri.activityInfo = ai;
5421                list.add(ri);
5422            }
5423            return list;
5424        }
5425
5426        // reader
5427        synchronized (mPackages) {
5428            final String pkgName = intent.getPackage();
5429            if (pkgName == null) {
5430                List<CrossProfileIntentFilter> matchingFilters =
5431                        getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
5432                // Check for results that need to skip the current profile.
5433                ResolveInfo xpResolveInfo  = querySkipCurrentProfileIntents(matchingFilters, intent,
5434                        resolvedType, flags, userId);
5435                if (xpResolveInfo != null) {
5436                    List<ResolveInfo> result = new ArrayList<ResolveInfo>(1);
5437                    result.add(xpResolveInfo);
5438                    return filterIfNotSystemUser(result, userId);
5439                }
5440
5441                // Check for results in the current profile.
5442                List<ResolveInfo> result = mActivities.queryIntent(
5443                        intent, resolvedType, flags, userId);
5444                result = filterIfNotSystemUser(result, userId);
5445
5446                // Check for cross profile results.
5447                boolean hasNonNegativePriorityResult = hasNonNegativePriority(result);
5448                xpResolveInfo = queryCrossProfileIntents(
5449                        matchingFilters, intent, resolvedType, flags, userId,
5450                        hasNonNegativePriorityResult);
5451                if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
5452                    boolean isVisibleToUser = filterIfNotSystemUser(
5453                            Collections.singletonList(xpResolveInfo), userId).size() > 0;
5454                    if (isVisibleToUser) {
5455                        result.add(xpResolveInfo);
5456                        Collections.sort(result, mResolvePrioritySorter);
5457                    }
5458                }
5459                if (hasWebURI(intent)) {
5460                    CrossProfileDomainInfo xpDomainInfo = null;
5461                    final UserInfo parent = getProfileParent(userId);
5462                    if (parent != null) {
5463                        xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType,
5464                                flags, userId, parent.id);
5465                    }
5466                    if (xpDomainInfo != null) {
5467                        if (xpResolveInfo != null) {
5468                            // If we didn't remove it, the cross-profile ResolveInfo would be twice
5469                            // in the result.
5470                            result.remove(xpResolveInfo);
5471                        }
5472                        if (result.size() == 0) {
5473                            result.add(xpDomainInfo.resolveInfo);
5474                            return result;
5475                        }
5476                    } else if (result.size() <= 1) {
5477                        return result;
5478                    }
5479                    result = filterCandidatesWithDomainPreferredActivitiesLPr(intent, flags, result,
5480                            xpDomainInfo, userId);
5481                    Collections.sort(result, mResolvePrioritySorter);
5482                }
5483                return result;
5484            }
5485            final PackageParser.Package pkg = mPackages.get(pkgName);
5486            if (pkg != null) {
5487                return filterIfNotSystemUser(
5488                        mActivities.queryIntentForPackage(
5489                                intent, resolvedType, flags, pkg.activities, userId),
5490                        userId);
5491            }
5492            return new ArrayList<ResolveInfo>();
5493        }
5494    }
5495
5496    private static class CrossProfileDomainInfo {
5497        /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */
5498        ResolveInfo resolveInfo;
5499        /* Best domain verification status of the activities found in the other profile */
5500        int bestDomainVerificationStatus;
5501    }
5502
5503    private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent,
5504            String resolvedType, int flags, int sourceUserId, int parentUserId) {
5505        if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING,
5506                sourceUserId)) {
5507            return null;
5508        }
5509        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
5510                resolvedType, flags, parentUserId);
5511
5512        if (resultTargetUser == null || resultTargetUser.isEmpty()) {
5513            return null;
5514        }
5515        CrossProfileDomainInfo result = null;
5516        int size = resultTargetUser.size();
5517        for (int i = 0; i < size; i++) {
5518            ResolveInfo riTargetUser = resultTargetUser.get(i);
5519            // Intent filter verification is only for filters that specify a host. So don't return
5520            // those that handle all web uris.
5521            if (riTargetUser.handleAllWebDataURI) {
5522                continue;
5523            }
5524            String packageName = riTargetUser.activityInfo.packageName;
5525            PackageSetting ps = mSettings.mPackages.get(packageName);
5526            if (ps == null) {
5527                continue;
5528            }
5529            long verificationState = getDomainVerificationStatusLPr(ps, parentUserId);
5530            int status = (int)(verificationState >> 32);
5531            if (result == null) {
5532                result = new CrossProfileDomainInfo();
5533                result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(),
5534                        sourceUserId, parentUserId);
5535                result.bestDomainVerificationStatus = status;
5536            } else {
5537                result.bestDomainVerificationStatus = bestDomainVerificationStatus(status,
5538                        result.bestDomainVerificationStatus);
5539            }
5540        }
5541        // Don't consider matches with status NEVER across profiles.
5542        if (result != null && result.bestDomainVerificationStatus
5543                == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5544            return null;
5545        }
5546        return result;
5547    }
5548
5549    /**
5550     * Verification statuses are ordered from the worse to the best, except for
5551     * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse.
5552     */
5553    private int bestDomainVerificationStatus(int status1, int status2) {
5554        if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5555            return status2;
5556        }
5557        if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5558            return status1;
5559        }
5560        return (int) MathUtils.max(status1, status2);
5561    }
5562
5563    private boolean isUserEnabled(int userId) {
5564        long callingId = Binder.clearCallingIdentity();
5565        try {
5566            UserInfo userInfo = sUserManager.getUserInfo(userId);
5567            return userInfo != null && userInfo.isEnabled();
5568        } finally {
5569            Binder.restoreCallingIdentity(callingId);
5570        }
5571    }
5572
5573    /**
5574     * Filter out activities with systemUserOnly flag set, when current user is not System.
5575     *
5576     * @return filtered list
5577     */
5578    private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) {
5579        if (userId == UserHandle.USER_SYSTEM) {
5580            return resolveInfos;
5581        }
5582        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
5583            ResolveInfo info = resolveInfos.get(i);
5584            if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) {
5585                resolveInfos.remove(i);
5586            }
5587        }
5588        return resolveInfos;
5589    }
5590
5591    /**
5592     * @param resolveInfos list of resolve infos in descending priority order
5593     * @return if the list contains a resolve info with non-negative priority
5594     */
5595    private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) {
5596        return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0;
5597    }
5598
5599    private static boolean hasWebURI(Intent intent) {
5600        if (intent.getData() == null) {
5601            return false;
5602        }
5603        final String scheme = intent.getScheme();
5604        if (TextUtils.isEmpty(scheme)) {
5605            return false;
5606        }
5607        return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS);
5608    }
5609
5610    private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent,
5611            int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo,
5612            int userId) {
5613        final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0;
5614
5615        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
5616            Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " +
5617                    candidates.size());
5618        }
5619
5620        ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>();
5621        ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>();
5622        ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>();
5623        ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>();
5624        ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>();
5625        ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>();
5626
5627        synchronized (mPackages) {
5628            final int count = candidates.size();
5629            // First, try to use linked apps. Partition the candidates into four lists:
5630            // one for the final results, one for the "do not use ever", one for "undefined status"
5631            // and finally one for "browser app type".
5632            for (int n=0; n<count; n++) {
5633                ResolveInfo info = candidates.get(n);
5634                String packageName = info.activityInfo.packageName;
5635                PackageSetting ps = mSettings.mPackages.get(packageName);
5636                if (ps != null) {
5637                    // Add to the special match all list (Browser use case)
5638                    if (info.handleAllWebDataURI) {
5639                        matchAllList.add(info);
5640                        continue;
5641                    }
5642                    // Try to get the status from User settings first
5643                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
5644                    int status = (int)(packedStatus >> 32);
5645                    int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
5646                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
5647                        if (DEBUG_DOMAIN_VERIFICATION) {
5648                            Slog.i(TAG, "  + always: " + info.activityInfo.packageName
5649                                    + " : linkgen=" + linkGeneration);
5650                        }
5651                        // Use link-enabled generation as preferredOrder, i.e.
5652                        // prefer newly-enabled over earlier-enabled.
5653                        info.preferredOrder = linkGeneration;
5654                        alwaysList.add(info);
5655                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5656                        if (DEBUG_DOMAIN_VERIFICATION) {
5657                            Slog.i(TAG, "  + never: " + info.activityInfo.packageName);
5658                        }
5659                        neverList.add(info);
5660                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
5661                        if (DEBUG_DOMAIN_VERIFICATION) {
5662                            Slog.i(TAG, "  + always-ask: " + info.activityInfo.packageName);
5663                        }
5664                        alwaysAskList.add(info);
5665                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED ||
5666                            status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) {
5667                        if (DEBUG_DOMAIN_VERIFICATION) {
5668                            Slog.i(TAG, "  + ask: " + info.activityInfo.packageName);
5669                        }
5670                        undefinedList.add(info);
5671                    }
5672                }
5673            }
5674
5675            // We'll want to include browser possibilities in a few cases
5676            boolean includeBrowser = false;
5677
5678            // First try to add the "always" resolution(s) for the current user, if any
5679            if (alwaysList.size() > 0) {
5680                result.addAll(alwaysList);
5681            } else {
5682                // Add all undefined apps as we want them to appear in the disambiguation dialog.
5683                result.addAll(undefinedList);
5684                // Maybe add one for the other profile.
5685                if (xpDomainInfo != null && (
5686                        xpDomainInfo.bestDomainVerificationStatus
5687                        != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) {
5688                    result.add(xpDomainInfo.resolveInfo);
5689                }
5690                includeBrowser = true;
5691            }
5692
5693            // The presence of any 'always ask' alternatives means we'll also offer browsers.
5694            // If there were 'always' entries their preferred order has been set, so we also
5695            // back that off to make the alternatives equivalent
5696            if (alwaysAskList.size() > 0) {
5697                for (ResolveInfo i : result) {
5698                    i.preferredOrder = 0;
5699                }
5700                result.addAll(alwaysAskList);
5701                includeBrowser = true;
5702            }
5703
5704            if (includeBrowser) {
5705                // Also add browsers (all of them or only the default one)
5706                if (DEBUG_DOMAIN_VERIFICATION) {
5707                    Slog.v(TAG, "   ...including browsers in candidate set");
5708                }
5709                if ((matchFlags & MATCH_ALL) != 0) {
5710                    result.addAll(matchAllList);
5711                } else {
5712                    // Browser/generic handling case.  If there's a default browser, go straight
5713                    // to that (but only if there is no other higher-priority match).
5714                    final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
5715                    int maxMatchPrio = 0;
5716                    ResolveInfo defaultBrowserMatch = null;
5717                    final int numCandidates = matchAllList.size();
5718                    for (int n = 0; n < numCandidates; n++) {
5719                        ResolveInfo info = matchAllList.get(n);
5720                        // track the highest overall match priority...
5721                        if (info.priority > maxMatchPrio) {
5722                            maxMatchPrio = info.priority;
5723                        }
5724                        // ...and the highest-priority default browser match
5725                        if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) {
5726                            if (defaultBrowserMatch == null
5727                                    || (defaultBrowserMatch.priority < info.priority)) {
5728                                if (debug) {
5729                                    Slog.v(TAG, "Considering default browser match " + info);
5730                                }
5731                                defaultBrowserMatch = info;
5732                            }
5733                        }
5734                    }
5735                    if (defaultBrowserMatch != null
5736                            && defaultBrowserMatch.priority >= maxMatchPrio
5737                            && !TextUtils.isEmpty(defaultBrowserPackageName))
5738                    {
5739                        if (debug) {
5740                            Slog.v(TAG, "Default browser match " + defaultBrowserMatch);
5741                        }
5742                        result.add(defaultBrowserMatch);
5743                    } else {
5744                        result.addAll(matchAllList);
5745                    }
5746                }
5747
5748                // If there is nothing selected, add all candidates and remove the ones that the user
5749                // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state
5750                if (result.size() == 0) {
5751                    result.addAll(candidates);
5752                    result.removeAll(neverList);
5753                }
5754            }
5755        }
5756        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
5757            Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " +
5758                    result.size());
5759            for (ResolveInfo info : result) {
5760                Slog.v(TAG, "  + " + info.activityInfo);
5761            }
5762        }
5763        return result;
5764    }
5765
5766    // Returns a packed value as a long:
5767    //
5768    // high 'int'-sized word: link status: undefined/ask/never/always.
5769    // low 'int'-sized word: relative priority among 'always' results.
5770    private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) {
5771        long result = ps.getDomainVerificationStatusForUser(userId);
5772        // if none available, get the master status
5773        if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
5774            if (ps.getIntentFilterVerificationInfo() != null) {
5775                result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32;
5776            }
5777        }
5778        return result;
5779    }
5780
5781    private ResolveInfo querySkipCurrentProfileIntents(
5782            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
5783            int flags, int sourceUserId) {
5784        if (matchingFilters != null) {
5785            int size = matchingFilters.size();
5786            for (int i = 0; i < size; i ++) {
5787                CrossProfileIntentFilter filter = matchingFilters.get(i);
5788                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
5789                    // Checking if there are activities in the target user that can handle the
5790                    // intent.
5791                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
5792                            resolvedType, flags, sourceUserId);
5793                    if (resolveInfo != null) {
5794                        return resolveInfo;
5795                    }
5796                }
5797            }
5798        }
5799        return null;
5800    }
5801
5802    // Return matching ResolveInfo in target user if any.
5803    private ResolveInfo queryCrossProfileIntents(
5804            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
5805            int flags, int sourceUserId, boolean matchInCurrentProfile) {
5806        if (matchingFilters != null) {
5807            // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
5808            // match the same intent. For performance reasons, it is better not to
5809            // run queryIntent twice for the same userId
5810            SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
5811            int size = matchingFilters.size();
5812            for (int i = 0; i < size; i++) {
5813                CrossProfileIntentFilter filter = matchingFilters.get(i);
5814                int targetUserId = filter.getTargetUserId();
5815                boolean skipCurrentProfile =
5816                        (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0;
5817                boolean skipCurrentProfileIfNoMatchFound =
5818                        (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0;
5819                if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId)
5820                        && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) {
5821                    // Checking if there are activities in the target user that can handle the
5822                    // intent.
5823                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
5824                            resolvedType, flags, sourceUserId);
5825                    if (resolveInfo != null) return resolveInfo;
5826                    alreadyTriedUserIds.put(targetUserId, true);
5827                }
5828            }
5829        }
5830        return null;
5831    }
5832
5833    /**
5834     * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that
5835     * will forward the intent to the filter's target user.
5836     * Otherwise, returns null.
5837     */
5838    private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent,
5839            String resolvedType, int flags, int sourceUserId) {
5840        int targetUserId = filter.getTargetUserId();
5841        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
5842                resolvedType, flags, targetUserId);
5843        if (resultTargetUser != null && isUserEnabled(targetUserId)) {
5844            // If all the matches in the target profile are suspended, return null.
5845            for (int i = resultTargetUser.size() - 1; i >= 0; i--) {
5846                if ((resultTargetUser.get(i).activityInfo.applicationInfo.flags
5847                        & ApplicationInfo.FLAG_SUSPENDED) == 0) {
5848                    return createForwardingResolveInfoUnchecked(filter, sourceUserId,
5849                            targetUserId);
5850                }
5851            }
5852        }
5853        return null;
5854    }
5855
5856    private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter,
5857            int sourceUserId, int targetUserId) {
5858        ResolveInfo forwardingResolveInfo = new ResolveInfo();
5859        long ident = Binder.clearCallingIdentity();
5860        boolean targetIsProfile;
5861        try {
5862            targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile();
5863        } finally {
5864            Binder.restoreCallingIdentity(ident);
5865        }
5866        String className;
5867        if (targetIsProfile) {
5868            className = FORWARD_INTENT_TO_MANAGED_PROFILE;
5869        } else {
5870            className = FORWARD_INTENT_TO_PARENT;
5871        }
5872        ComponentName forwardingActivityComponentName = new ComponentName(
5873                mAndroidApplication.packageName, className);
5874        ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
5875                sourceUserId);
5876        if (!targetIsProfile) {
5877            forwardingActivityInfo.showUserIcon = targetUserId;
5878            forwardingResolveInfo.noResourceId = true;
5879        }
5880        forwardingResolveInfo.activityInfo = forwardingActivityInfo;
5881        forwardingResolveInfo.priority = 0;
5882        forwardingResolveInfo.preferredOrder = 0;
5883        forwardingResolveInfo.match = 0;
5884        forwardingResolveInfo.isDefault = true;
5885        forwardingResolveInfo.filter = filter;
5886        forwardingResolveInfo.targetUserId = targetUserId;
5887        return forwardingResolveInfo;
5888    }
5889
5890    @Override
5891    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
5892            Intent[] specifics, String[] specificTypes, Intent intent,
5893            String resolvedType, int flags, int userId) {
5894        return new ParceledListSlice<>(queryIntentActivityOptionsInternal(caller, specifics,
5895                specificTypes, intent, resolvedType, flags, userId));
5896    }
5897
5898    private @NonNull List<ResolveInfo> queryIntentActivityOptionsInternal(ComponentName caller,
5899            Intent[] specifics, String[] specificTypes, Intent intent,
5900            String resolvedType, int flags, int userId) {
5901        if (!sUserManager.exists(userId)) return Collections.emptyList();
5902        flags = updateFlagsForResolve(flags, userId, intent);
5903        enforceCrossUserPermission(Binder.getCallingUid(), userId,
5904                false /* requireFullPermission */, false /* checkShell */,
5905                "query intent activity options");
5906        final String resultsAction = intent.getAction();
5907
5908        final List<ResolveInfo> results = queryIntentActivitiesInternal(intent, resolvedType, flags
5909                | PackageManager.GET_RESOLVED_FILTER, userId);
5910
5911        if (DEBUG_INTENT_MATCHING) {
5912            Log.v(TAG, "Query " + intent + ": " + results);
5913        }
5914
5915        int specificsPos = 0;
5916        int N;
5917
5918        // todo: note that the algorithm used here is O(N^2).  This
5919        // isn't a problem in our current environment, but if we start running
5920        // into situations where we have more than 5 or 10 matches then this
5921        // should probably be changed to something smarter...
5922
5923        // First we go through and resolve each of the specific items
5924        // that were supplied, taking care of removing any corresponding
5925        // duplicate items in the generic resolve list.
5926        if (specifics != null) {
5927            for (int i=0; i<specifics.length; i++) {
5928                final Intent sintent = specifics[i];
5929                if (sintent == null) {
5930                    continue;
5931                }
5932
5933                if (DEBUG_INTENT_MATCHING) {
5934                    Log.v(TAG, "Specific #" + i + ": " + sintent);
5935                }
5936
5937                String action = sintent.getAction();
5938                if (resultsAction != null && resultsAction.equals(action)) {
5939                    // If this action was explicitly requested, then don't
5940                    // remove things that have it.
5941                    action = null;
5942                }
5943
5944                ResolveInfo ri = null;
5945                ActivityInfo ai = null;
5946
5947                ComponentName comp = sintent.getComponent();
5948                if (comp == null) {
5949                    ri = resolveIntent(
5950                        sintent,
5951                        specificTypes != null ? specificTypes[i] : null,
5952                            flags, userId);
5953                    if (ri == null) {
5954                        continue;
5955                    }
5956                    if (ri == mResolveInfo) {
5957                        // ACK!  Must do something better with this.
5958                    }
5959                    ai = ri.activityInfo;
5960                    comp = new ComponentName(ai.applicationInfo.packageName,
5961                            ai.name);
5962                } else {
5963                    ai = getActivityInfo(comp, flags, userId);
5964                    if (ai == null) {
5965                        continue;
5966                    }
5967                }
5968
5969                // Look for any generic query activities that are duplicates
5970                // of this specific one, and remove them from the results.
5971                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
5972                N = results.size();
5973                int j;
5974                for (j=specificsPos; j<N; j++) {
5975                    ResolveInfo sri = results.get(j);
5976                    if ((sri.activityInfo.name.equals(comp.getClassName())
5977                            && sri.activityInfo.applicationInfo.packageName.equals(
5978                                    comp.getPackageName()))
5979                        || (action != null && sri.filter.matchAction(action))) {
5980                        results.remove(j);
5981                        if (DEBUG_INTENT_MATCHING) Log.v(
5982                            TAG, "Removing duplicate item from " + j
5983                            + " due to specific " + specificsPos);
5984                        if (ri == null) {
5985                            ri = sri;
5986                        }
5987                        j--;
5988                        N--;
5989                    }
5990                }
5991
5992                // Add this specific item to its proper place.
5993                if (ri == null) {
5994                    ri = new ResolveInfo();
5995                    ri.activityInfo = ai;
5996                }
5997                results.add(specificsPos, ri);
5998                ri.specificIndex = i;
5999                specificsPos++;
6000            }
6001        }
6002
6003        // Now we go through the remaining generic results and remove any
6004        // duplicate actions that are found here.
6005        N = results.size();
6006        for (int i=specificsPos; i<N-1; i++) {
6007            final ResolveInfo rii = results.get(i);
6008            if (rii.filter == null) {
6009                continue;
6010            }
6011
6012            // Iterate over all of the actions of this result's intent
6013            // filter...  typically this should be just one.
6014            final Iterator<String> it = rii.filter.actionsIterator();
6015            if (it == null) {
6016                continue;
6017            }
6018            while (it.hasNext()) {
6019                final String action = it.next();
6020                if (resultsAction != null && resultsAction.equals(action)) {
6021                    // If this action was explicitly requested, then don't
6022                    // remove things that have it.
6023                    continue;
6024                }
6025                for (int j=i+1; j<N; j++) {
6026                    final ResolveInfo rij = results.get(j);
6027                    if (rij.filter != null && rij.filter.hasAction(action)) {
6028                        results.remove(j);
6029                        if (DEBUG_INTENT_MATCHING) Log.v(
6030                            TAG, "Removing duplicate item from " + j
6031                            + " due to action " + action + " at " + i);
6032                        j--;
6033                        N--;
6034                    }
6035                }
6036            }
6037
6038            // If the caller didn't request filter information, drop it now
6039            // so we don't have to marshall/unmarshall it.
6040            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
6041                rii.filter = null;
6042            }
6043        }
6044
6045        // Filter out the caller activity if so requested.
6046        if (caller != null) {
6047            N = results.size();
6048            for (int i=0; i<N; i++) {
6049                ActivityInfo ainfo = results.get(i).activityInfo;
6050                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
6051                        && caller.getClassName().equals(ainfo.name)) {
6052                    results.remove(i);
6053                    break;
6054                }
6055            }
6056        }
6057
6058        // If the caller didn't request filter information,
6059        // drop them now so we don't have to
6060        // marshall/unmarshall it.
6061        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
6062            N = results.size();
6063            for (int i=0; i<N; i++) {
6064                results.get(i).filter = null;
6065            }
6066        }
6067
6068        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
6069        return results;
6070    }
6071
6072    @Override
6073    public @NonNull ParceledListSlice<ResolveInfo> queryIntentReceivers(Intent intent,
6074            String resolvedType, int flags, int userId) {
6075        return new ParceledListSlice<>(
6076                queryIntentReceiversInternal(intent, resolvedType, flags, userId));
6077    }
6078
6079    private @NonNull List<ResolveInfo> queryIntentReceiversInternal(Intent intent,
6080            String resolvedType, int flags, int userId) {
6081        if (!sUserManager.exists(userId)) return Collections.emptyList();
6082        flags = updateFlagsForResolve(flags, userId, intent);
6083        ComponentName comp = intent.getComponent();
6084        if (comp == null) {
6085            if (intent.getSelector() != null) {
6086                intent = intent.getSelector();
6087                comp = intent.getComponent();
6088            }
6089        }
6090        if (comp != null) {
6091            List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
6092            ActivityInfo ai = getReceiverInfo(comp, flags, userId);
6093            if (ai != null) {
6094                ResolveInfo ri = new ResolveInfo();
6095                ri.activityInfo = ai;
6096                list.add(ri);
6097            }
6098            return list;
6099        }
6100
6101        // reader
6102        synchronized (mPackages) {
6103            String pkgName = intent.getPackage();
6104            if (pkgName == null) {
6105                return mReceivers.queryIntent(intent, resolvedType, flags, userId);
6106            }
6107            final PackageParser.Package pkg = mPackages.get(pkgName);
6108            if (pkg != null) {
6109                return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers,
6110                        userId);
6111            }
6112            return Collections.emptyList();
6113        }
6114    }
6115
6116    @Override
6117    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
6118        if (!sUserManager.exists(userId)) return null;
6119        flags = updateFlagsForResolve(flags, userId, intent);
6120        List<ResolveInfo> query = queryIntentServicesInternal(intent, resolvedType, flags, userId);
6121        if (query != null) {
6122            if (query.size() >= 1) {
6123                // If there is more than one service with the same priority,
6124                // just arbitrarily pick the first one.
6125                return query.get(0);
6126            }
6127        }
6128        return null;
6129    }
6130
6131    @Override
6132    public @NonNull ParceledListSlice<ResolveInfo> queryIntentServices(Intent intent,
6133            String resolvedType, int flags, int userId) {
6134        return new ParceledListSlice<>(
6135                queryIntentServicesInternal(intent, resolvedType, flags, userId));
6136    }
6137
6138    private @NonNull List<ResolveInfo> queryIntentServicesInternal(Intent intent,
6139            String resolvedType, int flags, int userId) {
6140        if (!sUserManager.exists(userId)) return Collections.emptyList();
6141        flags = updateFlagsForResolve(flags, userId, intent);
6142        ComponentName comp = intent.getComponent();
6143        if (comp == null) {
6144            if (intent.getSelector() != null) {
6145                intent = intent.getSelector();
6146                comp = intent.getComponent();
6147            }
6148        }
6149        if (comp != null) {
6150            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
6151            final ServiceInfo si = getServiceInfo(comp, flags, userId);
6152            if (si != null) {
6153                final ResolveInfo ri = new ResolveInfo();
6154                ri.serviceInfo = si;
6155                list.add(ri);
6156            }
6157            return list;
6158        }
6159
6160        // reader
6161        synchronized (mPackages) {
6162            String pkgName = intent.getPackage();
6163            if (pkgName == null) {
6164                return mServices.queryIntent(intent, resolvedType, flags, userId);
6165            }
6166            final PackageParser.Package pkg = mPackages.get(pkgName);
6167            if (pkg != null) {
6168                return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
6169                        userId);
6170            }
6171            return Collections.emptyList();
6172        }
6173    }
6174
6175    @Override
6176    public @NonNull ParceledListSlice<ResolveInfo> queryIntentContentProviders(Intent intent,
6177            String resolvedType, int flags, int userId) {
6178        return new ParceledListSlice<>(
6179                queryIntentContentProvidersInternal(intent, resolvedType, flags, userId));
6180    }
6181
6182    private @NonNull List<ResolveInfo> queryIntentContentProvidersInternal(
6183            Intent intent, String resolvedType, int flags, int userId) {
6184        if (!sUserManager.exists(userId)) return Collections.emptyList();
6185        flags = updateFlagsForResolve(flags, userId, intent);
6186        ComponentName comp = intent.getComponent();
6187        if (comp == null) {
6188            if (intent.getSelector() != null) {
6189                intent = intent.getSelector();
6190                comp = intent.getComponent();
6191            }
6192        }
6193        if (comp != null) {
6194            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
6195            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
6196            if (pi != null) {
6197                final ResolveInfo ri = new ResolveInfo();
6198                ri.providerInfo = pi;
6199                list.add(ri);
6200            }
6201            return list;
6202        }
6203
6204        // reader
6205        synchronized (mPackages) {
6206            String pkgName = intent.getPackage();
6207            if (pkgName == null) {
6208                return mProviders.queryIntent(intent, resolvedType, flags, userId);
6209            }
6210            final PackageParser.Package pkg = mPackages.get(pkgName);
6211            if (pkg != null) {
6212                return mProviders.queryIntentForPackage(
6213                        intent, resolvedType, flags, pkg.providers, userId);
6214            }
6215            return Collections.emptyList();
6216        }
6217    }
6218
6219    @Override
6220    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
6221        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
6222        flags = updateFlagsForPackage(flags, userId, null);
6223        final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0;
6224        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6225                true /* requireFullPermission */, false /* checkShell */,
6226                "get installed packages");
6227
6228        // writer
6229        synchronized (mPackages) {
6230            ArrayList<PackageInfo> list;
6231            if (listUninstalled) {
6232                list = new ArrayList<PackageInfo>(mSettings.mPackages.size());
6233                for (PackageSetting ps : mSettings.mPackages.values()) {
6234                    final PackageInfo pi;
6235                    if (ps.pkg != null) {
6236                        pi = generatePackageInfo(ps, flags, userId);
6237                    } else {
6238                        pi = generatePackageInfo(ps, flags, userId);
6239                    }
6240                    if (pi != null) {
6241                        list.add(pi);
6242                    }
6243                }
6244            } else {
6245                list = new ArrayList<PackageInfo>(mPackages.size());
6246                for (PackageParser.Package p : mPackages.values()) {
6247                    final PackageInfo pi =
6248                            generatePackageInfo((PackageSetting)p.mExtras, flags, userId);
6249                    if (pi != null) {
6250                        list.add(pi);
6251                    }
6252                }
6253            }
6254
6255            return new ParceledListSlice<PackageInfo>(list);
6256        }
6257    }
6258
6259    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
6260            String[] permissions, boolean[] tmp, int flags, int userId) {
6261        int numMatch = 0;
6262        final PermissionsState permissionsState = ps.getPermissionsState();
6263        for (int i=0; i<permissions.length; i++) {
6264            final String permission = permissions[i];
6265            if (permissionsState.hasPermission(permission, userId)) {
6266                tmp[i] = true;
6267                numMatch++;
6268            } else {
6269                tmp[i] = false;
6270            }
6271        }
6272        if (numMatch == 0) {
6273            return;
6274        }
6275        final PackageInfo pi;
6276        if (ps.pkg != null) {
6277            pi = generatePackageInfo(ps, flags, userId);
6278        } else {
6279            pi = generatePackageInfo(ps, flags, userId);
6280        }
6281        // The above might return null in cases of uninstalled apps or install-state
6282        // skew across users/profiles.
6283        if (pi != null) {
6284            if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
6285                if (numMatch == permissions.length) {
6286                    pi.requestedPermissions = permissions;
6287                } else {
6288                    pi.requestedPermissions = new String[numMatch];
6289                    numMatch = 0;
6290                    for (int i=0; i<permissions.length; i++) {
6291                        if (tmp[i]) {
6292                            pi.requestedPermissions[numMatch] = permissions[i];
6293                            numMatch++;
6294                        }
6295                    }
6296                }
6297            }
6298            list.add(pi);
6299        }
6300    }
6301
6302    @Override
6303    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
6304            String[] permissions, int flags, int userId) {
6305        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
6306        flags = updateFlagsForPackage(flags, userId, permissions);
6307        final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0;
6308
6309        // writer
6310        synchronized (mPackages) {
6311            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
6312            boolean[] tmpBools = new boolean[permissions.length];
6313            if (listUninstalled) {
6314                for (PackageSetting ps : mSettings.mPackages.values()) {
6315                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId);
6316                }
6317            } else {
6318                for (PackageParser.Package pkg : mPackages.values()) {
6319                    PackageSetting ps = (PackageSetting)pkg.mExtras;
6320                    if (ps != null) {
6321                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
6322                                userId);
6323                    }
6324                }
6325            }
6326
6327            return new ParceledListSlice<PackageInfo>(list);
6328        }
6329    }
6330
6331    @Override
6332    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
6333        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
6334        flags = updateFlagsForApplication(flags, userId, null);
6335        final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0;
6336
6337        // writer
6338        synchronized (mPackages) {
6339            ArrayList<ApplicationInfo> list;
6340            if (listUninstalled) {
6341                list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size());
6342                for (PackageSetting ps : mSettings.mPackages.values()) {
6343                    ApplicationInfo ai;
6344                    if (ps.pkg != null) {
6345                        ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
6346                                ps.readUserState(userId), userId);
6347                    } else {
6348                        ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId);
6349                    }
6350                    if (ai != null) {
6351                        list.add(ai);
6352                    }
6353                }
6354            } else {
6355                list = new ArrayList<ApplicationInfo>(mPackages.size());
6356                for (PackageParser.Package p : mPackages.values()) {
6357                    if (p.mExtras != null) {
6358                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
6359                                ((PackageSetting)p.mExtras).readUserState(userId), userId);
6360                        if (ai != null) {
6361                            list.add(ai);
6362                        }
6363                    }
6364                }
6365            }
6366
6367            return new ParceledListSlice<ApplicationInfo>(list);
6368        }
6369    }
6370
6371    @Override
6372    public ParceledListSlice<EphemeralApplicationInfo> getEphemeralApplications(int userId) {
6373        if (DISABLE_EPHEMERAL_APPS) {
6374            return null;
6375        }
6376
6377        mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS,
6378                "getEphemeralApplications");
6379        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6380                true /* requireFullPermission */, false /* checkShell */,
6381                "getEphemeralApplications");
6382        synchronized (mPackages) {
6383            List<EphemeralApplicationInfo> ephemeralApps = mEphemeralApplicationRegistry
6384                    .getEphemeralApplicationsLPw(userId);
6385            if (ephemeralApps != null) {
6386                return new ParceledListSlice<>(ephemeralApps);
6387            }
6388        }
6389        return null;
6390    }
6391
6392    @Override
6393    public boolean isEphemeralApplication(String packageName, int userId) {
6394        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6395                true /* requireFullPermission */, false /* checkShell */,
6396                "isEphemeral");
6397        if (DISABLE_EPHEMERAL_APPS) {
6398            return false;
6399        }
6400
6401        if (!isCallerSameApp(packageName)) {
6402            return false;
6403        }
6404        synchronized (mPackages) {
6405            PackageParser.Package pkg = mPackages.get(packageName);
6406            if (pkg != null) {
6407                return pkg.applicationInfo.isEphemeralApp();
6408            }
6409        }
6410        return false;
6411    }
6412
6413    @Override
6414    public byte[] getEphemeralApplicationCookie(String packageName, int userId) {
6415        if (DISABLE_EPHEMERAL_APPS) {
6416            return null;
6417        }
6418
6419        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6420                true /* requireFullPermission */, false /* checkShell */,
6421                "getCookie");
6422        if (!isCallerSameApp(packageName)) {
6423            return null;
6424        }
6425        synchronized (mPackages) {
6426            return mEphemeralApplicationRegistry.getEphemeralApplicationCookieLPw(
6427                    packageName, userId);
6428        }
6429    }
6430
6431    @Override
6432    public boolean setEphemeralApplicationCookie(String packageName, byte[] cookie, int userId) {
6433        if (DISABLE_EPHEMERAL_APPS) {
6434            return true;
6435        }
6436
6437        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6438                true /* requireFullPermission */, true /* checkShell */,
6439                "setCookie");
6440        if (!isCallerSameApp(packageName)) {
6441            return false;
6442        }
6443        synchronized (mPackages) {
6444            return mEphemeralApplicationRegistry.setEphemeralApplicationCookieLPw(
6445                    packageName, cookie, userId);
6446        }
6447    }
6448
6449    @Override
6450    public Bitmap getEphemeralApplicationIcon(String packageName, int userId) {
6451        if (DISABLE_EPHEMERAL_APPS) {
6452            return null;
6453        }
6454
6455        mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS,
6456                "getEphemeralApplicationIcon");
6457        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6458                true /* requireFullPermission */, false /* checkShell */,
6459                "getEphemeralApplicationIcon");
6460        synchronized (mPackages) {
6461            return mEphemeralApplicationRegistry.getEphemeralApplicationIconLPw(
6462                    packageName, userId);
6463        }
6464    }
6465
6466    private boolean isCallerSameApp(String packageName) {
6467        PackageParser.Package pkg = mPackages.get(packageName);
6468        return pkg != null
6469                && UserHandle.getAppId(Binder.getCallingUid()) == pkg.applicationInfo.uid;
6470    }
6471
6472    @Override
6473    public @NonNull ParceledListSlice<ApplicationInfo> getPersistentApplications(int flags) {
6474        return new ParceledListSlice<>(getPersistentApplicationsInternal(flags));
6475    }
6476
6477    private @NonNull List<ApplicationInfo> getPersistentApplicationsInternal(int flags) {
6478        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
6479
6480        // reader
6481        synchronized (mPackages) {
6482            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
6483            final int userId = UserHandle.getCallingUserId();
6484            while (i.hasNext()) {
6485                final PackageParser.Package p = i.next();
6486                if (p.applicationInfo == null) continue;
6487
6488                final boolean matchesUnaware = ((flags & MATCH_DIRECT_BOOT_UNAWARE) != 0)
6489                        && !p.applicationInfo.isDirectBootAware();
6490                final boolean matchesAware = ((flags & MATCH_DIRECT_BOOT_AWARE) != 0)
6491                        && p.applicationInfo.isDirectBootAware();
6492
6493                if ((p.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0
6494                        && (!mSafeMode || isSystemApp(p))
6495                        && (matchesUnaware || matchesAware)) {
6496                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
6497                    if (ps != null) {
6498                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
6499                                ps.readUserState(userId), userId);
6500                        if (ai != null) {
6501                            finalList.add(ai);
6502                        }
6503                    }
6504                }
6505            }
6506        }
6507
6508        return finalList;
6509    }
6510
6511    @Override
6512    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
6513        if (!sUserManager.exists(userId)) return null;
6514        flags = updateFlagsForComponent(flags, userId, name);
6515        // reader
6516        synchronized (mPackages) {
6517            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
6518            PackageSetting ps = provider != null
6519                    ? mSettings.mPackages.get(provider.owner.packageName)
6520                    : null;
6521            return ps != null
6522                    && mSettings.isEnabledAndMatchLPr(provider.info, flags, userId)
6523                    ? PackageParser.generateProviderInfo(provider, flags,
6524                            ps.readUserState(userId), userId)
6525                    : null;
6526        }
6527    }
6528
6529    /**
6530     * @deprecated
6531     */
6532    @Deprecated
6533    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
6534        // reader
6535        synchronized (mPackages) {
6536            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
6537                    .entrySet().iterator();
6538            final int userId = UserHandle.getCallingUserId();
6539            while (i.hasNext()) {
6540                Map.Entry<String, PackageParser.Provider> entry = i.next();
6541                PackageParser.Provider p = entry.getValue();
6542                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
6543
6544                if (ps != null && p.syncable
6545                        && (!mSafeMode || (p.info.applicationInfo.flags
6546                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
6547                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
6548                            ps.readUserState(userId), userId);
6549                    if (info != null) {
6550                        outNames.add(entry.getKey());
6551                        outInfo.add(info);
6552                    }
6553                }
6554            }
6555        }
6556    }
6557
6558    @Override
6559    public @NonNull ParceledListSlice<ProviderInfo> queryContentProviders(String processName,
6560            int uid, int flags) {
6561        final int userId = processName != null ? UserHandle.getUserId(uid)
6562                : UserHandle.getCallingUserId();
6563        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
6564        flags = updateFlagsForComponent(flags, userId, processName);
6565
6566        ArrayList<ProviderInfo> finalList = null;
6567        // reader
6568        synchronized (mPackages) {
6569            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
6570            while (i.hasNext()) {
6571                final PackageParser.Provider p = i.next();
6572                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
6573                if (ps != null && p.info.authority != null
6574                        && (processName == null
6575                                || (p.info.processName.equals(processName)
6576                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
6577                        && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
6578                    if (finalList == null) {
6579                        finalList = new ArrayList<ProviderInfo>(3);
6580                    }
6581                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
6582                            ps.readUserState(userId), userId);
6583                    if (info != null) {
6584                        finalList.add(info);
6585                    }
6586                }
6587            }
6588        }
6589
6590        if (finalList != null) {
6591            Collections.sort(finalList, mProviderInitOrderSorter);
6592            return new ParceledListSlice<ProviderInfo>(finalList);
6593        }
6594
6595        return ParceledListSlice.emptyList();
6596    }
6597
6598    @Override
6599    public InstrumentationInfo getInstrumentationInfo(ComponentName name, int flags) {
6600        // reader
6601        synchronized (mPackages) {
6602            final PackageParser.Instrumentation i = mInstrumentation.get(name);
6603            return PackageParser.generateInstrumentationInfo(i, flags);
6604        }
6605    }
6606
6607    @Override
6608    public @NonNull ParceledListSlice<InstrumentationInfo> queryInstrumentation(
6609            String targetPackage, int flags) {
6610        return new ParceledListSlice<>(queryInstrumentationInternal(targetPackage, flags));
6611    }
6612
6613    private @NonNull List<InstrumentationInfo> queryInstrumentationInternal(String targetPackage,
6614            int flags) {
6615        ArrayList<InstrumentationInfo> finalList = new ArrayList<InstrumentationInfo>();
6616
6617        // reader
6618        synchronized (mPackages) {
6619            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
6620            while (i.hasNext()) {
6621                final PackageParser.Instrumentation p = i.next();
6622                if (targetPackage == null
6623                        || targetPackage.equals(p.info.targetPackage)) {
6624                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
6625                            flags);
6626                    if (ii != null) {
6627                        finalList.add(ii);
6628                    }
6629                }
6630            }
6631        }
6632
6633        return finalList;
6634    }
6635
6636    private void createIdmapsForPackageLI(PackageParser.Package pkg) {
6637        ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName);
6638        if (overlays == null) {
6639            Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages");
6640            return;
6641        }
6642        for (PackageParser.Package opkg : overlays.values()) {
6643            // Not much to do if idmap fails: we already logged the error
6644            // and we certainly don't want to abort installation of pkg simply
6645            // because an overlay didn't fit properly. For these reasons,
6646            // ignore the return value of createIdmapForPackagePairLI.
6647            createIdmapForPackagePairLI(pkg, opkg);
6648        }
6649    }
6650
6651    private boolean createIdmapForPackagePairLI(PackageParser.Package pkg,
6652            PackageParser.Package opkg) {
6653        if (!opkg.mTrustedOverlay) {
6654            Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " +
6655                    opkg.baseCodePath + ": overlay not trusted");
6656            return false;
6657        }
6658        ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName);
6659        if (overlaySet == null) {
6660            Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " +
6661                    opkg.baseCodePath + " but target package has no known overlays");
6662            return false;
6663        }
6664        final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
6665        // TODO: generate idmap for split APKs
6666        try {
6667            mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid);
6668        } catch (InstallerException e) {
6669            Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and "
6670                    + opkg.baseCodePath);
6671            return false;
6672        }
6673        PackageParser.Package[] overlayArray =
6674            overlaySet.values().toArray(new PackageParser.Package[0]);
6675        Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() {
6676            public int compare(PackageParser.Package p1, PackageParser.Package p2) {
6677                return p1.mOverlayPriority - p2.mOverlayPriority;
6678            }
6679        };
6680        Arrays.sort(overlayArray, cmp);
6681
6682        pkg.applicationInfo.resourceDirs = new String[overlayArray.length];
6683        int i = 0;
6684        for (PackageParser.Package p : overlayArray) {
6685            pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath;
6686        }
6687        return true;
6688    }
6689
6690    private void scanDirTracedLI(File dir, final int parseFlags, int scanFlags, long currentTime) {
6691        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir");
6692        try {
6693            scanDirLI(dir, parseFlags, scanFlags, currentTime);
6694        } finally {
6695            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6696        }
6697    }
6698
6699    private void scanDirLI(File dir, final int parseFlags, int scanFlags, long currentTime) {
6700        final File[] files = dir.listFiles();
6701        if (ArrayUtils.isEmpty(files)) {
6702            Log.d(TAG, "No files in app dir " + dir);
6703            return;
6704        }
6705
6706        if (DEBUG_PACKAGE_SCANNING) {
6707            Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags
6708                    + " flags=0x" + Integer.toHexString(parseFlags));
6709        }
6710
6711        for (File file : files) {
6712            final boolean isPackage = (isApkFile(file) || file.isDirectory())
6713                    && !PackageInstallerService.isStageName(file.getName());
6714            if (!isPackage) {
6715                // Ignore entries which are not packages
6716                continue;
6717            }
6718            try {
6719                scanPackageTracedLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK,
6720                        scanFlags, currentTime, null);
6721            } catch (PackageManagerException e) {
6722                Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage());
6723
6724                // Delete invalid userdata apps
6725                if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
6726                        e.error == PackageManager.INSTALL_FAILED_INVALID_APK) {
6727                    logCriticalInfo(Log.WARN, "Deleting invalid package at " + file);
6728                    removeCodePathLI(file);
6729                }
6730            }
6731        }
6732    }
6733
6734    private static File getSettingsProblemFile() {
6735        File dataDir = Environment.getDataDirectory();
6736        File systemDir = new File(dataDir, "system");
6737        File fname = new File(systemDir, "uiderrors.txt");
6738        return fname;
6739    }
6740
6741    static void reportSettingsProblem(int priority, String msg) {
6742        logCriticalInfo(priority, msg);
6743    }
6744
6745    static void logCriticalInfo(int priority, String msg) {
6746        Slog.println(priority, TAG, msg);
6747        EventLogTags.writePmCriticalInfo(msg);
6748        try {
6749            File fname = getSettingsProblemFile();
6750            FileOutputStream out = new FileOutputStream(fname, true);
6751            PrintWriter pw = new FastPrintWriter(out);
6752            SimpleDateFormat formatter = new SimpleDateFormat();
6753            String dateString = formatter.format(new Date(System.currentTimeMillis()));
6754            pw.println(dateString + ": " + msg);
6755            pw.close();
6756            FileUtils.setPermissions(
6757                    fname.toString(),
6758                    FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
6759                    -1, -1);
6760        } catch (java.io.IOException e) {
6761        }
6762    }
6763
6764    private void collectCertificatesLI(PackageSetting ps, PackageParser.Package pkg, File srcFile,
6765            final int policyFlags) throws PackageManagerException {
6766        if (ps != null
6767                && ps.codePath.equals(srcFile)
6768                && ps.timeStamp == srcFile.lastModified()
6769                && !isCompatSignatureUpdateNeeded(pkg)
6770                && !isRecoverSignatureUpdateNeeded(pkg)) {
6771            long mSigningKeySetId = ps.keySetData.getProperSigningKeySet();
6772            KeySetManagerService ksms = mSettings.mKeySetManagerService;
6773            ArraySet<PublicKey> signingKs;
6774            synchronized (mPackages) {
6775                signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId);
6776            }
6777            if (ps.signatures.mSignatures != null
6778                    && ps.signatures.mSignatures.length != 0
6779                    && signingKs != null) {
6780                // Optimization: reuse the existing cached certificates
6781                // if the package appears to be unchanged.
6782                pkg.mSignatures = ps.signatures.mSignatures;
6783                pkg.mSigningKeys = signingKs;
6784                return;
6785            }
6786
6787            Slog.w(TAG, "PackageSetting for " + ps.name
6788                    + " is missing signatures.  Collecting certs again to recover them.");
6789        } else {
6790            Log.i(TAG, srcFile.toString() + " changed; collecting certs");
6791        }
6792
6793        try {
6794            PackageParser.collectCertificates(pkg, policyFlags);
6795        } catch (PackageParserException e) {
6796            throw PackageManagerException.from(e);
6797        }
6798    }
6799
6800    /**
6801     *  Traces a package scan.
6802     *  @see #scanPackageLI(File, int, int, long, UserHandle)
6803     */
6804    private PackageParser.Package scanPackageTracedLI(File scanFile, final int parseFlags,
6805            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
6806        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage");
6807        try {
6808            return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user);
6809        } finally {
6810            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6811        }
6812    }
6813
6814    /**
6815     *  Scans a package and returns the newly parsed package.
6816     *  Returns {@code null} in case of errors and the error code is stored in mLastScanError
6817     */
6818    private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags,
6819            long currentTime, UserHandle user) throws PackageManagerException {
6820        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
6821        PackageParser pp = new PackageParser();
6822        pp.setSeparateProcesses(mSeparateProcesses);
6823        pp.setOnlyCoreApps(mOnlyCore);
6824        pp.setDisplayMetrics(mMetrics);
6825
6826        if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) {
6827            parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY;
6828        }
6829
6830        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
6831        final PackageParser.Package pkg;
6832        try {
6833            pkg = pp.parsePackage(scanFile, parseFlags);
6834        } catch (PackageParserException e) {
6835            throw PackageManagerException.from(e);
6836        } finally {
6837            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6838        }
6839
6840        return scanPackageLI(pkg, scanFile, parseFlags, scanFlags, currentTime, user);
6841    }
6842
6843    /**
6844     *  Scans a package and returns the newly parsed package.
6845     *  @throws PackageManagerException on a parse error.
6846     */
6847    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, File scanFile,
6848            final int policyFlags, int scanFlags, long currentTime, UserHandle user)
6849            throws PackageManagerException {
6850        // If the package has children and this is the first dive in the function
6851        // we scan the package with the SCAN_CHECK_ONLY flag set to see whether all
6852        // packages (parent and children) would be successfully scanned before the
6853        // actual scan since scanning mutates internal state and we want to atomically
6854        // install the package and its children.
6855        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
6856            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
6857                scanFlags |= SCAN_CHECK_ONLY;
6858            }
6859        } else {
6860            scanFlags &= ~SCAN_CHECK_ONLY;
6861        }
6862
6863        // Scan the parent
6864        PackageParser.Package scannedPkg = scanPackageInternalLI(pkg, scanFile, policyFlags,
6865                scanFlags, currentTime, user);
6866
6867        // Scan the children
6868        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
6869        for (int i = 0; i < childCount; i++) {
6870            PackageParser.Package childPackage = pkg.childPackages.get(i);
6871            scanPackageInternalLI(childPackage, scanFile, policyFlags, scanFlags,
6872                    currentTime, user);
6873        }
6874
6875
6876        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
6877            return scanPackageLI(pkg, scanFile, policyFlags, scanFlags, currentTime, user);
6878        }
6879
6880        return scannedPkg;
6881    }
6882
6883    /**
6884     *  Scans a package and returns the newly parsed package.
6885     *  @throws PackageManagerException on a parse error.
6886     */
6887    private PackageParser.Package scanPackageInternalLI(PackageParser.Package pkg, File scanFile,
6888            int policyFlags, int scanFlags, long currentTime, UserHandle user)
6889            throws PackageManagerException {
6890        PackageSetting ps = null;
6891        PackageSetting updatedPkg;
6892        // reader
6893        synchronized (mPackages) {
6894            // Look to see if we already know about this package.
6895            String oldName = mSettings.mRenamedPackages.get(pkg.packageName);
6896            if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
6897                // This package has been renamed to its original name.  Let's
6898                // use that.
6899                ps = mSettings.peekPackageLPr(oldName);
6900            }
6901            // If there was no original package, see one for the real package name.
6902            if (ps == null) {
6903                ps = mSettings.peekPackageLPr(pkg.packageName);
6904            }
6905            // Check to see if this package could be hiding/updating a system
6906            // package.  Must look for it either under the original or real
6907            // package name depending on our state.
6908            updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName);
6909            if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg);
6910
6911            // If this is a package we don't know about on the system partition, we
6912            // may need to remove disabled child packages on the system partition
6913            // or may need to not add child packages if the parent apk is updated
6914            // on the data partition and no longer defines this child package.
6915            if ((policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) {
6916                // If this is a parent package for an updated system app and this system
6917                // app got an OTA update which no longer defines some of the child packages
6918                // we have to prune them from the disabled system packages.
6919                PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName);
6920                if (disabledPs != null) {
6921                    final int scannedChildCount = (pkg.childPackages != null)
6922                            ? pkg.childPackages.size() : 0;
6923                    final int disabledChildCount = disabledPs.childPackageNames != null
6924                            ? disabledPs.childPackageNames.size() : 0;
6925                    for (int i = 0; i < disabledChildCount; i++) {
6926                        String disabledChildPackageName = disabledPs.childPackageNames.get(i);
6927                        boolean disabledPackageAvailable = false;
6928                        for (int j = 0; j < scannedChildCount; j++) {
6929                            PackageParser.Package childPkg = pkg.childPackages.get(j);
6930                            if (childPkg.packageName.equals(disabledChildPackageName)) {
6931                                disabledPackageAvailable = true;
6932                                break;
6933                            }
6934                         }
6935                         if (!disabledPackageAvailable) {
6936                             mSettings.removeDisabledSystemPackageLPw(disabledChildPackageName);
6937                         }
6938                    }
6939                }
6940            }
6941        }
6942
6943        boolean updatedPkgBetter = false;
6944        // First check if this is a system package that may involve an update
6945        if (updatedPkg != null && (policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) {
6946            // If new package is not located in "/system/priv-app" (e.g. due to an OTA),
6947            // it needs to drop FLAG_PRIVILEGED.
6948            if (locationIsPrivileged(scanFile)) {
6949                updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
6950            } else {
6951                updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
6952            }
6953
6954            if (ps != null && !ps.codePath.equals(scanFile)) {
6955                // The path has changed from what was last scanned...  check the
6956                // version of the new path against what we have stored to determine
6957                // what to do.
6958                if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath);
6959                if (pkg.mVersionCode <= ps.versionCode) {
6960                    // The system package has been updated and the code path does not match
6961                    // Ignore entry. Skip it.
6962                    if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile
6963                            + " ignored: updated version " + ps.versionCode
6964                            + " better than this " + pkg.mVersionCode);
6965                    if (!updatedPkg.codePath.equals(scanFile)) {
6966                        Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg "
6967                                + ps.name + " changing from " + updatedPkg.codePathString
6968                                + " to " + scanFile);
6969                        updatedPkg.codePath = scanFile;
6970                        updatedPkg.codePathString = scanFile.toString();
6971                        updatedPkg.resourcePath = scanFile;
6972                        updatedPkg.resourcePathString = scanFile.toString();
6973                    }
6974                    updatedPkg.pkg = pkg;
6975                    updatedPkg.versionCode = pkg.mVersionCode;
6976
6977                    // Update the disabled system child packages to point to the package too.
6978                    final int childCount = updatedPkg.childPackageNames != null
6979                            ? updatedPkg.childPackageNames.size() : 0;
6980                    for (int i = 0; i < childCount; i++) {
6981                        String childPackageName = updatedPkg.childPackageNames.get(i);
6982                        PackageSetting updatedChildPkg = mSettings.getDisabledSystemPkgLPr(
6983                                childPackageName);
6984                        if (updatedChildPkg != null) {
6985                            updatedChildPkg.pkg = pkg;
6986                            updatedChildPkg.versionCode = pkg.mVersionCode;
6987                        }
6988                    }
6989
6990                    throw new PackageManagerException(Log.WARN, "Package " + ps.name + " at "
6991                            + scanFile + " ignored: updated version " + ps.versionCode
6992                            + " better than this " + pkg.mVersionCode);
6993                } else {
6994                    // The current app on the system partition is better than
6995                    // what we have updated to on the data partition; switch
6996                    // back to the system partition version.
6997                    // At this point, its safely assumed that package installation for
6998                    // apps in system partition will go through. If not there won't be a working
6999                    // version of the app
7000                    // writer
7001                    synchronized (mPackages) {
7002                        // Just remove the loaded entries from package lists.
7003                        mPackages.remove(ps.name);
7004                    }
7005
7006                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
7007                            + " reverting from " + ps.codePathString
7008                            + ": new version " + pkg.mVersionCode
7009                            + " better than installed " + ps.versionCode);
7010
7011                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
7012                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
7013                    synchronized (mInstallLock) {
7014                        args.cleanUpResourcesLI();
7015                    }
7016                    synchronized (mPackages) {
7017                        mSettings.enableSystemPackageLPw(ps.name);
7018                    }
7019                    updatedPkgBetter = true;
7020                }
7021            }
7022        }
7023
7024        if (updatedPkg != null) {
7025            // An updated system app will not have the PARSE_IS_SYSTEM flag set
7026            // initially
7027            policyFlags |= PackageParser.PARSE_IS_SYSTEM;
7028
7029            // An updated privileged app will not have the PARSE_IS_PRIVILEGED
7030            // flag set initially
7031            if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
7032                policyFlags |= PackageParser.PARSE_IS_PRIVILEGED;
7033            }
7034        }
7035
7036        // Verify certificates against what was last scanned
7037        collectCertificatesLI(ps, pkg, scanFile, policyFlags);
7038
7039        /*
7040         * A new system app appeared, but we already had a non-system one of the
7041         * same name installed earlier.
7042         */
7043        boolean shouldHideSystemApp = false;
7044        if (updatedPkg == null && ps != null
7045                && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) {
7046            /*
7047             * Check to make sure the signatures match first. If they don't,
7048             * wipe the installed application and its data.
7049             */
7050            if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures)
7051                    != PackageManager.SIGNATURE_MATCH) {
7052                logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but"
7053                        + " signatures don't match existing userdata copy; removing");
7054                try (PackageFreezer freezer = freezePackage(pkg.packageName,
7055                        "scanPackageInternalLI")) {
7056                    deletePackageLIF(pkg.packageName, null, true, null, 0, null, false, null);
7057                }
7058                ps = null;
7059            } else {
7060                /*
7061                 * If the newly-added system app is an older version than the
7062                 * already installed version, hide it. It will be scanned later
7063                 * and re-added like an update.
7064                 */
7065                if (pkg.mVersionCode <= ps.versionCode) {
7066                    shouldHideSystemApp = true;
7067                    logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile
7068                            + " but new version " + pkg.mVersionCode + " better than installed "
7069                            + ps.versionCode + "; hiding system");
7070                } else {
7071                    /*
7072                     * The newly found system app is a newer version that the
7073                     * one previously installed. Simply remove the
7074                     * already-installed application and replace it with our own
7075                     * while keeping the application data.
7076                     */
7077                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
7078                            + " reverting from " + ps.codePathString + ": new version "
7079                            + pkg.mVersionCode + " better than installed " + ps.versionCode);
7080                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
7081                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
7082                    synchronized (mInstallLock) {
7083                        args.cleanUpResourcesLI();
7084                    }
7085                }
7086            }
7087        }
7088
7089        // The apk is forward locked (not public) if its code and resources
7090        // are kept in different files. (except for app in either system or
7091        // vendor path).
7092        // TODO grab this value from PackageSettings
7093        if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
7094            if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
7095                policyFlags |= PackageParser.PARSE_FORWARD_LOCK;
7096            }
7097        }
7098
7099        // TODO: extend to support forward-locked splits
7100        String resourcePath = null;
7101        String baseResourcePath = null;
7102        if ((policyFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) {
7103            if (ps != null && ps.resourcePathString != null) {
7104                resourcePath = ps.resourcePathString;
7105                baseResourcePath = ps.resourcePathString;
7106            } else {
7107                // Should not happen at all. Just log an error.
7108                Slog.e(TAG, "Resource path not set for package " + pkg.packageName);
7109            }
7110        } else {
7111            resourcePath = pkg.codePath;
7112            baseResourcePath = pkg.baseCodePath;
7113        }
7114
7115        // Set application objects path explicitly.
7116        pkg.setApplicationVolumeUuid(pkg.volumeUuid);
7117        pkg.setApplicationInfoCodePath(pkg.codePath);
7118        pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
7119        pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
7120        pkg.setApplicationInfoResourcePath(resourcePath);
7121        pkg.setApplicationInfoBaseResourcePath(baseResourcePath);
7122        pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
7123
7124        // Note that we invoke the following method only if we are about to unpack an application
7125        PackageParser.Package scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags
7126                | SCAN_UPDATE_SIGNATURE, currentTime, user);
7127
7128        /*
7129         * If the system app should be overridden by a previously installed
7130         * data, hide the system app now and let the /data/app scan pick it up
7131         * again.
7132         */
7133        if (shouldHideSystemApp) {
7134            synchronized (mPackages) {
7135                mSettings.disableSystemPackageLPw(pkg.packageName, true);
7136            }
7137        }
7138
7139        return scannedPkg;
7140    }
7141
7142    private static String fixProcessName(String defProcessName,
7143            String processName, int uid) {
7144        if (processName == null) {
7145            return defProcessName;
7146        }
7147        return processName;
7148    }
7149
7150    private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg)
7151            throws PackageManagerException {
7152        if (pkgSetting.signatures.mSignatures != null) {
7153            // Already existing package. Make sure signatures match
7154            boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures)
7155                    == PackageManager.SIGNATURE_MATCH;
7156            if (!match) {
7157                match = compareSignaturesCompat(pkgSetting.signatures, pkg)
7158                        == PackageManager.SIGNATURE_MATCH;
7159            }
7160            if (!match) {
7161                match = compareSignaturesRecover(pkgSetting.signatures, pkg)
7162                        == PackageManager.SIGNATURE_MATCH;
7163            }
7164            if (!match) {
7165                throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
7166                        + pkg.packageName + " signatures do not match the "
7167                        + "previously installed version; ignoring!");
7168            }
7169        }
7170
7171        // Check for shared user signatures
7172        if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
7173            // Already existing package. Make sure signatures match
7174            boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
7175                    pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
7176            if (!match) {
7177                match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg)
7178                        == PackageManager.SIGNATURE_MATCH;
7179            }
7180            if (!match) {
7181                match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg)
7182                        == PackageManager.SIGNATURE_MATCH;
7183            }
7184            if (!match) {
7185                throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
7186                        "Package " + pkg.packageName
7187                        + " has no signatures that match those in shared user "
7188                        + pkgSetting.sharedUser.name + "; ignoring!");
7189            }
7190        }
7191    }
7192
7193    /**
7194     * Enforces that only the system UID or root's UID can call a method exposed
7195     * via Binder.
7196     *
7197     * @param message used as message if SecurityException is thrown
7198     * @throws SecurityException if the caller is not system or root
7199     */
7200    private static final void enforceSystemOrRoot(String message) {
7201        final int uid = Binder.getCallingUid();
7202        if (uid != Process.SYSTEM_UID && uid != 0) {
7203            throw new SecurityException(message);
7204        }
7205    }
7206
7207    @Override
7208    public void performFstrimIfNeeded() {
7209        enforceSystemOrRoot("Only the system can request fstrim");
7210
7211        // Before everything else, see whether we need to fstrim.
7212        try {
7213            IMountService ms = PackageHelper.getMountService();
7214            if (ms != null) {
7215                final boolean isUpgrade = isUpgrade();
7216                boolean doTrim = isUpgrade;
7217                if (doTrim) {
7218                    Slog.w(TAG, "Running disk maintenance immediately due to system update");
7219                } else {
7220                    final long interval = android.provider.Settings.Global.getLong(
7221                            mContext.getContentResolver(),
7222                            android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL,
7223                            DEFAULT_MANDATORY_FSTRIM_INTERVAL);
7224                    if (interval > 0) {
7225                        final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance();
7226                        if (timeSinceLast > interval) {
7227                            doTrim = true;
7228                            Slog.w(TAG, "No disk maintenance in " + timeSinceLast
7229                                    + "; running immediately");
7230                        }
7231                    }
7232                }
7233                if (doTrim) {
7234                    if (!isFirstBoot()) {
7235                        try {
7236                            ActivityManagerNative.getDefault().showBootMessage(
7237                                    mContext.getResources().getString(
7238                                            R.string.android_upgrading_fstrim), true);
7239                        } catch (RemoteException e) {
7240                        }
7241                    }
7242                    ms.runMaintenance();
7243                }
7244            } else {
7245                Slog.e(TAG, "Mount service unavailable!");
7246            }
7247        } catch (RemoteException e) {
7248            // Can't happen; MountService is local
7249        }
7250    }
7251
7252    @Override
7253    public void updatePackagesIfNeeded() {
7254        enforceSystemOrRoot("Only the system can request package update");
7255
7256        // We need to re-extract after an OTA.
7257        boolean causeUpgrade = isUpgrade();
7258
7259        // First boot or factory reset.
7260        // Note: we also handle devices that are upgrading to N right now as if it is their
7261        //       first boot, as they do not have profile data.
7262        boolean causeFirstBoot = isFirstBoot() || mIsPreNUpgrade;
7263
7264        // We need to re-extract after a pruned cache, as AoT-ed files will be out of date.
7265        boolean causePrunedCache = VMRuntime.didPruneDalvikCache();
7266
7267        if (!causeUpgrade && !causeFirstBoot && !causePrunedCache) {
7268            return;
7269        }
7270
7271        List<PackageParser.Package> pkgs;
7272        synchronized (mPackages) {
7273            pkgs = PackageManagerServiceUtils.getPackagesForDexopt(mPackages.values(), this);
7274        }
7275
7276        final long startTime = System.nanoTime();
7277        final int[] stats = performDexOpt(pkgs, mIsPreNUpgrade /* showDialog */,
7278                    getCompilerFilterForReason(causeFirstBoot ? REASON_FIRST_BOOT : REASON_BOOT));
7279
7280        final int elapsedTimeSeconds =
7281                (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - startTime);
7282
7283        MetricsLogger.histogram(mContext, "opt_dialog_num_dexopted", stats[0]);
7284        MetricsLogger.histogram(mContext, "opt_dialog_num_skipped", stats[1]);
7285        MetricsLogger.histogram(mContext, "opt_dialog_num_failed", stats[2]);
7286        MetricsLogger.histogram(mContext, "opt_dialog_num_total", getOptimizablePackages().size());
7287        MetricsLogger.histogram(mContext, "opt_dialog_time_s", elapsedTimeSeconds);
7288    }
7289
7290    /**
7291     * Performs dexopt on the set of packages in {@code packages} and returns an int array
7292     * containing statistics about the invocation. The array consists of three elements,
7293     * which are (in order) {@code numberOfPackagesOptimized}, {@code numberOfPackagesSkipped}
7294     * and {@code numberOfPackagesFailed}.
7295     */
7296    private int[] performDexOpt(List<PackageParser.Package> pkgs, boolean showDialog,
7297            String compilerFilter) {
7298
7299        int numberOfPackagesVisited = 0;
7300        int numberOfPackagesOptimized = 0;
7301        int numberOfPackagesSkipped = 0;
7302        int numberOfPackagesFailed = 0;
7303        final int numberOfPackagesToDexopt = pkgs.size();
7304
7305        for (PackageParser.Package pkg : pkgs) {
7306            numberOfPackagesVisited++;
7307
7308            if (!PackageDexOptimizer.canOptimizePackage(pkg)) {
7309                if (DEBUG_DEXOPT) {
7310                    Log.i(TAG, "Skipping update of of non-optimizable app " + pkg.packageName);
7311                }
7312                numberOfPackagesSkipped++;
7313                continue;
7314            }
7315
7316            if (DEBUG_DEXOPT) {
7317                Log.i(TAG, "Updating app " + numberOfPackagesVisited + " of " +
7318                        numberOfPackagesToDexopt + ": " + pkg.packageName);
7319            }
7320
7321            if (showDialog) {
7322                try {
7323                    ActivityManagerNative.getDefault().showBootMessage(
7324                            mContext.getResources().getString(R.string.android_upgrading_apk,
7325                                    numberOfPackagesVisited, numberOfPackagesToDexopt), true);
7326                } catch (RemoteException e) {
7327                }
7328            }
7329
7330            // checkProfiles is false to avoid merging profiles during boot which
7331            // might interfere with background compilation (b/28612421).
7332            // Unfortunately this will also means that "pm.dexopt.boot=speed-profile" will
7333            // behave differently than "pm.dexopt.bg-dexopt=speed-profile" but that's a
7334            // trade-off worth doing to save boot time work.
7335            int dexOptStatus = performDexOptTraced(pkg.packageName,
7336                    false /* checkProfiles */,
7337                    compilerFilter,
7338                    false /* force */);
7339            switch (dexOptStatus) {
7340                case PackageDexOptimizer.DEX_OPT_PERFORMED:
7341                    numberOfPackagesOptimized++;
7342                    break;
7343                case PackageDexOptimizer.DEX_OPT_SKIPPED:
7344                    numberOfPackagesSkipped++;
7345                    break;
7346                case PackageDexOptimizer.DEX_OPT_FAILED:
7347                    numberOfPackagesFailed++;
7348                    break;
7349                default:
7350                    Log.e(TAG, "Unexpected dexopt return code " + dexOptStatus);
7351                    break;
7352            }
7353        }
7354
7355        return new int[] { numberOfPackagesOptimized, numberOfPackagesSkipped,
7356                numberOfPackagesFailed };
7357    }
7358
7359    @Override
7360    public void notifyPackageUse(String packageName, int reason) {
7361        synchronized (mPackages) {
7362            PackageParser.Package p = mPackages.get(packageName);
7363            if (p == null) {
7364                return;
7365            }
7366            p.mLastPackageUsageTimeInMills[reason] = System.currentTimeMillis();
7367        }
7368    }
7369
7370    // TODO: this is not used nor needed. Delete it.
7371    @Override
7372    public boolean performDexOptIfNeeded(String packageName) {
7373        int dexOptStatus = performDexOptTraced(packageName,
7374                false /* checkProfiles */, getFullCompilerFilter(), false /* force */);
7375        return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
7376    }
7377
7378    @Override
7379    public boolean performDexOpt(String packageName,
7380            boolean checkProfiles, int compileReason, boolean force) {
7381        int dexOptStatus = performDexOptTraced(packageName, checkProfiles,
7382                getCompilerFilterForReason(compileReason), force);
7383        return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
7384    }
7385
7386    @Override
7387    public boolean performDexOptMode(String packageName,
7388            boolean checkProfiles, String targetCompilerFilter, boolean force) {
7389        int dexOptStatus = performDexOptTraced(packageName, checkProfiles,
7390                targetCompilerFilter, force);
7391        return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
7392    }
7393
7394    private int performDexOptTraced(String packageName,
7395                boolean checkProfiles, String targetCompilerFilter, boolean force) {
7396        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
7397        try {
7398            return performDexOptInternal(packageName, checkProfiles,
7399                    targetCompilerFilter, force);
7400        } finally {
7401            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7402        }
7403    }
7404
7405    // Run dexopt on a given package. Returns true if dexopt did not fail, i.e.
7406    // if the package can now be considered up to date for the given filter.
7407    private int performDexOptInternal(String packageName,
7408                boolean checkProfiles, String targetCompilerFilter, boolean force) {
7409        PackageParser.Package p;
7410        synchronized (mPackages) {
7411            p = mPackages.get(packageName);
7412            if (p == null) {
7413                // Package could not be found. Report failure.
7414                return PackageDexOptimizer.DEX_OPT_FAILED;
7415            }
7416            mPackageUsage.write(false);
7417        }
7418        long callingId = Binder.clearCallingIdentity();
7419        try {
7420            synchronized (mInstallLock) {
7421                return performDexOptInternalWithDependenciesLI(p, checkProfiles,
7422                        targetCompilerFilter, force);
7423            }
7424        } finally {
7425            Binder.restoreCallingIdentity(callingId);
7426        }
7427    }
7428
7429    public ArraySet<String> getOptimizablePackages() {
7430        ArraySet<String> pkgs = new ArraySet<String>();
7431        synchronized (mPackages) {
7432            for (PackageParser.Package p : mPackages.values()) {
7433                if (PackageDexOptimizer.canOptimizePackage(p)) {
7434                    pkgs.add(p.packageName);
7435                }
7436            }
7437        }
7438        return pkgs;
7439    }
7440
7441    private int performDexOptInternalWithDependenciesLI(PackageParser.Package p,
7442            boolean checkProfiles, String targetCompilerFilter,
7443            boolean force) {
7444        // Select the dex optimizer based on the force parameter.
7445        // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to
7446        //       allocate an object here.
7447        PackageDexOptimizer pdo = force
7448                ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer)
7449                : mPackageDexOptimizer;
7450
7451        // Optimize all dependencies first. Note: we ignore the return value and march on
7452        // on errors.
7453        Collection<PackageParser.Package> deps = findSharedNonSystemLibraries(p);
7454        final String[] instructionSets = getAppDexInstructionSets(p.applicationInfo);
7455        if (!deps.isEmpty()) {
7456            for (PackageParser.Package depPackage : deps) {
7457                // TODO: Analyze and investigate if we (should) profile libraries.
7458                // Currently this will do a full compilation of the library by default.
7459                pdo.performDexOpt(depPackage, null /* sharedLibraries */, instructionSets,
7460                        false /* checkProfiles */,
7461                        getCompilerFilterForReason(REASON_NON_SYSTEM_LIBRARY));
7462            }
7463        }
7464        return pdo.performDexOpt(p, p.usesLibraryFiles, instructionSets, checkProfiles,
7465                targetCompilerFilter);
7466    }
7467
7468    Collection<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package p) {
7469        if (p.usesLibraries != null || p.usesOptionalLibraries != null) {
7470            ArrayList<PackageParser.Package> retValue = new ArrayList<>();
7471            Set<String> collectedNames = new HashSet<>();
7472            findSharedNonSystemLibrariesRecursive(p, retValue, collectedNames);
7473
7474            retValue.remove(p);
7475
7476            return retValue;
7477        } else {
7478            return Collections.emptyList();
7479        }
7480    }
7481
7482    private void findSharedNonSystemLibrariesRecursive(PackageParser.Package p,
7483            Collection<PackageParser.Package> collected, Set<String> collectedNames) {
7484        if (!collectedNames.contains(p.packageName)) {
7485            collectedNames.add(p.packageName);
7486            collected.add(p);
7487
7488            if (p.usesLibraries != null) {
7489                findSharedNonSystemLibrariesRecursive(p.usesLibraries, collected, collectedNames);
7490            }
7491            if (p.usesOptionalLibraries != null) {
7492                findSharedNonSystemLibrariesRecursive(p.usesOptionalLibraries, collected,
7493                        collectedNames);
7494            }
7495        }
7496    }
7497
7498    private void findSharedNonSystemLibrariesRecursive(Collection<String> libs,
7499            Collection<PackageParser.Package> collected, Set<String> collectedNames) {
7500        for (String libName : libs) {
7501            PackageParser.Package libPkg = findSharedNonSystemLibrary(libName);
7502            if (libPkg != null) {
7503                findSharedNonSystemLibrariesRecursive(libPkg, collected, collectedNames);
7504            }
7505        }
7506    }
7507
7508    private PackageParser.Package findSharedNonSystemLibrary(String libName) {
7509        synchronized (mPackages) {
7510            PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName);
7511            if (lib != null && lib.apk != null) {
7512                return mPackages.get(lib.apk);
7513            }
7514        }
7515        return null;
7516    }
7517
7518    public void shutdown() {
7519        mPackageUsage.write(true);
7520    }
7521
7522    @Override
7523    public void dumpProfiles(String packageName) {
7524        PackageParser.Package pkg;
7525        synchronized (mPackages) {
7526            pkg = mPackages.get(packageName);
7527            if (pkg == null) {
7528                throw new IllegalArgumentException("Unknown package: " + packageName);
7529            }
7530        }
7531        /* Only the shell, root, or the app user should be able to dump profiles. */
7532        int callingUid = Binder.getCallingUid();
7533        if (callingUid != Process.SHELL_UID &&
7534            callingUid != Process.ROOT_UID &&
7535            callingUid != pkg.applicationInfo.uid) {
7536            throw new SecurityException("dumpProfiles");
7537        }
7538
7539        synchronized (mInstallLock) {
7540            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dump profiles");
7541            final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
7542            try {
7543                List<String> allCodePaths = pkg.getAllCodePathsExcludingResourceOnly();
7544                String gid = Integer.toString(sharedGid);
7545                String codePaths = TextUtils.join(";", allCodePaths);
7546                mInstaller.dumpProfiles(gid, packageName, codePaths);
7547            } catch (InstallerException e) {
7548                Slog.w(TAG, "Failed to dump profiles", e);
7549            }
7550            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7551        }
7552    }
7553
7554    @Override
7555    public void forceDexOpt(String packageName) {
7556        enforceSystemOrRoot("forceDexOpt");
7557
7558        PackageParser.Package pkg;
7559        synchronized (mPackages) {
7560            pkg = mPackages.get(packageName);
7561            if (pkg == null) {
7562                throw new IllegalArgumentException("Unknown package: " + packageName);
7563            }
7564        }
7565
7566        synchronized (mInstallLock) {
7567            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
7568
7569            // Whoever is calling forceDexOpt wants a fully compiled package.
7570            // Don't use profiles since that may cause compilation to be skipped.
7571            final int res = performDexOptInternalWithDependenciesLI(pkg,
7572                    false /* checkProfiles */, getCompilerFilterForReason(REASON_FORCED_DEXOPT),
7573                    true /* force */);
7574
7575            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7576            if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) {
7577                throw new IllegalStateException("Failed to dexopt: " + res);
7578            }
7579        }
7580    }
7581
7582    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
7583        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
7584            Slog.w(TAG, "Unable to update from " + oldPkg.name
7585                    + " to " + newPkg.packageName
7586                    + ": old package not in system partition");
7587            return false;
7588        } else if (mPackages.get(oldPkg.name) != null) {
7589            Slog.w(TAG, "Unable to update from " + oldPkg.name
7590                    + " to " + newPkg.packageName
7591                    + ": old package still exists");
7592            return false;
7593        }
7594        return true;
7595    }
7596
7597    void removeCodePathLI(File codePath) {
7598        if (codePath.isDirectory()) {
7599            try {
7600                mInstaller.rmPackageDir(codePath.getAbsolutePath());
7601            } catch (InstallerException e) {
7602                Slog.w(TAG, "Failed to remove code path", e);
7603            }
7604        } else {
7605            codePath.delete();
7606        }
7607    }
7608
7609    private int[] resolveUserIds(int userId) {
7610        return (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() : new int[] { userId };
7611    }
7612
7613    private void clearAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
7614        if (pkg == null) {
7615            Slog.wtf(TAG, "Package was null!", new Throwable());
7616            return;
7617        }
7618        clearAppDataLeafLIF(pkg, userId, flags);
7619        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7620        for (int i = 0; i < childCount; i++) {
7621            clearAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
7622        }
7623    }
7624
7625    private void clearAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
7626        final PackageSetting ps;
7627        synchronized (mPackages) {
7628            ps = mSettings.mPackages.get(pkg.packageName);
7629        }
7630        for (int realUserId : resolveUserIds(userId)) {
7631            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
7632            try {
7633                mInstaller.clearAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
7634                        ceDataInode);
7635            } catch (InstallerException e) {
7636                Slog.w(TAG, String.valueOf(e));
7637            }
7638        }
7639    }
7640
7641    private void destroyAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
7642        if (pkg == null) {
7643            Slog.wtf(TAG, "Package was null!", new Throwable());
7644            return;
7645        }
7646        destroyAppDataLeafLIF(pkg, userId, flags);
7647        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7648        for (int i = 0; i < childCount; i++) {
7649            destroyAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
7650        }
7651    }
7652
7653    private void destroyAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
7654        final PackageSetting ps;
7655        synchronized (mPackages) {
7656            ps = mSettings.mPackages.get(pkg.packageName);
7657        }
7658        for (int realUserId : resolveUserIds(userId)) {
7659            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
7660            try {
7661                mInstaller.destroyAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
7662                        ceDataInode);
7663            } catch (InstallerException e) {
7664                Slog.w(TAG, String.valueOf(e));
7665            }
7666        }
7667    }
7668
7669    private void destroyAppProfilesLIF(PackageParser.Package pkg, int userId) {
7670        if (pkg == null) {
7671            Slog.wtf(TAG, "Package was null!", new Throwable());
7672            return;
7673        }
7674        destroyAppProfilesLeafLIF(pkg);
7675        destroyAppReferenceProfileLeafLIF(pkg, userId, true /* removeBaseMarker */);
7676        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7677        for (int i = 0; i < childCount; i++) {
7678            destroyAppProfilesLeafLIF(pkg.childPackages.get(i));
7679            destroyAppReferenceProfileLeafLIF(pkg.childPackages.get(i), userId,
7680                    true /* removeBaseMarker */);
7681        }
7682    }
7683
7684    private void destroyAppReferenceProfileLeafLIF(PackageParser.Package pkg, int userId,
7685            boolean removeBaseMarker) {
7686        if (pkg.isForwardLocked()) {
7687            return;
7688        }
7689
7690        for (String path : pkg.getAllCodePathsExcludingResourceOnly()) {
7691            try {
7692                path = PackageManagerServiceUtils.realpath(new File(path));
7693            } catch (IOException e) {
7694                // TODO: Should we return early here ?
7695                Slog.w(TAG, "Failed to get canonical path", e);
7696                continue;
7697            }
7698
7699            final String useMarker = path.replace('/', '@');
7700            for (int realUserId : resolveUserIds(userId)) {
7701                File profileDir = Environment.getDataProfilesDeForeignDexDirectory(realUserId);
7702                if (removeBaseMarker) {
7703                    File foreignUseMark = new File(profileDir, useMarker);
7704                    if (foreignUseMark.exists()) {
7705                        if (!foreignUseMark.delete()) {
7706                            Slog.w(TAG, "Unable to delete foreign user mark for package: "
7707                                    + pkg.packageName);
7708                        }
7709                    }
7710                }
7711
7712                File[] markers = profileDir.listFiles();
7713                if (markers != null) {
7714                    final String searchString = "@" + pkg.packageName + "@";
7715                    // We also delete all markers that contain the package name we're
7716                    // uninstalling. These are associated with secondary dex-files belonging
7717                    // to the package. Reconstructing the path of these dex files is messy
7718                    // in general.
7719                    for (File marker : markers) {
7720                        if (marker.getName().indexOf(searchString) > 0) {
7721                            if (!marker.delete()) {
7722                                Slog.w(TAG, "Unable to delete foreign user mark for package: "
7723                                    + pkg.packageName);
7724                            }
7725                        }
7726                    }
7727                }
7728            }
7729        }
7730    }
7731
7732    private void destroyAppProfilesLeafLIF(PackageParser.Package pkg) {
7733        try {
7734            mInstaller.destroyAppProfiles(pkg.packageName);
7735        } catch (InstallerException e) {
7736            Slog.w(TAG, String.valueOf(e));
7737        }
7738    }
7739
7740    private void clearAppProfilesLIF(PackageParser.Package pkg, int userId) {
7741        if (pkg == null) {
7742            Slog.wtf(TAG, "Package was null!", new Throwable());
7743            return;
7744        }
7745        clearAppProfilesLeafLIF(pkg);
7746        // We don't remove the base foreign use marker when clearing profiles because
7747        // we will rename it when the app is updated. Unlike the actual profile contents,
7748        // the foreign use marker is good across installs.
7749        destroyAppReferenceProfileLeafLIF(pkg, userId, false /* removeBaseMarker */);
7750        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7751        for (int i = 0; i < childCount; i++) {
7752            clearAppProfilesLeafLIF(pkg.childPackages.get(i));
7753        }
7754    }
7755
7756    private void clearAppProfilesLeafLIF(PackageParser.Package pkg) {
7757        try {
7758            mInstaller.clearAppProfiles(pkg.packageName);
7759        } catch (InstallerException e) {
7760            Slog.w(TAG, String.valueOf(e));
7761        }
7762    }
7763
7764    private void setInstallAndUpdateTime(PackageParser.Package pkg, long firstInstallTime,
7765            long lastUpdateTime) {
7766        // Set parent install/update time
7767        PackageSetting ps = (PackageSetting) pkg.mExtras;
7768        if (ps != null) {
7769            ps.firstInstallTime = firstInstallTime;
7770            ps.lastUpdateTime = lastUpdateTime;
7771        }
7772        // Set children install/update time
7773        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7774        for (int i = 0; i < childCount; i++) {
7775            PackageParser.Package childPkg = pkg.childPackages.get(i);
7776            ps = (PackageSetting) childPkg.mExtras;
7777            if (ps != null) {
7778                ps.firstInstallTime = firstInstallTime;
7779                ps.lastUpdateTime = lastUpdateTime;
7780            }
7781        }
7782    }
7783
7784    private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file,
7785            PackageParser.Package changingLib) {
7786        if (file.path != null) {
7787            usesLibraryFiles.add(file.path);
7788            return;
7789        }
7790        PackageParser.Package p = mPackages.get(file.apk);
7791        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
7792            // If we are doing this while in the middle of updating a library apk,
7793            // then we need to make sure to use that new apk for determining the
7794            // dependencies here.  (We haven't yet finished committing the new apk
7795            // to the package manager state.)
7796            if (p == null || p.packageName.equals(changingLib.packageName)) {
7797                p = changingLib;
7798            }
7799        }
7800        if (p != null) {
7801            usesLibraryFiles.addAll(p.getAllCodePaths());
7802        }
7803    }
7804
7805    private void updateSharedLibrariesLPw(PackageParser.Package pkg,
7806            PackageParser.Package changingLib) throws PackageManagerException {
7807        if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) {
7808            final ArraySet<String> usesLibraryFiles = new ArraySet<>();
7809            int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0;
7810            for (int i=0; i<N; i++) {
7811                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i));
7812                if (file == null) {
7813                    throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
7814                            "Package " + pkg.packageName + " requires unavailable shared library "
7815                            + pkg.usesLibraries.get(i) + "; failing!");
7816                }
7817                addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
7818            }
7819            N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0;
7820            for (int i=0; i<N; i++) {
7821                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i));
7822                if (file == null) {
7823                    Slog.w(TAG, "Package " + pkg.packageName
7824                            + " desires unavailable shared library "
7825                            + pkg.usesOptionalLibraries.get(i) + "; ignoring!");
7826                } else {
7827                    addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
7828                }
7829            }
7830            N = usesLibraryFiles.size();
7831            if (N > 0) {
7832                pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]);
7833            } else {
7834                pkg.usesLibraryFiles = null;
7835            }
7836        }
7837    }
7838
7839    private static boolean hasString(List<String> list, List<String> which) {
7840        if (list == null) {
7841            return false;
7842        }
7843        for (int i=list.size()-1; i>=0; i--) {
7844            for (int j=which.size()-1; j>=0; j--) {
7845                if (which.get(j).equals(list.get(i))) {
7846                    return true;
7847                }
7848            }
7849        }
7850        return false;
7851    }
7852
7853    private void updateAllSharedLibrariesLPw() {
7854        for (PackageParser.Package pkg : mPackages.values()) {
7855            try {
7856                updateSharedLibrariesLPw(pkg, null);
7857            } catch (PackageManagerException e) {
7858                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
7859            }
7860        }
7861    }
7862
7863    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
7864            PackageParser.Package changingPkg) {
7865        ArrayList<PackageParser.Package> res = null;
7866        for (PackageParser.Package pkg : mPackages.values()) {
7867            if (hasString(pkg.usesLibraries, changingPkg.libraryNames)
7868                    || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) {
7869                if (res == null) {
7870                    res = new ArrayList<PackageParser.Package>();
7871                }
7872                res.add(pkg);
7873                try {
7874                    updateSharedLibrariesLPw(pkg, changingPkg);
7875                } catch (PackageManagerException e) {
7876                    Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
7877                }
7878            }
7879        }
7880        return res;
7881    }
7882
7883    /**
7884     * Derive the value of the {@code cpuAbiOverride} based on the provided
7885     * value and an optional stored value from the package settings.
7886     */
7887    private static String deriveAbiOverride(String abiOverride, PackageSetting settings) {
7888        String cpuAbiOverride = null;
7889
7890        if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) {
7891            cpuAbiOverride = null;
7892        } else if (abiOverride != null) {
7893            cpuAbiOverride = abiOverride;
7894        } else if (settings != null) {
7895            cpuAbiOverride = settings.cpuAbiOverrideString;
7896        }
7897
7898        return cpuAbiOverride;
7899    }
7900
7901    private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg,
7902            final int policyFlags, int scanFlags, long currentTime, UserHandle user)
7903                    throws PackageManagerException {
7904        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage");
7905        // If the package has children and this is the first dive in the function
7906        // we recursively scan the package with the SCAN_CHECK_ONLY flag set to see
7907        // whether all packages (parent and children) would be successfully scanned
7908        // before the actual scan since scanning mutates internal state and we want
7909        // to atomically install the package and its children.
7910        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
7911            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
7912                scanFlags |= SCAN_CHECK_ONLY;
7913            }
7914        } else {
7915            scanFlags &= ~SCAN_CHECK_ONLY;
7916        }
7917
7918        final PackageParser.Package scannedPkg;
7919        try {
7920            // Scan the parent
7921            scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags, currentTime, user);
7922            // Scan the children
7923            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7924            for (int i = 0; i < childCount; i++) {
7925                PackageParser.Package childPkg = pkg.childPackages.get(i);
7926                scanPackageLI(childPkg, policyFlags,
7927                        scanFlags, currentTime, user);
7928            }
7929        } finally {
7930            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7931        }
7932
7933        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
7934            return scanPackageTracedLI(pkg, policyFlags, scanFlags, currentTime, user);
7935        }
7936
7937        return scannedPkg;
7938    }
7939
7940    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, final int policyFlags,
7941            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
7942        boolean success = false;
7943        try {
7944            final PackageParser.Package res = scanPackageDirtyLI(pkg, policyFlags, scanFlags,
7945                    currentTime, user);
7946            success = true;
7947            return res;
7948        } finally {
7949            if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
7950                // DELETE_DATA_ON_FAILURES is only used by frozen paths
7951                destroyAppDataLIF(pkg, UserHandle.USER_ALL,
7952                        StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
7953                destroyAppProfilesLIF(pkg, UserHandle.USER_ALL);
7954            }
7955        }
7956    }
7957
7958    /**
7959     * Returns {@code true} if the given file contains code. Otherwise {@code false}.
7960     */
7961    private static boolean apkHasCode(String fileName) {
7962        StrictJarFile jarFile = null;
7963        try {
7964            jarFile = new StrictJarFile(fileName,
7965                    false /*verify*/, false /*signatureSchemeRollbackProtectionsEnforced*/);
7966            return jarFile.findEntry("classes.dex") != null;
7967        } catch (IOException ignore) {
7968        } finally {
7969            try {
7970                jarFile.close();
7971            } catch (IOException ignore) {}
7972        }
7973        return false;
7974    }
7975
7976    /**
7977     * Enforces code policy for the package. This ensures that if an APK has
7978     * declared hasCode="true" in its manifest that the APK actually contains
7979     * code.
7980     *
7981     * @throws PackageManagerException If bytecode could not be found when it should exist
7982     */
7983    private static void enforceCodePolicy(PackageParser.Package pkg)
7984            throws PackageManagerException {
7985        final boolean shouldHaveCode =
7986                (pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) != 0;
7987        if (shouldHaveCode && !apkHasCode(pkg.baseCodePath)) {
7988            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
7989                    "Package " + pkg.baseCodePath + " code is missing");
7990        }
7991
7992        if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
7993            for (int i = 0; i < pkg.splitCodePaths.length; i++) {
7994                final boolean splitShouldHaveCode =
7995                        (pkg.splitFlags[i] & ApplicationInfo.FLAG_HAS_CODE) != 0;
7996                if (splitShouldHaveCode && !apkHasCode(pkg.splitCodePaths[i])) {
7997                    throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
7998                            "Package " + pkg.splitCodePaths[i] + " code is missing");
7999                }
8000            }
8001        }
8002    }
8003
8004    private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg,
8005            final int policyFlags, final int scanFlags, long currentTime, UserHandle user)
8006            throws PackageManagerException {
8007        final File scanFile = new File(pkg.codePath);
8008        if (pkg.applicationInfo.getCodePath() == null ||
8009                pkg.applicationInfo.getResourcePath() == null) {
8010            // Bail out. The resource and code paths haven't been set.
8011            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
8012                    "Code and resource paths haven't been set correctly");
8013        }
8014
8015        // Apply policy
8016        if ((policyFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
8017            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
8018            if (pkg.applicationInfo.isDirectBootAware()) {
8019                // we're direct boot aware; set for all components
8020                for (PackageParser.Service s : pkg.services) {
8021                    s.info.encryptionAware = s.info.directBootAware = true;
8022                }
8023                for (PackageParser.Provider p : pkg.providers) {
8024                    p.info.encryptionAware = p.info.directBootAware = true;
8025                }
8026                for (PackageParser.Activity a : pkg.activities) {
8027                    a.info.encryptionAware = a.info.directBootAware = true;
8028                }
8029                for (PackageParser.Activity r : pkg.receivers) {
8030                    r.info.encryptionAware = r.info.directBootAware = true;
8031                }
8032            }
8033        } else {
8034            // Only allow system apps to be flagged as core apps.
8035            pkg.coreApp = false;
8036            // clear flags not applicable to regular apps
8037            pkg.applicationInfo.privateFlags &=
8038                    ~ApplicationInfo.PRIVATE_FLAG_DEFAULT_TO_DEVICE_PROTECTED_STORAGE;
8039            pkg.applicationInfo.privateFlags &=
8040                    ~ApplicationInfo.PRIVATE_FLAG_DIRECT_BOOT_AWARE;
8041        }
8042        pkg.mTrustedOverlay = (policyFlags&PackageParser.PARSE_TRUSTED_OVERLAY) != 0;
8043
8044        if ((policyFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) {
8045            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
8046        }
8047
8048        if ((policyFlags & PackageParser.PARSE_ENFORCE_CODE) != 0) {
8049            enforceCodePolicy(pkg);
8050        }
8051
8052        if (mCustomResolverComponentName != null &&
8053                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
8054            setUpCustomResolverActivity(pkg);
8055        }
8056
8057        if (pkg.packageName.equals("android")) {
8058            synchronized (mPackages) {
8059                if (mAndroidApplication != null) {
8060                    Slog.w(TAG, "*************************************************");
8061                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
8062                    Slog.w(TAG, " file=" + scanFile);
8063                    Slog.w(TAG, "*************************************************");
8064                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
8065                            "Core android package being redefined.  Skipping.");
8066                }
8067
8068                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
8069                    // Set up information for our fall-back user intent resolution activity.
8070                    mPlatformPackage = pkg;
8071                    pkg.mVersionCode = mSdkVersion;
8072                    mAndroidApplication = pkg.applicationInfo;
8073
8074                    if (!mResolverReplaced) {
8075                        mResolveActivity.applicationInfo = mAndroidApplication;
8076                        mResolveActivity.name = ResolverActivity.class.getName();
8077                        mResolveActivity.packageName = mAndroidApplication.packageName;
8078                        mResolveActivity.processName = "system:ui";
8079                        mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
8080                        mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
8081                        mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
8082                        mResolveActivity.theme = R.style.Theme_Material_Dialog_Alert;
8083                        mResolveActivity.exported = true;
8084                        mResolveActivity.enabled = true;
8085                        mResolveActivity.resizeMode = ActivityInfo.RESIZE_MODE_RESIZEABLE;
8086                        mResolveActivity.configChanges = ActivityInfo.CONFIG_SCREEN_SIZE
8087                                | ActivityInfo.CONFIG_SMALLEST_SCREEN_SIZE
8088                                | ActivityInfo.CONFIG_SCREEN_LAYOUT
8089                                | ActivityInfo.CONFIG_ORIENTATION
8090                                | ActivityInfo.CONFIG_KEYBOARD
8091                                | ActivityInfo.CONFIG_KEYBOARD_HIDDEN;
8092                        mResolveInfo.activityInfo = mResolveActivity;
8093                        mResolveInfo.priority = 0;
8094                        mResolveInfo.preferredOrder = 0;
8095                        mResolveInfo.match = 0;
8096                        mResolveComponentName = new ComponentName(
8097                                mAndroidApplication.packageName, mResolveActivity.name);
8098                    }
8099                }
8100            }
8101        }
8102
8103        if (DEBUG_PACKAGE_SCANNING) {
8104            if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
8105                Log.d(TAG, "Scanning package " + pkg.packageName);
8106        }
8107
8108        synchronized (mPackages) {
8109            if (mPackages.containsKey(pkg.packageName)
8110                    || mSharedLibraries.containsKey(pkg.packageName)) {
8111                throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
8112                        "Application package " + pkg.packageName
8113                                + " already installed.  Skipping duplicate.");
8114            }
8115
8116            // If we're only installing presumed-existing packages, require that the
8117            // scanned APK is both already known and at the path previously established
8118            // for it.  Previously unknown packages we pick up normally, but if we have an
8119            // a priori expectation about this package's install presence, enforce it.
8120            // With a singular exception for new system packages. When an OTA contains
8121            // a new system package, we allow the codepath to change from a system location
8122            // to the user-installed location. If we don't allow this change, any newer,
8123            // user-installed version of the application will be ignored.
8124            if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) {
8125                if (mExpectingBetter.containsKey(pkg.packageName)) {
8126                    logCriticalInfo(Log.WARN,
8127                            "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName);
8128                } else {
8129                    PackageSetting known = mSettings.peekPackageLPr(pkg.packageName);
8130                    if (known != null) {
8131                        if (DEBUG_PACKAGE_SCANNING) {
8132                            Log.d(TAG, "Examining " + pkg.codePath
8133                                    + " and requiring known paths " + known.codePathString
8134                                    + " & " + known.resourcePathString);
8135                        }
8136                        if (!pkg.applicationInfo.getCodePath().equals(known.codePathString)
8137                                || !pkg.applicationInfo.getResourcePath().equals(
8138                                known.resourcePathString)) {
8139                            throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED,
8140                                    "Application package " + pkg.packageName
8141                                            + " found at " + pkg.applicationInfo.getCodePath()
8142                                            + " but expected at " + known.codePathString
8143                                            + "; ignoring.");
8144                        }
8145                    }
8146                }
8147            }
8148        }
8149
8150        // Initialize package source and resource directories
8151        File destCodeFile = new File(pkg.applicationInfo.getCodePath());
8152        File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
8153
8154        SharedUserSetting suid = null;
8155        PackageSetting pkgSetting = null;
8156
8157        if (!isSystemApp(pkg)) {
8158            // Only system apps can use these features.
8159            pkg.mOriginalPackages = null;
8160            pkg.mRealPackage = null;
8161            pkg.mAdoptPermissions = null;
8162        }
8163
8164        // Getting the package setting may have a side-effect, so if we
8165        // are only checking if scan would succeed, stash a copy of the
8166        // old setting to restore at the end.
8167        PackageSetting nonMutatedPs = null;
8168
8169        // writer
8170        synchronized (mPackages) {
8171            if (pkg.mSharedUserId != null) {
8172                suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true);
8173                if (suid == null) {
8174                    throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
8175                            "Creating application package " + pkg.packageName
8176                            + " for shared user failed");
8177                }
8178                if (DEBUG_PACKAGE_SCANNING) {
8179                    if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
8180                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId
8181                                + "): packages=" + suid.packages);
8182                }
8183            }
8184
8185            // Check if we are renaming from an original package name.
8186            PackageSetting origPackage = null;
8187            String realName = null;
8188            if (pkg.mOriginalPackages != null) {
8189                // This package may need to be renamed to a previously
8190                // installed name.  Let's check on that...
8191                final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage);
8192                if (pkg.mOriginalPackages.contains(renamed)) {
8193                    // This package had originally been installed as the
8194                    // original name, and we have already taken care of
8195                    // transitioning to the new one.  Just update the new
8196                    // one to continue using the old name.
8197                    realName = pkg.mRealPackage;
8198                    if (!pkg.packageName.equals(renamed)) {
8199                        // Callers into this function may have already taken
8200                        // care of renaming the package; only do it here if
8201                        // it is not already done.
8202                        pkg.setPackageName(renamed);
8203                    }
8204
8205                } else {
8206                    for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
8207                        if ((origPackage = mSettings.peekPackageLPr(
8208                                pkg.mOriginalPackages.get(i))) != null) {
8209                            // We do have the package already installed under its
8210                            // original name...  should we use it?
8211                            if (!verifyPackageUpdateLPr(origPackage, pkg)) {
8212                                // New package is not compatible with original.
8213                                origPackage = null;
8214                                continue;
8215                            } else if (origPackage.sharedUser != null) {
8216                                // Make sure uid is compatible between packages.
8217                                if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
8218                                    Slog.w(TAG, "Unable to migrate data from " + origPackage.name
8219                                            + " to " + pkg.packageName + ": old uid "
8220                                            + origPackage.sharedUser.name
8221                                            + " differs from " + pkg.mSharedUserId);
8222                                    origPackage = null;
8223                                    continue;
8224                                }
8225                                // TODO: Add case when shared user id is added [b/28144775]
8226                            } else {
8227                                if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
8228                                        + pkg.packageName + " to old name " + origPackage.name);
8229                            }
8230                            break;
8231                        }
8232                    }
8233                }
8234            }
8235
8236            if (mTransferedPackages.contains(pkg.packageName)) {
8237                Slog.w(TAG, "Package " + pkg.packageName
8238                        + " was transferred to another, but its .apk remains");
8239            }
8240
8241            // See comments in nonMutatedPs declaration
8242            if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
8243                PackageSetting foundPs = mSettings.peekPackageLPr(pkg.packageName);
8244                if (foundPs != null) {
8245                    nonMutatedPs = new PackageSetting(foundPs);
8246                }
8247            }
8248
8249            // Just create the setting, don't add it yet. For already existing packages
8250            // the PkgSetting exists already and doesn't have to be created.
8251            pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile,
8252                    destResourceFile, pkg.applicationInfo.nativeLibraryRootDir,
8253                    pkg.applicationInfo.primaryCpuAbi,
8254                    pkg.applicationInfo.secondaryCpuAbi,
8255                    pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags,
8256                    user, false);
8257            if (pkgSetting == null) {
8258                throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
8259                        "Creating application package " + pkg.packageName + " failed");
8260            }
8261
8262            if (pkgSetting.origPackage != null) {
8263                // If we are first transitioning from an original package,
8264                // fix up the new package's name now.  We need to do this after
8265                // looking up the package under its new name, so getPackageLP
8266                // can take care of fiddling things correctly.
8267                pkg.setPackageName(origPackage.name);
8268
8269                // File a report about this.
8270                String msg = "New package " + pkgSetting.realName
8271                        + " renamed to replace old package " + pkgSetting.name;
8272                reportSettingsProblem(Log.WARN, msg);
8273
8274                // Make a note of it.
8275                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
8276                    mTransferedPackages.add(origPackage.name);
8277                }
8278
8279                // No longer need to retain this.
8280                pkgSetting.origPackage = null;
8281            }
8282
8283            if ((scanFlags & SCAN_CHECK_ONLY) == 0 && realName != null) {
8284                // Make a note of it.
8285                mTransferedPackages.add(pkg.packageName);
8286            }
8287
8288            if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) {
8289                pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
8290            }
8291
8292            if ((policyFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
8293                // Check all shared libraries and map to their actual file path.
8294                // We only do this here for apps not on a system dir, because those
8295                // are the only ones that can fail an install due to this.  We
8296                // will take care of the system apps by updating all of their
8297                // library paths after the scan is done.
8298                updateSharedLibrariesLPw(pkg, null);
8299            }
8300
8301            if (mFoundPolicyFile) {
8302                SELinuxMMAC.assignSeinfoValue(pkg);
8303            }
8304
8305            pkg.applicationInfo.uid = pkgSetting.appId;
8306            pkg.mExtras = pkgSetting;
8307            if (shouldCheckUpgradeKeySetLP(pkgSetting, scanFlags)) {
8308                if (checkUpgradeKeySetLP(pkgSetting, pkg)) {
8309                    // We just determined the app is signed correctly, so bring
8310                    // over the latest parsed certs.
8311                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
8312                } else {
8313                    if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
8314                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
8315                                "Package " + pkg.packageName + " upgrade keys do not match the "
8316                                + "previously installed version");
8317                    } else {
8318                        pkgSetting.signatures.mSignatures = pkg.mSignatures;
8319                        String msg = "System package " + pkg.packageName
8320                            + " signature changed; retaining data.";
8321                        reportSettingsProblem(Log.WARN, msg);
8322                    }
8323                }
8324            } else {
8325                try {
8326                    verifySignaturesLP(pkgSetting, pkg);
8327                    // We just determined the app is signed correctly, so bring
8328                    // over the latest parsed certs.
8329                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
8330                } catch (PackageManagerException e) {
8331                    if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
8332                        throw e;
8333                    }
8334                    // The signature has changed, but this package is in the system
8335                    // image...  let's recover!
8336                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
8337                    // However...  if this package is part of a shared user, but it
8338                    // doesn't match the signature of the shared user, let's fail.
8339                    // What this means is that you can't change the signatures
8340                    // associated with an overall shared user, which doesn't seem all
8341                    // that unreasonable.
8342                    if (pkgSetting.sharedUser != null) {
8343                        if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
8344                                              pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
8345                            throw new PackageManagerException(
8346                                    INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
8347                                            "Signature mismatch for shared user: "
8348                                            + pkgSetting.sharedUser);
8349                        }
8350                    }
8351                    // File a report about this.
8352                    String msg = "System package " + pkg.packageName
8353                        + " signature changed; retaining data.";
8354                    reportSettingsProblem(Log.WARN, msg);
8355                }
8356            }
8357            // Verify that this new package doesn't have any content providers
8358            // that conflict with existing packages.  Only do this if the
8359            // package isn't already installed, since we don't want to break
8360            // things that are installed.
8361            if ((scanFlags & SCAN_NEW_INSTALL) != 0) {
8362                final int N = pkg.providers.size();
8363                int i;
8364                for (i=0; i<N; i++) {
8365                    PackageParser.Provider p = pkg.providers.get(i);
8366                    if (p.info.authority != null) {
8367                        String names[] = p.info.authority.split(";");
8368                        for (int j = 0; j < names.length; j++) {
8369                            if (mProvidersByAuthority.containsKey(names[j])) {
8370                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
8371                                final String otherPackageName =
8372                                        ((other != null && other.getComponentName() != null) ?
8373                                                other.getComponentName().getPackageName() : "?");
8374                                throw new PackageManagerException(
8375                                        INSTALL_FAILED_CONFLICTING_PROVIDER,
8376                                                "Can't install because provider name " + names[j]
8377                                                + " (in package " + pkg.applicationInfo.packageName
8378                                                + ") is already used by " + otherPackageName);
8379                            }
8380                        }
8381                    }
8382                }
8383            }
8384
8385            if ((scanFlags & SCAN_CHECK_ONLY) == 0 && pkg.mAdoptPermissions != null) {
8386                // This package wants to adopt ownership of permissions from
8387                // another package.
8388                for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
8389                    final String origName = pkg.mAdoptPermissions.get(i);
8390                    final PackageSetting orig = mSettings.peekPackageLPr(origName);
8391                    if (orig != null) {
8392                        if (verifyPackageUpdateLPr(orig, pkg)) {
8393                            Slog.i(TAG, "Adopting permissions from " + origName + " to "
8394                                    + pkg.packageName);
8395                            mSettings.transferPermissionsLPw(origName, pkg.packageName);
8396                        }
8397                    }
8398                }
8399            }
8400        }
8401
8402        final String pkgName = pkg.packageName;
8403
8404        final long scanFileTime = scanFile.lastModified();
8405        final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0;
8406        pkg.applicationInfo.processName = fixProcessName(
8407                pkg.applicationInfo.packageName,
8408                pkg.applicationInfo.processName,
8409                pkg.applicationInfo.uid);
8410
8411        if (pkg != mPlatformPackage) {
8412            // Get all of our default paths setup
8413            pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM);
8414        }
8415
8416        final String path = scanFile.getPath();
8417        final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
8418
8419        if ((scanFlags & SCAN_NEW_INSTALL) == 0) {
8420            derivePackageAbi(pkg, scanFile, cpuAbiOverride, true /* extract libs */);
8421
8422            // Some system apps still use directory structure for native libraries
8423            // in which case we might end up not detecting abi solely based on apk
8424            // structure. Try to detect abi based on directory structure.
8425            if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() &&
8426                    pkg.applicationInfo.primaryCpuAbi == null) {
8427                setBundledAppAbisAndRoots(pkg, pkgSetting);
8428                setNativeLibraryPaths(pkg);
8429            }
8430
8431        } else {
8432            if ((scanFlags & SCAN_MOVE) != 0) {
8433                // We haven't run dex-opt for this move (since we've moved the compiled output too)
8434                // but we already have this packages package info in the PackageSetting. We just
8435                // use that and derive the native library path based on the new codepath.
8436                pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString;
8437                pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString;
8438            }
8439
8440            // Set native library paths again. For moves, the path will be updated based on the
8441            // ABIs we've determined above. For non-moves, the path will be updated based on the
8442            // ABIs we determined during compilation, but the path will depend on the final
8443            // package path (after the rename away from the stage path).
8444            setNativeLibraryPaths(pkg);
8445        }
8446
8447        // This is a special case for the "system" package, where the ABI is
8448        // dictated by the zygote configuration (and init.rc). We should keep track
8449        // of this ABI so that we can deal with "normal" applications that run under
8450        // the same UID correctly.
8451        if (mPlatformPackage == pkg) {
8452            pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
8453                    Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
8454        }
8455
8456        // If there's a mismatch between the abi-override in the package setting
8457        // and the abiOverride specified for the install. Warn about this because we
8458        // would've already compiled the app without taking the package setting into
8459        // account.
8460        if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) {
8461            if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) {
8462                Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride +
8463                        " for package " + pkg.packageName);
8464            }
8465        }
8466
8467        pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
8468        pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
8469        pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
8470
8471        // Copy the derived override back to the parsed package, so that we can
8472        // update the package settings accordingly.
8473        pkg.cpuAbiOverride = cpuAbiOverride;
8474
8475        if (DEBUG_ABI_SELECTION) {
8476            Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName
8477                    + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
8478                    + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
8479        }
8480
8481        // Push the derived path down into PackageSettings so we know what to
8482        // clean up at uninstall time.
8483        pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
8484
8485        if (DEBUG_ABI_SELECTION) {
8486            Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
8487                    " primary=" + pkg.applicationInfo.primaryCpuAbi +
8488                    " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
8489        }
8490
8491        if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
8492            // We don't do this here during boot because we can do it all
8493            // at once after scanning all existing packages.
8494            //
8495            // We also do this *before* we perform dexopt on this package, so that
8496            // we can avoid redundant dexopts, and also to make sure we've got the
8497            // code and package path correct.
8498            adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages,
8499                    pkg, true /* boot complete */);
8500        }
8501
8502        if (mFactoryTest && pkg.requestedPermissions.contains(
8503                android.Manifest.permission.FACTORY_TEST)) {
8504            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
8505        }
8506
8507        ArrayList<PackageParser.Package> clientLibPkgs = null;
8508
8509        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
8510            if (nonMutatedPs != null) {
8511                synchronized (mPackages) {
8512                    mSettings.mPackages.put(nonMutatedPs.name, nonMutatedPs);
8513                }
8514            }
8515            return pkg;
8516        }
8517
8518        // Only privileged apps and updated privileged apps can add child packages.
8519        if (pkg.childPackages != null && !pkg.childPackages.isEmpty()) {
8520            if ((policyFlags & PARSE_IS_PRIVILEGED) == 0) {
8521                throw new PackageManagerException("Only privileged apps and updated "
8522                        + "privileged apps can add child packages. Ignoring package "
8523                        + pkg.packageName);
8524            }
8525            final int childCount = pkg.childPackages.size();
8526            for (int i = 0; i < childCount; i++) {
8527                PackageParser.Package childPkg = pkg.childPackages.get(i);
8528                if (mSettings.hasOtherDisabledSystemPkgWithChildLPr(pkg.packageName,
8529                        childPkg.packageName)) {
8530                    throw new PackageManagerException("Cannot override a child package of "
8531                            + "another disabled system app. Ignoring package " + pkg.packageName);
8532                }
8533            }
8534        }
8535
8536        // writer
8537        synchronized (mPackages) {
8538            if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
8539                // Only system apps can add new shared libraries.
8540                if (pkg.libraryNames != null) {
8541                    for (int i=0; i<pkg.libraryNames.size(); i++) {
8542                        String name = pkg.libraryNames.get(i);
8543                        boolean allowed = false;
8544                        if (pkg.isUpdatedSystemApp()) {
8545                            // New library entries can only be added through the
8546                            // system image.  This is important to get rid of a lot
8547                            // of nasty edge cases: for example if we allowed a non-
8548                            // system update of the app to add a library, then uninstalling
8549                            // the update would make the library go away, and assumptions
8550                            // we made such as through app install filtering would now
8551                            // have allowed apps on the device which aren't compatible
8552                            // with it.  Better to just have the restriction here, be
8553                            // conservative, and create many fewer cases that can negatively
8554                            // impact the user experience.
8555                            final PackageSetting sysPs = mSettings
8556                                    .getDisabledSystemPkgLPr(pkg.packageName);
8557                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
8558                                for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) {
8559                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
8560                                        allowed = true;
8561                                        break;
8562                                    }
8563                                }
8564                            }
8565                        } else {
8566                            allowed = true;
8567                        }
8568                        if (allowed) {
8569                            if (!mSharedLibraries.containsKey(name)) {
8570                                mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName));
8571                            } else if (!name.equals(pkg.packageName)) {
8572                                Slog.w(TAG, "Package " + pkg.packageName + " library "
8573                                        + name + " already exists; skipping");
8574                            }
8575                        } else {
8576                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
8577                                    + name + " that is not declared on system image; skipping");
8578                        }
8579                    }
8580                    if ((scanFlags & SCAN_BOOTING) == 0) {
8581                        // If we are not booting, we need to update any applications
8582                        // that are clients of our shared library.  If we are booting,
8583                        // this will all be done once the scan is complete.
8584                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
8585                    }
8586                }
8587            }
8588        }
8589
8590        if ((scanFlags & SCAN_BOOTING) != 0) {
8591            // No apps can run during boot scan, so they don't need to be frozen
8592        } else if ((scanFlags & SCAN_DONT_KILL_APP) != 0) {
8593            // Caller asked to not kill app, so it's probably not frozen
8594        } else if ((scanFlags & SCAN_IGNORE_FROZEN) != 0) {
8595            // Caller asked us to ignore frozen check for some reason; they
8596            // probably didn't know the package name
8597        } else {
8598            // We're doing major surgery on this package, so it better be frozen
8599            // right now to keep it from launching
8600            checkPackageFrozen(pkgName);
8601        }
8602
8603        // Also need to kill any apps that are dependent on the library.
8604        if (clientLibPkgs != null) {
8605            for (int i=0; i<clientLibPkgs.size(); i++) {
8606                PackageParser.Package clientPkg = clientLibPkgs.get(i);
8607                killApplication(clientPkg.applicationInfo.packageName,
8608                        clientPkg.applicationInfo.uid, "update lib");
8609            }
8610        }
8611
8612        // Make sure we're not adding any bogus keyset info
8613        KeySetManagerService ksms = mSettings.mKeySetManagerService;
8614        ksms.assertScannedPackageValid(pkg);
8615
8616        // writer
8617        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
8618
8619        boolean createIdmapFailed = false;
8620        synchronized (mPackages) {
8621            // We don't expect installation to fail beyond this point
8622
8623            if (pkgSetting.pkg != null) {
8624                // Note that |user| might be null during the initial boot scan. If a codePath
8625                // for an app has changed during a boot scan, it's due to an app update that's
8626                // part of the system partition and marker changes must be applied to all users.
8627                maybeRenameForeignDexMarkers(pkgSetting.pkg, pkg,
8628                    (user != null) ? user : UserHandle.ALL);
8629            }
8630
8631            // Add the new setting to mSettings
8632            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
8633            // Add the new setting to mPackages
8634            mPackages.put(pkg.applicationInfo.packageName, pkg);
8635            // Make sure we don't accidentally delete its data.
8636            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
8637            while (iter.hasNext()) {
8638                PackageCleanItem item = iter.next();
8639                if (pkgName.equals(item.packageName)) {
8640                    iter.remove();
8641                }
8642            }
8643
8644            // Take care of first install / last update times.
8645            if (currentTime != 0) {
8646                if (pkgSetting.firstInstallTime == 0) {
8647                    pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
8648                } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) {
8649                    pkgSetting.lastUpdateTime = currentTime;
8650                }
8651            } else if (pkgSetting.firstInstallTime == 0) {
8652                // We need *something*.  Take time time stamp of the file.
8653                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
8654            } else if ((policyFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
8655                if (scanFileTime != pkgSetting.timeStamp) {
8656                    // A package on the system image has changed; consider this
8657                    // to be an update.
8658                    pkgSetting.lastUpdateTime = scanFileTime;
8659                }
8660            }
8661
8662            // Add the package's KeySets to the global KeySetManagerService
8663            ksms.addScannedPackageLPw(pkg);
8664
8665            int N = pkg.providers.size();
8666            StringBuilder r = null;
8667            int i;
8668            for (i=0; i<N; i++) {
8669                PackageParser.Provider p = pkg.providers.get(i);
8670                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
8671                        p.info.processName, pkg.applicationInfo.uid);
8672                mProviders.addProvider(p);
8673                p.syncable = p.info.isSyncable;
8674                if (p.info.authority != null) {
8675                    String names[] = p.info.authority.split(";");
8676                    p.info.authority = null;
8677                    for (int j = 0; j < names.length; j++) {
8678                        if (j == 1 && p.syncable) {
8679                            // We only want the first authority for a provider to possibly be
8680                            // syncable, so if we already added this provider using a different
8681                            // authority clear the syncable flag. We copy the provider before
8682                            // changing it because the mProviders object contains a reference
8683                            // to a provider that we don't want to change.
8684                            // Only do this for the second authority since the resulting provider
8685                            // object can be the same for all future authorities for this provider.
8686                            p = new PackageParser.Provider(p);
8687                            p.syncable = false;
8688                        }
8689                        if (!mProvidersByAuthority.containsKey(names[j])) {
8690                            mProvidersByAuthority.put(names[j], p);
8691                            if (p.info.authority == null) {
8692                                p.info.authority = names[j];
8693                            } else {
8694                                p.info.authority = p.info.authority + ";" + names[j];
8695                            }
8696                            if (DEBUG_PACKAGE_SCANNING) {
8697                                if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
8698                                    Log.d(TAG, "Registered content provider: " + names[j]
8699                                            + ", className = " + p.info.name + ", isSyncable = "
8700                                            + p.info.isSyncable);
8701                            }
8702                        } else {
8703                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
8704                            Slog.w(TAG, "Skipping provider name " + names[j] +
8705                                    " (in package " + pkg.applicationInfo.packageName +
8706                                    "): name already used by "
8707                                    + ((other != null && other.getComponentName() != null)
8708                                            ? other.getComponentName().getPackageName() : "?"));
8709                        }
8710                    }
8711                }
8712                if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8713                    if (r == null) {
8714                        r = new StringBuilder(256);
8715                    } else {
8716                        r.append(' ');
8717                    }
8718                    r.append(p.info.name);
8719                }
8720            }
8721            if (r != null) {
8722                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
8723            }
8724
8725            N = pkg.services.size();
8726            r = null;
8727            for (i=0; i<N; i++) {
8728                PackageParser.Service s = pkg.services.get(i);
8729                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
8730                        s.info.processName, pkg.applicationInfo.uid);
8731                mServices.addService(s);
8732                if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8733                    if (r == null) {
8734                        r = new StringBuilder(256);
8735                    } else {
8736                        r.append(' ');
8737                    }
8738                    r.append(s.info.name);
8739                }
8740            }
8741            if (r != null) {
8742                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
8743            }
8744
8745            N = pkg.receivers.size();
8746            r = null;
8747            for (i=0; i<N; i++) {
8748                PackageParser.Activity a = pkg.receivers.get(i);
8749                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
8750                        a.info.processName, pkg.applicationInfo.uid);
8751                mReceivers.addActivity(a, "receiver");
8752                if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8753                    if (r == null) {
8754                        r = new StringBuilder(256);
8755                    } else {
8756                        r.append(' ');
8757                    }
8758                    r.append(a.info.name);
8759                }
8760            }
8761            if (r != null) {
8762                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
8763            }
8764
8765            N = pkg.activities.size();
8766            r = null;
8767            for (i=0; i<N; i++) {
8768                PackageParser.Activity a = pkg.activities.get(i);
8769                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
8770                        a.info.processName, pkg.applicationInfo.uid);
8771                mActivities.addActivity(a, "activity");
8772                if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8773                    if (r == null) {
8774                        r = new StringBuilder(256);
8775                    } else {
8776                        r.append(' ');
8777                    }
8778                    r.append(a.info.name);
8779                }
8780            }
8781            if (r != null) {
8782                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
8783            }
8784
8785            N = pkg.permissionGroups.size();
8786            r = null;
8787            for (i=0; i<N; i++) {
8788                PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
8789                PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
8790                if (cur == null) {
8791                    mPermissionGroups.put(pg.info.name, pg);
8792                    if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8793                        if (r == null) {
8794                            r = new StringBuilder(256);
8795                        } else {
8796                            r.append(' ');
8797                        }
8798                        r.append(pg.info.name);
8799                    }
8800                } else {
8801                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
8802                            + pg.info.packageName + " ignored: original from "
8803                            + cur.info.packageName);
8804                    if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8805                        if (r == null) {
8806                            r = new StringBuilder(256);
8807                        } else {
8808                            r.append(' ');
8809                        }
8810                        r.append("DUP:");
8811                        r.append(pg.info.name);
8812                    }
8813                }
8814            }
8815            if (r != null) {
8816                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permission Groups: " + r);
8817            }
8818
8819            N = pkg.permissions.size();
8820            r = null;
8821            for (i=0; i<N; i++) {
8822                PackageParser.Permission p = pkg.permissions.get(i);
8823
8824                // Assume by default that we did not install this permission into the system.
8825                p.info.flags &= ~PermissionInfo.FLAG_INSTALLED;
8826
8827                // Now that permission groups have a special meaning, we ignore permission
8828                // groups for legacy apps to prevent unexpected behavior. In particular,
8829                // permissions for one app being granted to someone just becase they happen
8830                // to be in a group defined by another app (before this had no implications).
8831                if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) {
8832                    p.group = mPermissionGroups.get(p.info.group);
8833                    // Warn for a permission in an unknown group.
8834                    if (p.info.group != null && p.group == null) {
8835                        Slog.w(TAG, "Permission " + p.info.name + " from package "
8836                                + p.info.packageName + " in an unknown group " + p.info.group);
8837                    }
8838                }
8839
8840                ArrayMap<String, BasePermission> permissionMap =
8841                        p.tree ? mSettings.mPermissionTrees
8842                                : mSettings.mPermissions;
8843                BasePermission bp = permissionMap.get(p.info.name);
8844
8845                // Allow system apps to redefine non-system permissions
8846                if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) {
8847                    final boolean currentOwnerIsSystem = (bp.perm != null
8848                            && isSystemApp(bp.perm.owner));
8849                    if (isSystemApp(p.owner)) {
8850                        if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) {
8851                            // It's a built-in permission and no owner, take ownership now
8852                            bp.packageSetting = pkgSetting;
8853                            bp.perm = p;
8854                            bp.uid = pkg.applicationInfo.uid;
8855                            bp.sourcePackage = p.info.packageName;
8856                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
8857                        } else if (!currentOwnerIsSystem) {
8858                            String msg = "New decl " + p.owner + " of permission  "
8859                                    + p.info.name + " is system; overriding " + bp.sourcePackage;
8860                            reportSettingsProblem(Log.WARN, msg);
8861                            bp = null;
8862                        }
8863                    }
8864                }
8865
8866                if (bp == null) {
8867                    bp = new BasePermission(p.info.name, p.info.packageName,
8868                            BasePermission.TYPE_NORMAL);
8869                    permissionMap.put(p.info.name, bp);
8870                }
8871
8872                if (bp.perm == null) {
8873                    if (bp.sourcePackage == null
8874                            || bp.sourcePackage.equals(p.info.packageName)) {
8875                        BasePermission tree = findPermissionTreeLP(p.info.name);
8876                        if (tree == null
8877                                || tree.sourcePackage.equals(p.info.packageName)) {
8878                            bp.packageSetting = pkgSetting;
8879                            bp.perm = p;
8880                            bp.uid = pkg.applicationInfo.uid;
8881                            bp.sourcePackage = p.info.packageName;
8882                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
8883                            if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8884                                if (r == null) {
8885                                    r = new StringBuilder(256);
8886                                } else {
8887                                    r.append(' ');
8888                                }
8889                                r.append(p.info.name);
8890                            }
8891                        } else {
8892                            Slog.w(TAG, "Permission " + p.info.name + " from package "
8893                                    + p.info.packageName + " ignored: base tree "
8894                                    + tree.name + " is from package "
8895                                    + tree.sourcePackage);
8896                        }
8897                    } else {
8898                        Slog.w(TAG, "Permission " + p.info.name + " from package "
8899                                + p.info.packageName + " ignored: original from "
8900                                + bp.sourcePackage);
8901                    }
8902                } else if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8903                    if (r == null) {
8904                        r = new StringBuilder(256);
8905                    } else {
8906                        r.append(' ');
8907                    }
8908                    r.append("DUP:");
8909                    r.append(p.info.name);
8910                }
8911                if (bp.perm == p) {
8912                    bp.protectionLevel = p.info.protectionLevel;
8913                }
8914            }
8915
8916            if (r != null) {
8917                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permissions: " + r);
8918            }
8919
8920            N = pkg.instrumentation.size();
8921            r = null;
8922            for (i=0; i<N; i++) {
8923                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
8924                a.info.packageName = pkg.applicationInfo.packageName;
8925                a.info.sourceDir = pkg.applicationInfo.sourceDir;
8926                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
8927                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
8928                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
8929                a.info.dataDir = pkg.applicationInfo.dataDir;
8930                a.info.deviceProtectedDataDir = pkg.applicationInfo.deviceProtectedDataDir;
8931                a.info.credentialProtectedDataDir = pkg.applicationInfo.credentialProtectedDataDir;
8932
8933                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
8934                a.info.secondaryNativeLibraryDir = pkg.applicationInfo.secondaryNativeLibraryDir;
8935                mInstrumentation.put(a.getComponentName(), a);
8936                if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8937                    if (r == null) {
8938                        r = new StringBuilder(256);
8939                    } else {
8940                        r.append(' ');
8941                    }
8942                    r.append(a.info.name);
8943                }
8944            }
8945            if (r != null) {
8946                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
8947            }
8948
8949            if (pkg.protectedBroadcasts != null) {
8950                N = pkg.protectedBroadcasts.size();
8951                for (i=0; i<N; i++) {
8952                    mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
8953                }
8954            }
8955
8956            pkgSetting.setTimeStamp(scanFileTime);
8957
8958            // Create idmap files for pairs of (packages, overlay packages).
8959            // Note: "android", ie framework-res.apk, is handled by native layers.
8960            if (pkg.mOverlayTarget != null) {
8961                // This is an overlay package.
8962                if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) {
8963                    if (!mOverlays.containsKey(pkg.mOverlayTarget)) {
8964                        mOverlays.put(pkg.mOverlayTarget,
8965                                new ArrayMap<String, PackageParser.Package>());
8966                    }
8967                    ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget);
8968                    map.put(pkg.packageName, pkg);
8969                    PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget);
8970                    if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) {
8971                        createIdmapFailed = true;
8972                    }
8973                }
8974            } else if (mOverlays.containsKey(pkg.packageName) &&
8975                    !pkg.packageName.equals("android")) {
8976                // This is a regular package, with one or more known overlay packages.
8977                createIdmapsForPackageLI(pkg);
8978            }
8979        }
8980
8981        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8982
8983        if (createIdmapFailed) {
8984            throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
8985                    "scanPackageLI failed to createIdmap");
8986        }
8987        return pkg;
8988    }
8989
8990    private void maybeRenameForeignDexMarkers(PackageParser.Package existing,
8991            PackageParser.Package update, UserHandle user) {
8992        if (existing.applicationInfo == null || update.applicationInfo == null) {
8993            // This isn't due to an app installation.
8994            return;
8995        }
8996
8997        final File oldCodePath = new File(existing.applicationInfo.getCodePath());
8998        final File newCodePath = new File(update.applicationInfo.getCodePath());
8999
9000        // The codePath hasn't changed, so there's nothing for us to do.
9001        if (Objects.equals(oldCodePath, newCodePath)) {
9002            return;
9003        }
9004
9005        File canonicalNewCodePath;
9006        try {
9007            canonicalNewCodePath = new File(PackageManagerServiceUtils.realpath(newCodePath));
9008        } catch (IOException e) {
9009            Slog.w(TAG, "Failed to get canonical path.", e);
9010            return;
9011        }
9012
9013        // This is a bit of a hack. The oldCodePath doesn't exist at this point (because
9014        // we've already renamed / deleted it) so we cannot call realpath on it. Here we assume
9015        // that the last component of the path (i.e, the name) doesn't need canonicalization
9016        // (i.e, that it isn't ".", ".." or a symbolic link). This is a valid assumption for now
9017        // but may change in the future. Hopefully this function won't exist at that point.
9018        final File canonicalOldCodePath = new File(canonicalNewCodePath.getParentFile(),
9019                oldCodePath.getName());
9020
9021        // Calculate the prefixes of the markers. These are just the paths with "/" replaced
9022        // with "@".
9023        String oldMarkerPrefix = canonicalOldCodePath.getAbsolutePath().replace('/', '@');
9024        if (!oldMarkerPrefix.endsWith("@")) {
9025            oldMarkerPrefix += "@";
9026        }
9027        String newMarkerPrefix = canonicalNewCodePath.getAbsolutePath().replace('/', '@');
9028        if (!newMarkerPrefix.endsWith("@")) {
9029            newMarkerPrefix += "@";
9030        }
9031
9032        List<String> updatedPaths = update.getAllCodePathsExcludingResourceOnly();
9033        List<String> markerSuffixes = new ArrayList<String>(updatedPaths.size());
9034        for (String updatedPath : updatedPaths) {
9035            String updatedPathName = new File(updatedPath).getName();
9036            markerSuffixes.add(updatedPathName.replace('/', '@'));
9037        }
9038
9039        for (int userId : resolveUserIds(user.getIdentifier())) {
9040            File profileDir = Environment.getDataProfilesDeForeignDexDirectory(userId);
9041
9042            for (String markerSuffix : markerSuffixes) {
9043                File oldForeignUseMark = new File(profileDir, oldMarkerPrefix + markerSuffix);
9044                File newForeignUseMark = new File(profileDir, newMarkerPrefix + markerSuffix);
9045                if (oldForeignUseMark.exists()) {
9046                    try {
9047                        Os.rename(oldForeignUseMark.getAbsolutePath(),
9048                                newForeignUseMark.getAbsolutePath());
9049                    } catch (ErrnoException e) {
9050                        Slog.w(TAG, "Failed to rename foreign use marker", e);
9051                        oldForeignUseMark.delete();
9052                    }
9053                }
9054            }
9055        }
9056    }
9057
9058    /**
9059     * Derive the ABI of a non-system package located at {@code scanFile}. This information
9060     * is derived purely on the basis of the contents of {@code scanFile} and
9061     * {@code cpuAbiOverride}.
9062     *
9063     * If {@code extractLibs} is true, native libraries are extracted from the app if required.
9064     */
9065    private void derivePackageAbi(PackageParser.Package pkg, File scanFile,
9066                                 String cpuAbiOverride, boolean extractLibs)
9067            throws PackageManagerException {
9068        // TODO: We can probably be smarter about this stuff. For installed apps,
9069        // we can calculate this information at install time once and for all. For
9070        // system apps, we can probably assume that this information doesn't change
9071        // after the first boot scan. As things stand, we do lots of unnecessary work.
9072
9073        // Give ourselves some initial paths; we'll come back for another
9074        // pass once we've determined ABI below.
9075        setNativeLibraryPaths(pkg);
9076
9077        // We would never need to extract libs for forward-locked and external packages,
9078        // since the container service will do it for us. We shouldn't attempt to
9079        // extract libs from system app when it was not updated.
9080        if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() ||
9081                (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) {
9082            extractLibs = false;
9083        }
9084
9085        final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
9086        final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
9087
9088        NativeLibraryHelper.Handle handle = null;
9089        try {
9090            handle = NativeLibraryHelper.Handle.create(pkg);
9091            // TODO(multiArch): This can be null for apps that didn't go through the
9092            // usual installation process. We can calculate it again, like we
9093            // do during install time.
9094            //
9095            // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
9096            // unnecessary.
9097            final File nativeLibraryRoot = new File(nativeLibraryRootStr);
9098
9099            // Null out the abis so that they can be recalculated.
9100            pkg.applicationInfo.primaryCpuAbi = null;
9101            pkg.applicationInfo.secondaryCpuAbi = null;
9102            if (isMultiArch(pkg.applicationInfo)) {
9103                // Warn if we've set an abiOverride for multi-lib packages..
9104                // By definition, we need to copy both 32 and 64 bit libraries for
9105                // such packages.
9106                if (pkg.cpuAbiOverride != null
9107                        && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
9108                    Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
9109                }
9110
9111                int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
9112                int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
9113                if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
9114                    if (extractLibs) {
9115                        abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
9116                                nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
9117                                useIsaSpecificSubdirs);
9118                    } else {
9119                        abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
9120                    }
9121                }
9122
9123                maybeThrowExceptionForMultiArchCopy(
9124                        "Error unpackaging 32 bit native libs for multiarch app.", abi32);
9125
9126                if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
9127                    if (extractLibs) {
9128                        abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
9129                                nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
9130                                useIsaSpecificSubdirs);
9131                    } else {
9132                        abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
9133                    }
9134                }
9135
9136                maybeThrowExceptionForMultiArchCopy(
9137                        "Error unpackaging 64 bit native libs for multiarch app.", abi64);
9138
9139                if (abi64 >= 0) {
9140                    pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
9141                }
9142
9143                if (abi32 >= 0) {
9144                    final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
9145                    if (abi64 >= 0) {
9146                        if (pkg.use32bitAbi) {
9147                            pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi;
9148                            pkg.applicationInfo.primaryCpuAbi = abi;
9149                        } else {
9150                            pkg.applicationInfo.secondaryCpuAbi = abi;
9151                        }
9152                    } else {
9153                        pkg.applicationInfo.primaryCpuAbi = abi;
9154                    }
9155                }
9156
9157            } else {
9158                String[] abiList = (cpuAbiOverride != null) ?
9159                        new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
9160
9161                // Enable gross and lame hacks for apps that are built with old
9162                // SDK tools. We must scan their APKs for renderscript bitcode and
9163                // not launch them if it's present. Don't bother checking on devices
9164                // that don't have 64 bit support.
9165                boolean needsRenderScriptOverride = false;
9166                if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
9167                        NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
9168                    abiList = Build.SUPPORTED_32_BIT_ABIS;
9169                    needsRenderScriptOverride = true;
9170                }
9171
9172                final int copyRet;
9173                if (extractLibs) {
9174                    copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
9175                            nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
9176                } else {
9177                    copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
9178                }
9179
9180                if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
9181                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
9182                            "Error unpackaging native libs for app, errorCode=" + copyRet);
9183                }
9184
9185                if (copyRet >= 0) {
9186                    pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
9187                } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
9188                    pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
9189                } else if (needsRenderScriptOverride) {
9190                    pkg.applicationInfo.primaryCpuAbi = abiList[0];
9191                }
9192            }
9193        } catch (IOException ioe) {
9194            Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
9195        } finally {
9196            IoUtils.closeQuietly(handle);
9197        }
9198
9199        // Now that we've calculated the ABIs and determined if it's an internal app,
9200        // we will go ahead and populate the nativeLibraryPath.
9201        setNativeLibraryPaths(pkg);
9202    }
9203
9204    /**
9205     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
9206     * i.e, so that all packages can be run inside a single process if required.
9207     *
9208     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
9209     * this function will either try and make the ABI for all packages in {@code packagesForUser}
9210     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
9211     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
9212     * updating a package that belongs to a shared user.
9213     *
9214     * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
9215     * adds unnecessary complexity.
9216     */
9217    private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser,
9218            PackageParser.Package scannedPackage, boolean bootComplete) {
9219        String requiredInstructionSet = null;
9220        if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
9221            requiredInstructionSet = VMRuntime.getInstructionSet(
9222                     scannedPackage.applicationInfo.primaryCpuAbi);
9223        }
9224
9225        PackageSetting requirer = null;
9226        for (PackageSetting ps : packagesForUser) {
9227            // If packagesForUser contains scannedPackage, we skip it. This will happen
9228            // when scannedPackage is an update of an existing package. Without this check,
9229            // we will never be able to change the ABI of any package belonging to a shared
9230            // user, even if it's compatible with other packages.
9231            if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
9232                if (ps.primaryCpuAbiString == null) {
9233                    continue;
9234                }
9235
9236                final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
9237                if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
9238                    // We have a mismatch between instruction sets (say arm vs arm64) warn about
9239                    // this but there's not much we can do.
9240                    String errorMessage = "Instruction set mismatch, "
9241                            + ((requirer == null) ? "[caller]" : requirer)
9242                            + " requires " + requiredInstructionSet + " whereas " + ps
9243                            + " requires " + instructionSet;
9244                    Slog.w(TAG, errorMessage);
9245                }
9246
9247                if (requiredInstructionSet == null) {
9248                    requiredInstructionSet = instructionSet;
9249                    requirer = ps;
9250                }
9251            }
9252        }
9253
9254        if (requiredInstructionSet != null) {
9255            String adjustedAbi;
9256            if (requirer != null) {
9257                // requirer != null implies that either scannedPackage was null or that scannedPackage
9258                // did not require an ABI, in which case we have to adjust scannedPackage to match
9259                // the ABI of the set (which is the same as requirer's ABI)
9260                adjustedAbi = requirer.primaryCpuAbiString;
9261                if (scannedPackage != null) {
9262                    scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
9263                }
9264            } else {
9265                // requirer == null implies that we're updating all ABIs in the set to
9266                // match scannedPackage.
9267                adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
9268            }
9269
9270            for (PackageSetting ps : packagesForUser) {
9271                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
9272                    if (ps.primaryCpuAbiString != null) {
9273                        continue;
9274                    }
9275
9276                    ps.primaryCpuAbiString = adjustedAbi;
9277                    if (ps.pkg != null && ps.pkg.applicationInfo != null &&
9278                            !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) {
9279                        ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
9280                        Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi
9281                                + " (requirer="
9282                                + (requirer == null ? "null" : requirer.pkg.packageName)
9283                                + ", scannedPackage="
9284                                + (scannedPackage != null ? scannedPackage.packageName : "null")
9285                                + ")");
9286                        try {
9287                            mInstaller.rmdex(ps.codePathString,
9288                                    getDexCodeInstructionSet(getPreferredInstructionSet()));
9289                        } catch (InstallerException ignored) {
9290                        }
9291                    }
9292                }
9293            }
9294        }
9295    }
9296
9297    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
9298        synchronized (mPackages) {
9299            mResolverReplaced = true;
9300            // Set up information for custom user intent resolution activity.
9301            mResolveActivity.applicationInfo = pkg.applicationInfo;
9302            mResolveActivity.name = mCustomResolverComponentName.getClassName();
9303            mResolveActivity.packageName = pkg.applicationInfo.packageName;
9304            mResolveActivity.processName = pkg.applicationInfo.packageName;
9305            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
9306            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
9307                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
9308            mResolveActivity.theme = 0;
9309            mResolveActivity.exported = true;
9310            mResolveActivity.enabled = true;
9311            mResolveInfo.activityInfo = mResolveActivity;
9312            mResolveInfo.priority = 0;
9313            mResolveInfo.preferredOrder = 0;
9314            mResolveInfo.match = 0;
9315            mResolveComponentName = mCustomResolverComponentName;
9316            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
9317                    mResolveComponentName);
9318        }
9319    }
9320
9321    private void setUpEphemeralInstallerActivityLP(ComponentName installerComponent) {
9322        final PackageParser.Package pkg = mPackages.get(installerComponent.getPackageName());
9323
9324        // Set up information for ephemeral installer activity
9325        mEphemeralInstallerActivity.applicationInfo = pkg.applicationInfo;
9326        mEphemeralInstallerActivity.name = mEphemeralInstallerComponent.getClassName();
9327        mEphemeralInstallerActivity.packageName = pkg.applicationInfo.packageName;
9328        mEphemeralInstallerActivity.processName = pkg.applicationInfo.packageName;
9329        mEphemeralInstallerActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
9330        mEphemeralInstallerActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
9331                ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
9332        mEphemeralInstallerActivity.theme = 0;
9333        mEphemeralInstallerActivity.exported = true;
9334        mEphemeralInstallerActivity.enabled = true;
9335        mEphemeralInstallerInfo.activityInfo = mEphemeralInstallerActivity;
9336        mEphemeralInstallerInfo.priority = 0;
9337        mEphemeralInstallerInfo.preferredOrder = 0;
9338        mEphemeralInstallerInfo.match = 0;
9339
9340        if (DEBUG_EPHEMERAL) {
9341            Slog.d(TAG, "Set ephemeral installer activity: " + mEphemeralInstallerComponent);
9342        }
9343    }
9344
9345    private static String calculateBundledApkRoot(final String codePathString) {
9346        final File codePath = new File(codePathString);
9347        final File codeRoot;
9348        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
9349            codeRoot = Environment.getRootDirectory();
9350        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
9351            codeRoot = Environment.getOemDirectory();
9352        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
9353            codeRoot = Environment.getVendorDirectory();
9354        } else {
9355            // Unrecognized code path; take its top real segment as the apk root:
9356            // e.g. /something/app/blah.apk => /something
9357            try {
9358                File f = codePath.getCanonicalFile();
9359                File parent = f.getParentFile();    // non-null because codePath is a file
9360                File tmp;
9361                while ((tmp = parent.getParentFile()) != null) {
9362                    f = parent;
9363                    parent = tmp;
9364                }
9365                codeRoot = f;
9366                Slog.w(TAG, "Unrecognized code path "
9367                        + codePath + " - using " + codeRoot);
9368            } catch (IOException e) {
9369                // Can't canonicalize the code path -- shenanigans?
9370                Slog.w(TAG, "Can't canonicalize code path " + codePath);
9371                return Environment.getRootDirectory().getPath();
9372            }
9373        }
9374        return codeRoot.getPath();
9375    }
9376
9377    /**
9378     * Derive and set the location of native libraries for the given package,
9379     * which varies depending on where and how the package was installed.
9380     */
9381    private void setNativeLibraryPaths(PackageParser.Package pkg) {
9382        final ApplicationInfo info = pkg.applicationInfo;
9383        final String codePath = pkg.codePath;
9384        final File codeFile = new File(codePath);
9385        final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp();
9386        final boolean asecApp = info.isForwardLocked() || info.isExternalAsec();
9387
9388        info.nativeLibraryRootDir = null;
9389        info.nativeLibraryRootRequiresIsa = false;
9390        info.nativeLibraryDir = null;
9391        info.secondaryNativeLibraryDir = null;
9392
9393        if (isApkFile(codeFile)) {
9394            // Monolithic install
9395            if (bundledApp) {
9396                // If "/system/lib64/apkname" exists, assume that is the per-package
9397                // native library directory to use; otherwise use "/system/lib/apkname".
9398                final String apkRoot = calculateBundledApkRoot(info.sourceDir);
9399                final boolean is64Bit = VMRuntime.is64BitInstructionSet(
9400                        getPrimaryInstructionSet(info));
9401
9402                // This is a bundled system app so choose the path based on the ABI.
9403                // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
9404                // is just the default path.
9405                final String apkName = deriveCodePathName(codePath);
9406                final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
9407                info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
9408                        apkName).getAbsolutePath();
9409
9410                if (info.secondaryCpuAbi != null) {
9411                    final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
9412                    info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
9413                            secondaryLibDir, apkName).getAbsolutePath();
9414                }
9415            } else if (asecApp) {
9416                info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
9417                        .getAbsolutePath();
9418            } else {
9419                final String apkName = deriveCodePathName(codePath);
9420                info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName)
9421                        .getAbsolutePath();
9422            }
9423
9424            info.nativeLibraryRootRequiresIsa = false;
9425            info.nativeLibraryDir = info.nativeLibraryRootDir;
9426        } else {
9427            // Cluster install
9428            info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
9429            info.nativeLibraryRootRequiresIsa = true;
9430
9431            info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
9432                    getPrimaryInstructionSet(info)).getAbsolutePath();
9433
9434            if (info.secondaryCpuAbi != null) {
9435                info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
9436                        VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
9437            }
9438        }
9439    }
9440
9441    /**
9442     * Calculate the abis and roots for a bundled app. These can uniquely
9443     * be determined from the contents of the system partition, i.e whether
9444     * it contains 64 or 32 bit shared libraries etc. We do not validate any
9445     * of this information, and instead assume that the system was built
9446     * sensibly.
9447     */
9448    private void setBundledAppAbisAndRoots(PackageParser.Package pkg,
9449                                           PackageSetting pkgSetting) {
9450        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
9451
9452        // If "/system/lib64/apkname" exists, assume that is the per-package
9453        // native library directory to use; otherwise use "/system/lib/apkname".
9454        final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
9455        setBundledAppAbi(pkg, apkRoot, apkName);
9456        // pkgSetting might be null during rescan following uninstall of updates
9457        // to a bundled app, so accommodate that possibility.  The settings in
9458        // that case will be established later from the parsed package.
9459        //
9460        // If the settings aren't null, sync them up with what we've just derived.
9461        // note that apkRoot isn't stored in the package settings.
9462        if (pkgSetting != null) {
9463            pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
9464            pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
9465        }
9466    }
9467
9468    /**
9469     * Deduces the ABI of a bundled app and sets the relevant fields on the
9470     * parsed pkg object.
9471     *
9472     * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
9473     *        under which system libraries are installed.
9474     * @param apkName the name of the installed package.
9475     */
9476    private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
9477        final File codeFile = new File(pkg.codePath);
9478
9479        final boolean has64BitLibs;
9480        final boolean has32BitLibs;
9481        if (isApkFile(codeFile)) {
9482            // Monolithic install
9483            has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
9484            has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
9485        } else {
9486            // Cluster install
9487            final File rootDir = new File(codeFile, LIB_DIR_NAME);
9488            if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
9489                    && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
9490                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
9491                has64BitLibs = (new File(rootDir, isa)).exists();
9492            } else {
9493                has64BitLibs = false;
9494            }
9495            if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
9496                    && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
9497                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
9498                has32BitLibs = (new File(rootDir, isa)).exists();
9499            } else {
9500                has32BitLibs = false;
9501            }
9502        }
9503
9504        if (has64BitLibs && !has32BitLibs) {
9505            // The package has 64 bit libs, but not 32 bit libs. Its primary
9506            // ABI should be 64 bit. We can safely assume here that the bundled
9507            // native libraries correspond to the most preferred ABI in the list.
9508
9509            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
9510            pkg.applicationInfo.secondaryCpuAbi = null;
9511        } else if (has32BitLibs && !has64BitLibs) {
9512            // The package has 32 bit libs but not 64 bit libs. Its primary
9513            // ABI should be 32 bit.
9514
9515            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
9516            pkg.applicationInfo.secondaryCpuAbi = null;
9517        } else if (has32BitLibs && has64BitLibs) {
9518            // The application has both 64 and 32 bit bundled libraries. We check
9519            // here that the app declares multiArch support, and warn if it doesn't.
9520            //
9521            // We will be lenient here and record both ABIs. The primary will be the
9522            // ABI that's higher on the list, i.e, a device that's configured to prefer
9523            // 64 bit apps will see a 64 bit primary ABI,
9524
9525            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
9526                Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch.");
9527            }
9528
9529            if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
9530                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
9531                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
9532            } else {
9533                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
9534                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
9535            }
9536        } else {
9537            pkg.applicationInfo.primaryCpuAbi = null;
9538            pkg.applicationInfo.secondaryCpuAbi = null;
9539        }
9540    }
9541
9542    private void killApplication(String pkgName, int appId, String reason) {
9543        // Request the ActivityManager to kill the process(only for existing packages)
9544        // so that we do not end up in a confused state while the user is still using the older
9545        // version of the application while the new one gets installed.
9546        final long token = Binder.clearCallingIdentity();
9547        try {
9548            IActivityManager am = ActivityManagerNative.getDefault();
9549            if (am != null) {
9550                try {
9551                    am.killApplicationWithAppId(pkgName, appId, reason);
9552                } catch (RemoteException e) {
9553                }
9554            }
9555        } finally {
9556            Binder.restoreCallingIdentity(token);
9557        }
9558    }
9559
9560    private void removePackageLI(PackageParser.Package pkg, boolean chatty) {
9561        // Remove the parent package setting
9562        PackageSetting ps = (PackageSetting) pkg.mExtras;
9563        if (ps != null) {
9564            removePackageLI(ps, chatty);
9565        }
9566        // Remove the child package setting
9567        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9568        for (int i = 0; i < childCount; i++) {
9569            PackageParser.Package childPkg = pkg.childPackages.get(i);
9570            ps = (PackageSetting) childPkg.mExtras;
9571            if (ps != null) {
9572                removePackageLI(ps, chatty);
9573            }
9574        }
9575    }
9576
9577    void removePackageLI(PackageSetting ps, boolean chatty) {
9578        if (DEBUG_INSTALL) {
9579            if (chatty)
9580                Log.d(TAG, "Removing package " + ps.name);
9581        }
9582
9583        // writer
9584        synchronized (mPackages) {
9585            mPackages.remove(ps.name);
9586            final PackageParser.Package pkg = ps.pkg;
9587            if (pkg != null) {
9588                cleanPackageDataStructuresLILPw(pkg, chatty);
9589            }
9590        }
9591    }
9592
9593    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
9594        if (DEBUG_INSTALL) {
9595            if (chatty)
9596                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
9597        }
9598
9599        // writer
9600        synchronized (mPackages) {
9601            // Remove the parent package
9602            mPackages.remove(pkg.applicationInfo.packageName);
9603            cleanPackageDataStructuresLILPw(pkg, chatty);
9604
9605            // Remove the child packages
9606            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9607            for (int i = 0; i < childCount; i++) {
9608                PackageParser.Package childPkg = pkg.childPackages.get(i);
9609                mPackages.remove(childPkg.applicationInfo.packageName);
9610                cleanPackageDataStructuresLILPw(childPkg, chatty);
9611            }
9612        }
9613    }
9614
9615    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
9616        int N = pkg.providers.size();
9617        StringBuilder r = null;
9618        int i;
9619        for (i=0; i<N; i++) {
9620            PackageParser.Provider p = pkg.providers.get(i);
9621            mProviders.removeProvider(p);
9622            if (p.info.authority == null) {
9623
9624                /* There was another ContentProvider with this authority when
9625                 * this app was installed so this authority is null,
9626                 * Ignore it as we don't have to unregister the provider.
9627                 */
9628                continue;
9629            }
9630            String names[] = p.info.authority.split(";");
9631            for (int j = 0; j < names.length; j++) {
9632                if (mProvidersByAuthority.get(names[j]) == p) {
9633                    mProvidersByAuthority.remove(names[j]);
9634                    if (DEBUG_REMOVE) {
9635                        if (chatty)
9636                            Log.d(TAG, "Unregistered content provider: " + names[j]
9637                                    + ", className = " + p.info.name + ", isSyncable = "
9638                                    + p.info.isSyncable);
9639                    }
9640                }
9641            }
9642            if (DEBUG_REMOVE && chatty) {
9643                if (r == null) {
9644                    r = new StringBuilder(256);
9645                } else {
9646                    r.append(' ');
9647                }
9648                r.append(p.info.name);
9649            }
9650        }
9651        if (r != null) {
9652            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
9653        }
9654
9655        N = pkg.services.size();
9656        r = null;
9657        for (i=0; i<N; i++) {
9658            PackageParser.Service s = pkg.services.get(i);
9659            mServices.removeService(s);
9660            if (chatty) {
9661                if (r == null) {
9662                    r = new StringBuilder(256);
9663                } else {
9664                    r.append(' ');
9665                }
9666                r.append(s.info.name);
9667            }
9668        }
9669        if (r != null) {
9670            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
9671        }
9672
9673        N = pkg.receivers.size();
9674        r = null;
9675        for (i=0; i<N; i++) {
9676            PackageParser.Activity a = pkg.receivers.get(i);
9677            mReceivers.removeActivity(a, "receiver");
9678            if (DEBUG_REMOVE && chatty) {
9679                if (r == null) {
9680                    r = new StringBuilder(256);
9681                } else {
9682                    r.append(' ');
9683                }
9684                r.append(a.info.name);
9685            }
9686        }
9687        if (r != null) {
9688            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
9689        }
9690
9691        N = pkg.activities.size();
9692        r = null;
9693        for (i=0; i<N; i++) {
9694            PackageParser.Activity a = pkg.activities.get(i);
9695            mActivities.removeActivity(a, "activity");
9696            if (DEBUG_REMOVE && chatty) {
9697                if (r == null) {
9698                    r = new StringBuilder(256);
9699                } else {
9700                    r.append(' ');
9701                }
9702                r.append(a.info.name);
9703            }
9704        }
9705        if (r != null) {
9706            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
9707        }
9708
9709        N = pkg.permissions.size();
9710        r = null;
9711        for (i=0; i<N; i++) {
9712            PackageParser.Permission p = pkg.permissions.get(i);
9713            BasePermission bp = mSettings.mPermissions.get(p.info.name);
9714            if (bp == null) {
9715                bp = mSettings.mPermissionTrees.get(p.info.name);
9716            }
9717            if (bp != null && bp.perm == p) {
9718                bp.perm = null;
9719                if (DEBUG_REMOVE && chatty) {
9720                    if (r == null) {
9721                        r = new StringBuilder(256);
9722                    } else {
9723                        r.append(' ');
9724                    }
9725                    r.append(p.info.name);
9726                }
9727            }
9728            if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
9729                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(p.info.name);
9730                if (appOpPkgs != null) {
9731                    appOpPkgs.remove(pkg.packageName);
9732                }
9733            }
9734        }
9735        if (r != null) {
9736            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
9737        }
9738
9739        N = pkg.requestedPermissions.size();
9740        r = null;
9741        for (i=0; i<N; i++) {
9742            String perm = pkg.requestedPermissions.get(i);
9743            BasePermission bp = mSettings.mPermissions.get(perm);
9744            if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
9745                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(perm);
9746                if (appOpPkgs != null) {
9747                    appOpPkgs.remove(pkg.packageName);
9748                    if (appOpPkgs.isEmpty()) {
9749                        mAppOpPermissionPackages.remove(perm);
9750                    }
9751                }
9752            }
9753        }
9754        if (r != null) {
9755            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
9756        }
9757
9758        N = pkg.instrumentation.size();
9759        r = null;
9760        for (i=0; i<N; i++) {
9761            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
9762            mInstrumentation.remove(a.getComponentName());
9763            if (DEBUG_REMOVE && chatty) {
9764                if (r == null) {
9765                    r = new StringBuilder(256);
9766                } else {
9767                    r.append(' ');
9768                }
9769                r.append(a.info.name);
9770            }
9771        }
9772        if (r != null) {
9773            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
9774        }
9775
9776        r = null;
9777        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
9778            // Only system apps can hold shared libraries.
9779            if (pkg.libraryNames != null) {
9780                for (i=0; i<pkg.libraryNames.size(); i++) {
9781                    String name = pkg.libraryNames.get(i);
9782                    SharedLibraryEntry cur = mSharedLibraries.get(name);
9783                    if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) {
9784                        mSharedLibraries.remove(name);
9785                        if (DEBUG_REMOVE && chatty) {
9786                            if (r == null) {
9787                                r = new StringBuilder(256);
9788                            } else {
9789                                r.append(' ');
9790                            }
9791                            r.append(name);
9792                        }
9793                    }
9794                }
9795            }
9796        }
9797        if (r != null) {
9798            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
9799        }
9800    }
9801
9802    private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
9803        for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
9804            if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
9805                return true;
9806            }
9807        }
9808        return false;
9809    }
9810
9811    static final int UPDATE_PERMISSIONS_ALL = 1<<0;
9812    static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
9813    static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
9814
9815    private void updatePermissionsLPw(PackageParser.Package pkg, int flags) {
9816        // Update the parent permissions
9817        updatePermissionsLPw(pkg.packageName, pkg, flags);
9818        // Update the child permissions
9819        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9820        for (int i = 0; i < childCount; i++) {
9821            PackageParser.Package childPkg = pkg.childPackages.get(i);
9822            updatePermissionsLPw(childPkg.packageName, childPkg, flags);
9823        }
9824    }
9825
9826    private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo,
9827            int flags) {
9828        final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null;
9829        updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags);
9830    }
9831
9832    private void updatePermissionsLPw(String changingPkg,
9833            PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) {
9834        // Make sure there are no dangling permission trees.
9835        Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator();
9836        while (it.hasNext()) {
9837            final BasePermission bp = it.next();
9838            if (bp.packageSetting == null) {
9839                // We may not yet have parsed the package, so just see if
9840                // we still know about its settings.
9841                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
9842            }
9843            if (bp.packageSetting == null) {
9844                Slog.w(TAG, "Removing dangling permission tree: " + bp.name
9845                        + " from package " + bp.sourcePackage);
9846                it.remove();
9847            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
9848                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
9849                    Slog.i(TAG, "Removing old permission tree: " + bp.name
9850                            + " from package " + bp.sourcePackage);
9851                    flags |= UPDATE_PERMISSIONS_ALL;
9852                    it.remove();
9853                }
9854            }
9855        }
9856
9857        // Make sure all dynamic permissions have been assigned to a package,
9858        // and make sure there are no dangling permissions.
9859        it = mSettings.mPermissions.values().iterator();
9860        while (it.hasNext()) {
9861            final BasePermission bp = it.next();
9862            if (bp.type == BasePermission.TYPE_DYNAMIC) {
9863                if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
9864                        + bp.name + " pkg=" + bp.sourcePackage
9865                        + " info=" + bp.pendingInfo);
9866                if (bp.packageSetting == null && bp.pendingInfo != null) {
9867                    final BasePermission tree = findPermissionTreeLP(bp.name);
9868                    if (tree != null && tree.perm != null) {
9869                        bp.packageSetting = tree.packageSetting;
9870                        bp.perm = new PackageParser.Permission(tree.perm.owner,
9871                                new PermissionInfo(bp.pendingInfo));
9872                        bp.perm.info.packageName = tree.perm.info.packageName;
9873                        bp.perm.info.name = bp.name;
9874                        bp.uid = tree.uid;
9875                    }
9876                }
9877            }
9878            if (bp.packageSetting == null) {
9879                // We may not yet have parsed the package, so just see if
9880                // we still know about its settings.
9881                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
9882            }
9883            if (bp.packageSetting == null) {
9884                Slog.w(TAG, "Removing dangling permission: " + bp.name
9885                        + " from package " + bp.sourcePackage);
9886                it.remove();
9887            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
9888                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
9889                    Slog.i(TAG, "Removing old permission: " + bp.name
9890                            + " from package " + bp.sourcePackage);
9891                    flags |= UPDATE_PERMISSIONS_ALL;
9892                    it.remove();
9893                }
9894            }
9895        }
9896
9897        // Now update the permissions for all packages, in particular
9898        // replace the granted permissions of the system packages.
9899        if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
9900            for (PackageParser.Package pkg : mPackages.values()) {
9901                if (pkg != pkgInfo) {
9902                    // Only replace for packages on requested volume
9903                    final String volumeUuid = getVolumeUuidForPackage(pkg);
9904                    final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0)
9905                            && Objects.equals(replaceVolumeUuid, volumeUuid);
9906                    grantPermissionsLPw(pkg, replace, changingPkg);
9907                }
9908            }
9909        }
9910
9911        if (pkgInfo != null) {
9912            // Only replace for packages on requested volume
9913            final String volumeUuid = getVolumeUuidForPackage(pkgInfo);
9914            final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0)
9915                    && Objects.equals(replaceVolumeUuid, volumeUuid);
9916            grantPermissionsLPw(pkgInfo, replace, changingPkg);
9917        }
9918    }
9919
9920    private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace,
9921            String packageOfInterest) {
9922        // IMPORTANT: There are two types of permissions: install and runtime.
9923        // Install time permissions are granted when the app is installed to
9924        // all device users and users added in the future. Runtime permissions
9925        // are granted at runtime explicitly to specific users. Normal and signature
9926        // protected permissions are install time permissions. Dangerous permissions
9927        // are install permissions if the app's target SDK is Lollipop MR1 or older,
9928        // otherwise they are runtime permissions. This function does not manage
9929        // runtime permissions except for the case an app targeting Lollipop MR1
9930        // being upgraded to target a newer SDK, in which case dangerous permissions
9931        // are transformed from install time to runtime ones.
9932
9933        final PackageSetting ps = (PackageSetting) pkg.mExtras;
9934        if (ps == null) {
9935            return;
9936        }
9937
9938        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions");
9939
9940        PermissionsState permissionsState = ps.getPermissionsState();
9941        PermissionsState origPermissions = permissionsState;
9942
9943        final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
9944
9945        boolean runtimePermissionsRevoked = false;
9946        int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY;
9947
9948        boolean changedInstallPermission = false;
9949
9950        if (replace) {
9951            ps.installPermissionsFixed = false;
9952            if (!ps.isSharedUser()) {
9953                origPermissions = new PermissionsState(permissionsState);
9954                permissionsState.reset();
9955            } else {
9956                // We need to know only about runtime permission changes since the
9957                // calling code always writes the install permissions state but
9958                // the runtime ones are written only if changed. The only cases of
9959                // changed runtime permissions here are promotion of an install to
9960                // runtime and revocation of a runtime from a shared user.
9961                changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw(
9962                        ps.sharedUser, UserManagerService.getInstance().getUserIds());
9963                if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) {
9964                    runtimePermissionsRevoked = true;
9965                }
9966            }
9967        }
9968
9969        permissionsState.setGlobalGids(mGlobalGids);
9970
9971        final int N = pkg.requestedPermissions.size();
9972        for (int i=0; i<N; i++) {
9973            final String name = pkg.requestedPermissions.get(i);
9974            final BasePermission bp = mSettings.mPermissions.get(name);
9975
9976            if (DEBUG_INSTALL) {
9977                Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
9978            }
9979
9980            if (bp == null || bp.packageSetting == null) {
9981                if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
9982                    Slog.w(TAG, "Unknown permission " + name
9983                            + " in package " + pkg.packageName);
9984                }
9985                continue;
9986            }
9987
9988            final String perm = bp.name;
9989            boolean allowedSig = false;
9990            int grant = GRANT_DENIED;
9991
9992            // Keep track of app op permissions.
9993            if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
9994                ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name);
9995                if (pkgs == null) {
9996                    pkgs = new ArraySet<>();
9997                    mAppOpPermissionPackages.put(bp.name, pkgs);
9998                }
9999                pkgs.add(pkg.packageName);
10000            }
10001
10002            final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE;
10003            final boolean appSupportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion
10004                    >= Build.VERSION_CODES.M;
10005            switch (level) {
10006                case PermissionInfo.PROTECTION_NORMAL: {
10007                    // For all apps normal permissions are install time ones.
10008                    grant = GRANT_INSTALL;
10009                } break;
10010
10011                case PermissionInfo.PROTECTION_DANGEROUS: {
10012                    // If a permission review is required for legacy apps we represent
10013                    // their permissions as always granted runtime ones since we need
10014                    // to keep the review required permission flag per user while an
10015                    // install permission's state is shared across all users.
10016                    if (!appSupportsRuntimePermissions && !Build.PERMISSIONS_REVIEW_REQUIRED) {
10017                        // For legacy apps dangerous permissions are install time ones.
10018                        grant = GRANT_INSTALL;
10019                    } else if (origPermissions.hasInstallPermission(bp.name)) {
10020                        // For legacy apps that became modern, install becomes runtime.
10021                        grant = GRANT_UPGRADE;
10022                    } else if (mPromoteSystemApps
10023                            && isSystemApp(ps)
10024                            && mExistingSystemPackages.contains(ps.name)) {
10025                        // For legacy system apps, install becomes runtime.
10026                        // We cannot check hasInstallPermission() for system apps since those
10027                        // permissions were granted implicitly and not persisted pre-M.
10028                        grant = GRANT_UPGRADE;
10029                    } else {
10030                        // For modern apps keep runtime permissions unchanged.
10031                        grant = GRANT_RUNTIME;
10032                    }
10033                } break;
10034
10035                case PermissionInfo.PROTECTION_SIGNATURE: {
10036                    // For all apps signature permissions are install time ones.
10037                    allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions);
10038                    if (allowedSig) {
10039                        grant = GRANT_INSTALL;
10040                    }
10041                } break;
10042            }
10043
10044            if (DEBUG_INSTALL) {
10045                Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
10046            }
10047
10048            if (grant != GRANT_DENIED) {
10049                if (!isSystemApp(ps) && ps.installPermissionsFixed) {
10050                    // If this is an existing, non-system package, then
10051                    // we can't add any new permissions to it.
10052                    if (!allowedSig && !origPermissions.hasInstallPermission(perm)) {
10053                        // Except...  if this is a permission that was added
10054                        // to the platform (note: need to only do this when
10055                        // updating the platform).
10056                        if (!isNewPlatformPermissionForPackage(perm, pkg)) {
10057                            grant = GRANT_DENIED;
10058                        }
10059                    }
10060                }
10061
10062                switch (grant) {
10063                    case GRANT_INSTALL: {
10064                        // Revoke this as runtime permission to handle the case of
10065                        // a runtime permission being downgraded to an install one.
10066                        // Also in permission review mode we keep dangerous permissions
10067                        // for legacy apps
10068                        for (int userId : UserManagerService.getInstance().getUserIds()) {
10069                            if (origPermissions.getRuntimePermissionState(
10070                                    bp.name, userId) != null) {
10071                                // Revoke the runtime permission and clear the flags.
10072                                origPermissions.revokeRuntimePermission(bp, userId);
10073                                origPermissions.updatePermissionFlags(bp, userId,
10074                                      PackageManager.MASK_PERMISSION_FLAGS, 0);
10075                                // If we revoked a permission permission, we have to write.
10076                                changedRuntimePermissionUserIds = ArrayUtils.appendInt(
10077                                        changedRuntimePermissionUserIds, userId);
10078                            }
10079                        }
10080                        // Grant an install permission.
10081                        if (permissionsState.grantInstallPermission(bp) !=
10082                                PermissionsState.PERMISSION_OPERATION_FAILURE) {
10083                            changedInstallPermission = true;
10084                        }
10085                    } break;
10086
10087                    case GRANT_RUNTIME: {
10088                        // Grant previously granted runtime permissions.
10089                        for (int userId : UserManagerService.getInstance().getUserIds()) {
10090                            PermissionState permissionState = origPermissions
10091                                    .getRuntimePermissionState(bp.name, userId);
10092                            int flags = permissionState != null
10093                                    ? permissionState.getFlags() : 0;
10094                            if (origPermissions.hasRuntimePermission(bp.name, userId)) {
10095                                if (permissionsState.grantRuntimePermission(bp, userId) ==
10096                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
10097                                    // If we cannot put the permission as it was, we have to write.
10098                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
10099                                            changedRuntimePermissionUserIds, userId);
10100                                }
10101                                // If the app supports runtime permissions no need for a review.
10102                                if (Build.PERMISSIONS_REVIEW_REQUIRED
10103                                        && appSupportsRuntimePermissions
10104                                        && (flags & PackageManager
10105                                                .FLAG_PERMISSION_REVIEW_REQUIRED) != 0) {
10106                                    flags &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
10107                                    // Since we changed the flags, we have to write.
10108                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
10109                                            changedRuntimePermissionUserIds, userId);
10110                                }
10111                            } else if (Build.PERMISSIONS_REVIEW_REQUIRED
10112                                    && !appSupportsRuntimePermissions) {
10113                                // For legacy apps that need a permission review, every new
10114                                // runtime permission is granted but it is pending a review.
10115                                // We also need to review only platform defined runtime
10116                                // permissions as these are the only ones the platform knows
10117                                // how to disable the API to simulate revocation as legacy
10118                                // apps don't expect to run with revoked permissions.
10119                                if (PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage)) {
10120                                    if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
10121                                        flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
10122                                        // We changed the flags, hence have to write.
10123                                        changedRuntimePermissionUserIds = ArrayUtils.appendInt(
10124                                                changedRuntimePermissionUserIds, userId);
10125                                    }
10126                                }
10127                                if (permissionsState.grantRuntimePermission(bp, userId)
10128                                        != PermissionsState.PERMISSION_OPERATION_FAILURE) {
10129                                    // We changed the permission, hence have to write.
10130                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
10131                                            changedRuntimePermissionUserIds, userId);
10132                                }
10133                            }
10134                            // Propagate the permission flags.
10135                            permissionsState.updatePermissionFlags(bp, userId, flags, flags);
10136                        }
10137                    } break;
10138
10139                    case GRANT_UPGRADE: {
10140                        // Grant runtime permissions for a previously held install permission.
10141                        PermissionState permissionState = origPermissions
10142                                .getInstallPermissionState(bp.name);
10143                        final int flags = permissionState != null ? permissionState.getFlags() : 0;
10144
10145                        if (origPermissions.revokeInstallPermission(bp)
10146                                != PermissionsState.PERMISSION_OPERATION_FAILURE) {
10147                            // We will be transferring the permission flags, so clear them.
10148                            origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL,
10149                                    PackageManager.MASK_PERMISSION_FLAGS, 0);
10150                            changedInstallPermission = true;
10151                        }
10152
10153                        // If the permission is not to be promoted to runtime we ignore it and
10154                        // also its other flags as they are not applicable to install permissions.
10155                        if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) {
10156                            for (int userId : currentUserIds) {
10157                                if (permissionsState.grantRuntimePermission(bp, userId) !=
10158                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
10159                                    // Transfer the permission flags.
10160                                    permissionsState.updatePermissionFlags(bp, userId,
10161                                            flags, flags);
10162                                    // If we granted the permission, we have to write.
10163                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
10164                                            changedRuntimePermissionUserIds, userId);
10165                                }
10166                            }
10167                        }
10168                    } break;
10169
10170                    default: {
10171                        if (packageOfInterest == null
10172                                || packageOfInterest.equals(pkg.packageName)) {
10173                            Slog.w(TAG, "Not granting permission " + perm
10174                                    + " to package " + pkg.packageName
10175                                    + " because it was previously installed without");
10176                        }
10177                    } break;
10178                }
10179            } else {
10180                if (permissionsState.revokeInstallPermission(bp) !=
10181                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
10182                    // Also drop the permission flags.
10183                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
10184                            PackageManager.MASK_PERMISSION_FLAGS, 0);
10185                    changedInstallPermission = true;
10186                    Slog.i(TAG, "Un-granting permission " + perm
10187                            + " from package " + pkg.packageName
10188                            + " (protectionLevel=" + bp.protectionLevel
10189                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
10190                            + ")");
10191                } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) {
10192                    // Don't print warning for app op permissions, since it is fine for them
10193                    // not to be granted, there is a UI for the user to decide.
10194                    if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
10195                        Slog.w(TAG, "Not granting permission " + perm
10196                                + " to package " + pkg.packageName
10197                                + " (protectionLevel=" + bp.protectionLevel
10198                                + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
10199                                + ")");
10200                    }
10201                }
10202            }
10203        }
10204
10205        if ((changedInstallPermission || replace) && !ps.installPermissionsFixed &&
10206                !isSystemApp(ps) || isUpdatedSystemApp(ps)){
10207            // This is the first that we have heard about this package, so the
10208            // permissions we have now selected are fixed until explicitly
10209            // changed.
10210            ps.installPermissionsFixed = true;
10211        }
10212
10213        // Persist the runtime permissions state for users with changes. If permissions
10214        // were revoked because no app in the shared user declares them we have to
10215        // write synchronously to avoid losing runtime permissions state.
10216        for (int userId : changedRuntimePermissionUserIds) {
10217            mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked);
10218        }
10219
10220        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10221    }
10222
10223    private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) {
10224        boolean allowed = false;
10225        final int NP = PackageParser.NEW_PERMISSIONS.length;
10226        for (int ip=0; ip<NP; ip++) {
10227            final PackageParser.NewPermissionInfo npi
10228                    = PackageParser.NEW_PERMISSIONS[ip];
10229            if (npi.name.equals(perm)
10230                    && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
10231                allowed = true;
10232                Log.i(TAG, "Auto-granting " + perm + " to old pkg "
10233                        + pkg.packageName);
10234                break;
10235            }
10236        }
10237        return allowed;
10238    }
10239
10240    private boolean grantSignaturePermission(String perm, PackageParser.Package pkg,
10241            BasePermission bp, PermissionsState origPermissions) {
10242        boolean allowed;
10243        allowed = (compareSignatures(
10244                bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
10245                        == PackageManager.SIGNATURE_MATCH)
10246                || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
10247                        == PackageManager.SIGNATURE_MATCH);
10248        if (!allowed && (bp.protectionLevel
10249                & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0) {
10250            if (isSystemApp(pkg)) {
10251                // For updated system applications, a system permission
10252                // is granted only if it had been defined by the original application.
10253                if (pkg.isUpdatedSystemApp()) {
10254                    final PackageSetting sysPs = mSettings
10255                            .getDisabledSystemPkgLPr(pkg.packageName);
10256                    if (sysPs != null && sysPs.getPermissionsState().hasInstallPermission(perm)) {
10257                        // If the original was granted this permission, we take
10258                        // that grant decision as read and propagate it to the
10259                        // update.
10260                        if (sysPs.isPrivileged()) {
10261                            allowed = true;
10262                        }
10263                    } else {
10264                        // The system apk may have been updated with an older
10265                        // version of the one on the data partition, but which
10266                        // granted a new system permission that it didn't have
10267                        // before.  In this case we do want to allow the app to
10268                        // now get the new permission if the ancestral apk is
10269                        // privileged to get it.
10270                        if (sysPs != null && sysPs.pkg != null && sysPs.isPrivileged()) {
10271                            for (int j = 0; j < sysPs.pkg.requestedPermissions.size(); j++) {
10272                                if (perm.equals(sysPs.pkg.requestedPermissions.get(j))) {
10273                                    allowed = true;
10274                                    break;
10275                                }
10276                            }
10277                        }
10278                        // Also if a privileged parent package on the system image or any of
10279                        // its children requested a privileged permission, the updated child
10280                        // packages can also get the permission.
10281                        if (pkg.parentPackage != null) {
10282                            final PackageSetting disabledSysParentPs = mSettings
10283                                    .getDisabledSystemPkgLPr(pkg.parentPackage.packageName);
10284                            if (disabledSysParentPs != null && disabledSysParentPs.pkg != null
10285                                    && disabledSysParentPs.isPrivileged()) {
10286                                if (isPackageRequestingPermission(disabledSysParentPs.pkg, perm)) {
10287                                    allowed = true;
10288                                } else if (disabledSysParentPs.pkg.childPackages != null) {
10289                                    final int count = disabledSysParentPs.pkg.childPackages.size();
10290                                    for (int i = 0; i < count; i++) {
10291                                        PackageParser.Package disabledSysChildPkg =
10292                                                disabledSysParentPs.pkg.childPackages.get(i);
10293                                        if (isPackageRequestingPermission(disabledSysChildPkg,
10294                                                perm)) {
10295                                            allowed = true;
10296                                            break;
10297                                        }
10298                                    }
10299                                }
10300                            }
10301                        }
10302                    }
10303                } else {
10304                    allowed = isPrivilegedApp(pkg);
10305                }
10306            }
10307        }
10308        if (!allowed) {
10309            if (!allowed && (bp.protectionLevel
10310                    & PermissionInfo.PROTECTION_FLAG_PRE23) != 0
10311                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
10312                // If this was a previously normal/dangerous permission that got moved
10313                // to a system permission as part of the runtime permission redesign, then
10314                // we still want to blindly grant it to old apps.
10315                allowed = true;
10316            }
10317            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0
10318                    && pkg.packageName.equals(mRequiredInstallerPackage)) {
10319                // If this permission is to be granted to the system installer and
10320                // this app is an installer, then it gets the permission.
10321                allowed = true;
10322            }
10323            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0
10324                    && pkg.packageName.equals(mRequiredVerifierPackage)) {
10325                // If this permission is to be granted to the system verifier and
10326                // this app is a verifier, then it gets the permission.
10327                allowed = true;
10328            }
10329            if (!allowed && (bp.protectionLevel
10330                    & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0
10331                    && isSystemApp(pkg)) {
10332                // Any pre-installed system app is allowed to get this permission.
10333                allowed = true;
10334            }
10335            if (!allowed && (bp.protectionLevel
10336                    & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) {
10337                // For development permissions, a development permission
10338                // is granted only if it was already granted.
10339                allowed = origPermissions.hasInstallPermission(perm);
10340            }
10341            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_SETUP) != 0
10342                    && pkg.packageName.equals(mSetupWizardPackage)) {
10343                // If this permission is to be granted to the system setup wizard and
10344                // this app is a setup wizard, then it gets the permission.
10345                allowed = true;
10346            }
10347        }
10348        return allowed;
10349    }
10350
10351    private boolean isPackageRequestingPermission(PackageParser.Package pkg, String permission) {
10352        final int permCount = pkg.requestedPermissions.size();
10353        for (int j = 0; j < permCount; j++) {
10354            String requestedPermission = pkg.requestedPermissions.get(j);
10355            if (permission.equals(requestedPermission)) {
10356                return true;
10357            }
10358        }
10359        return false;
10360    }
10361
10362    final class ActivityIntentResolver
10363            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
10364        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
10365                boolean defaultOnly, int userId) {
10366            if (!sUserManager.exists(userId)) return null;
10367            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
10368            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
10369        }
10370
10371        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
10372                int userId) {
10373            if (!sUserManager.exists(userId)) return null;
10374            mFlags = flags;
10375            return super.queryIntent(intent, resolvedType,
10376                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
10377        }
10378
10379        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
10380                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
10381            if (!sUserManager.exists(userId)) return null;
10382            if (packageActivities == null) {
10383                return null;
10384            }
10385            mFlags = flags;
10386            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
10387            final int N = packageActivities.size();
10388            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
10389                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
10390
10391            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
10392            for (int i = 0; i < N; ++i) {
10393                intentFilters = packageActivities.get(i).intents;
10394                if (intentFilters != null && intentFilters.size() > 0) {
10395                    PackageParser.ActivityIntentInfo[] array =
10396                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
10397                    intentFilters.toArray(array);
10398                    listCut.add(array);
10399                }
10400            }
10401            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
10402        }
10403
10404        /**
10405         * Finds a privileged activity that matches the specified activity names.
10406         */
10407        private PackageParser.Activity findMatchingActivity(
10408                List<PackageParser.Activity> activityList, ActivityInfo activityInfo) {
10409            for (PackageParser.Activity sysActivity : activityList) {
10410                if (sysActivity.info.name.equals(activityInfo.name)) {
10411                    return sysActivity;
10412                }
10413                if (sysActivity.info.name.equals(activityInfo.targetActivity)) {
10414                    return sysActivity;
10415                }
10416                if (sysActivity.info.targetActivity != null) {
10417                    if (sysActivity.info.targetActivity.equals(activityInfo.name)) {
10418                        return sysActivity;
10419                    }
10420                    if (sysActivity.info.targetActivity.equals(activityInfo.targetActivity)) {
10421                        return sysActivity;
10422                    }
10423                }
10424            }
10425            return null;
10426        }
10427
10428        public class IterGenerator<E> {
10429            public Iterator<E> generate(ActivityIntentInfo info) {
10430                return null;
10431            }
10432        }
10433
10434        public class ActionIterGenerator extends IterGenerator<String> {
10435            @Override
10436            public Iterator<String> generate(ActivityIntentInfo info) {
10437                return info.actionsIterator();
10438            }
10439        }
10440
10441        public class CategoriesIterGenerator extends IterGenerator<String> {
10442            @Override
10443            public Iterator<String> generate(ActivityIntentInfo info) {
10444                return info.categoriesIterator();
10445            }
10446        }
10447
10448        public class SchemesIterGenerator extends IterGenerator<String> {
10449            @Override
10450            public Iterator<String> generate(ActivityIntentInfo info) {
10451                return info.schemesIterator();
10452            }
10453        }
10454
10455        public class AuthoritiesIterGenerator extends IterGenerator<IntentFilter.AuthorityEntry> {
10456            @Override
10457            public Iterator<IntentFilter.AuthorityEntry> generate(ActivityIntentInfo info) {
10458                return info.authoritiesIterator();
10459            }
10460        }
10461
10462        /**
10463         * <em>WARNING</em> for performance reasons, the passed in intentList WILL BE
10464         * MODIFIED. Do not pass in a list that should not be changed.
10465         */
10466        private <T> void getIntentListSubset(List<ActivityIntentInfo> intentList,
10467                IterGenerator<T> generator, Iterator<T> searchIterator) {
10468            // loop through the set of actions; every one must be found in the intent filter
10469            while (searchIterator.hasNext()) {
10470                // we must have at least one filter in the list to consider a match
10471                if (intentList.size() == 0) {
10472                    break;
10473                }
10474
10475                final T searchAction = searchIterator.next();
10476
10477                // loop through the set of intent filters
10478                final Iterator<ActivityIntentInfo> intentIter = intentList.iterator();
10479                while (intentIter.hasNext()) {
10480                    final ActivityIntentInfo intentInfo = intentIter.next();
10481                    boolean selectionFound = false;
10482
10483                    // loop through the intent filter's selection criteria; at least one
10484                    // of them must match the searched criteria
10485                    final Iterator<T> intentSelectionIter = generator.generate(intentInfo);
10486                    while (intentSelectionIter != null && intentSelectionIter.hasNext()) {
10487                        final T intentSelection = intentSelectionIter.next();
10488                        if (intentSelection != null && intentSelection.equals(searchAction)) {
10489                            selectionFound = true;
10490                            break;
10491                        }
10492                    }
10493
10494                    // the selection criteria wasn't found in this filter's set; this filter
10495                    // is not a potential match
10496                    if (!selectionFound) {
10497                        intentIter.remove();
10498                    }
10499                }
10500            }
10501        }
10502
10503        private boolean isProtectedAction(ActivityIntentInfo filter) {
10504            final Iterator<String> actionsIter = filter.actionsIterator();
10505            while (actionsIter != null && actionsIter.hasNext()) {
10506                final String filterAction = actionsIter.next();
10507                if (PROTECTED_ACTIONS.contains(filterAction)) {
10508                    return true;
10509                }
10510            }
10511            return false;
10512        }
10513
10514        /**
10515         * Adjusts the priority of the given intent filter according to policy.
10516         * <p>
10517         * <ul>
10518         * <li>The priority for non privileged applications is capped to '0'</li>
10519         * <li>The priority for protected actions on privileged applications is capped to '0'</li>
10520         * <li>The priority for unbundled updates to privileged applications is capped to the
10521         *      priority defined on the system partition</li>
10522         * </ul>
10523         * <p>
10524         * <em>NOTE:</em> There is one exception. For security reasons, the setup wizard is
10525         * allowed to obtain any priority on any action.
10526         */
10527        private void adjustPriority(
10528                List<PackageParser.Activity> systemActivities, ActivityIntentInfo intent) {
10529            // nothing to do; priority is fine as-is
10530            if (intent.getPriority() <= 0) {
10531                return;
10532            }
10533
10534            final ActivityInfo activityInfo = intent.activity.info;
10535            final ApplicationInfo applicationInfo = activityInfo.applicationInfo;
10536
10537            final boolean privilegedApp =
10538                    ((applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0);
10539            if (!privilegedApp) {
10540                // non-privileged applications can never define a priority >0
10541                Slog.w(TAG, "Non-privileged app; cap priority to 0;"
10542                        + " package: " + applicationInfo.packageName
10543                        + " activity: " + intent.activity.className
10544                        + " origPrio: " + intent.getPriority());
10545                intent.setPriority(0);
10546                return;
10547            }
10548
10549            if (systemActivities == null) {
10550                // the system package is not disabled; we're parsing the system partition
10551                if (isProtectedAction(intent)) {
10552                    if (mDeferProtectedFilters) {
10553                        // We can't deal with these just yet. No component should ever obtain a
10554                        // >0 priority for a protected actions, with ONE exception -- the setup
10555                        // wizard. The setup wizard, however, cannot be known until we're able to
10556                        // query it for the category CATEGORY_SETUP_WIZARD. Which we can't do
10557                        // until all intent filters have been processed. Chicken, meet egg.
10558                        // Let the filter temporarily have a high priority and rectify the
10559                        // priorities after all system packages have been scanned.
10560                        mProtectedFilters.add(intent);
10561                        if (DEBUG_FILTERS) {
10562                            Slog.i(TAG, "Protected action; save for later;"
10563                                    + " package: " + applicationInfo.packageName
10564                                    + " activity: " + intent.activity.className
10565                                    + " origPrio: " + intent.getPriority());
10566                        }
10567                        return;
10568                    } else {
10569                        if (DEBUG_FILTERS && mSetupWizardPackage == null) {
10570                            Slog.i(TAG, "No setup wizard;"
10571                                + " All protected intents capped to priority 0");
10572                        }
10573                        if (intent.activity.info.packageName.equals(mSetupWizardPackage)) {
10574                            if (DEBUG_FILTERS) {
10575                                Slog.i(TAG, "Found setup wizard;"
10576                                    + " allow priority " + intent.getPriority() + ";"
10577                                    + " package: " + intent.activity.info.packageName
10578                                    + " activity: " + intent.activity.className
10579                                    + " priority: " + intent.getPriority());
10580                            }
10581                            // setup wizard gets whatever it wants
10582                            return;
10583                        }
10584                        Slog.w(TAG, "Protected action; cap priority to 0;"
10585                                + " package: " + intent.activity.info.packageName
10586                                + " activity: " + intent.activity.className
10587                                + " origPrio: " + intent.getPriority());
10588                        intent.setPriority(0);
10589                        return;
10590                    }
10591                }
10592                // privileged apps on the system image get whatever priority they request
10593                return;
10594            }
10595
10596            // privileged app unbundled update ... try to find the same activity
10597            final PackageParser.Activity foundActivity =
10598                    findMatchingActivity(systemActivities, activityInfo);
10599            if (foundActivity == null) {
10600                // this is a new activity; it cannot obtain >0 priority
10601                if (DEBUG_FILTERS) {
10602                    Slog.i(TAG, "New activity; cap priority to 0;"
10603                            + " package: " + applicationInfo.packageName
10604                            + " activity: " + intent.activity.className
10605                            + " origPrio: " + intent.getPriority());
10606                }
10607                intent.setPriority(0);
10608                return;
10609            }
10610
10611            // found activity, now check for filter equivalence
10612
10613            // a shallow copy is enough; we modify the list, not its contents
10614            final List<ActivityIntentInfo> intentListCopy =
10615                    new ArrayList<>(foundActivity.intents);
10616            final List<ActivityIntentInfo> foundFilters = findFilters(intent);
10617
10618            // find matching action subsets
10619            final Iterator<String> actionsIterator = intent.actionsIterator();
10620            if (actionsIterator != null) {
10621                getIntentListSubset(
10622                        intentListCopy, new ActionIterGenerator(), actionsIterator);
10623                if (intentListCopy.size() == 0) {
10624                    // no more intents to match; we're not equivalent
10625                    if (DEBUG_FILTERS) {
10626                        Slog.i(TAG, "Mismatched action; cap priority to 0;"
10627                                + " package: " + applicationInfo.packageName
10628                                + " activity: " + intent.activity.className
10629                                + " origPrio: " + intent.getPriority());
10630                    }
10631                    intent.setPriority(0);
10632                    return;
10633                }
10634            }
10635
10636            // find matching category subsets
10637            final Iterator<String> categoriesIterator = intent.categoriesIterator();
10638            if (categoriesIterator != null) {
10639                getIntentListSubset(intentListCopy, new CategoriesIterGenerator(),
10640                        categoriesIterator);
10641                if (intentListCopy.size() == 0) {
10642                    // no more intents to match; we're not equivalent
10643                    if (DEBUG_FILTERS) {
10644                        Slog.i(TAG, "Mismatched category; cap priority to 0;"
10645                                + " package: " + applicationInfo.packageName
10646                                + " activity: " + intent.activity.className
10647                                + " origPrio: " + intent.getPriority());
10648                    }
10649                    intent.setPriority(0);
10650                    return;
10651                }
10652            }
10653
10654            // find matching schemes subsets
10655            final Iterator<String> schemesIterator = intent.schemesIterator();
10656            if (schemesIterator != null) {
10657                getIntentListSubset(intentListCopy, new SchemesIterGenerator(),
10658                        schemesIterator);
10659                if (intentListCopy.size() == 0) {
10660                    // no more intents to match; we're not equivalent
10661                    if (DEBUG_FILTERS) {
10662                        Slog.i(TAG, "Mismatched scheme; cap priority to 0;"
10663                                + " package: " + applicationInfo.packageName
10664                                + " activity: " + intent.activity.className
10665                                + " origPrio: " + intent.getPriority());
10666                    }
10667                    intent.setPriority(0);
10668                    return;
10669                }
10670            }
10671
10672            // find matching authorities subsets
10673            final Iterator<IntentFilter.AuthorityEntry>
10674                    authoritiesIterator = intent.authoritiesIterator();
10675            if (authoritiesIterator != null) {
10676                getIntentListSubset(intentListCopy,
10677                        new AuthoritiesIterGenerator(),
10678                        authoritiesIterator);
10679                if (intentListCopy.size() == 0) {
10680                    // no more intents to match; we're not equivalent
10681                    if (DEBUG_FILTERS) {
10682                        Slog.i(TAG, "Mismatched authority; cap priority to 0;"
10683                                + " package: " + applicationInfo.packageName
10684                                + " activity: " + intent.activity.className
10685                                + " origPrio: " + intent.getPriority());
10686                    }
10687                    intent.setPriority(0);
10688                    return;
10689                }
10690            }
10691
10692            // we found matching filter(s); app gets the max priority of all intents
10693            int cappedPriority = 0;
10694            for (int i = intentListCopy.size() - 1; i >= 0; --i) {
10695                cappedPriority = Math.max(cappedPriority, intentListCopy.get(i).getPriority());
10696            }
10697            if (intent.getPriority() > cappedPriority) {
10698                if (DEBUG_FILTERS) {
10699                    Slog.i(TAG, "Found matching filter(s);"
10700                            + " cap priority to " + cappedPriority + ";"
10701                            + " package: " + applicationInfo.packageName
10702                            + " activity: " + intent.activity.className
10703                            + " origPrio: " + intent.getPriority());
10704                }
10705                intent.setPriority(cappedPriority);
10706                return;
10707            }
10708            // all this for nothing; the requested priority was <= what was on the system
10709        }
10710
10711        public final void addActivity(PackageParser.Activity a, String type) {
10712            mActivities.put(a.getComponentName(), a);
10713            if (DEBUG_SHOW_INFO)
10714                Log.v(
10715                TAG, "  " + type + " " +
10716                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
10717            if (DEBUG_SHOW_INFO)
10718                Log.v(TAG, "    Class=" + a.info.name);
10719            final int NI = a.intents.size();
10720            for (int j=0; j<NI; j++) {
10721                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
10722                if ("activity".equals(type)) {
10723                    final PackageSetting ps =
10724                            mSettings.getDisabledSystemPkgLPr(intent.activity.info.packageName);
10725                    final List<PackageParser.Activity> systemActivities =
10726                            ps != null && ps.pkg != null ? ps.pkg.activities : null;
10727                    adjustPriority(systemActivities, intent);
10728                }
10729                if (DEBUG_SHOW_INFO) {
10730                    Log.v(TAG, "    IntentFilter:");
10731                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
10732                }
10733                if (!intent.debugCheck()) {
10734                    Log.w(TAG, "==> For Activity " + a.info.name);
10735                }
10736                addFilter(intent);
10737            }
10738        }
10739
10740        public final void removeActivity(PackageParser.Activity a, String type) {
10741            mActivities.remove(a.getComponentName());
10742            if (DEBUG_SHOW_INFO) {
10743                Log.v(TAG, "  " + type + " "
10744                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
10745                                : a.info.name) + ":");
10746                Log.v(TAG, "    Class=" + a.info.name);
10747            }
10748            final int NI = a.intents.size();
10749            for (int j=0; j<NI; j++) {
10750                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
10751                if (DEBUG_SHOW_INFO) {
10752                    Log.v(TAG, "    IntentFilter:");
10753                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
10754                }
10755                removeFilter(intent);
10756            }
10757        }
10758
10759        @Override
10760        protected boolean allowFilterResult(
10761                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
10762            ActivityInfo filterAi = filter.activity.info;
10763            for (int i=dest.size()-1; i>=0; i--) {
10764                ActivityInfo destAi = dest.get(i).activityInfo;
10765                if (destAi.name == filterAi.name
10766                        && destAi.packageName == filterAi.packageName) {
10767                    return false;
10768                }
10769            }
10770            return true;
10771        }
10772
10773        @Override
10774        protected ActivityIntentInfo[] newArray(int size) {
10775            return new ActivityIntentInfo[size];
10776        }
10777
10778        @Override
10779        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
10780            if (!sUserManager.exists(userId)) return true;
10781            PackageParser.Package p = filter.activity.owner;
10782            if (p != null) {
10783                PackageSetting ps = (PackageSetting)p.mExtras;
10784                if (ps != null) {
10785                    // System apps are never considered stopped for purposes of
10786                    // filtering, because there may be no way for the user to
10787                    // actually re-launch them.
10788                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
10789                            && ps.getStopped(userId);
10790                }
10791            }
10792            return false;
10793        }
10794
10795        @Override
10796        protected boolean isPackageForFilter(String packageName,
10797                PackageParser.ActivityIntentInfo info) {
10798            return packageName.equals(info.activity.owner.packageName);
10799        }
10800
10801        @Override
10802        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
10803                int match, int userId) {
10804            if (!sUserManager.exists(userId)) return null;
10805            if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) {
10806                return null;
10807            }
10808            final PackageParser.Activity activity = info.activity;
10809            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
10810            if (ps == null) {
10811                return null;
10812            }
10813            ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags,
10814                    ps.readUserState(userId), userId);
10815            if (ai == null) {
10816                return null;
10817            }
10818            final ResolveInfo res = new ResolveInfo();
10819            res.activityInfo = ai;
10820            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
10821                res.filter = info;
10822            }
10823            if (info != null) {
10824                res.handleAllWebDataURI = info.handleAllWebDataURI();
10825            }
10826            res.priority = info.getPriority();
10827            res.preferredOrder = activity.owner.mPreferredOrder;
10828            //System.out.println("Result: " + res.activityInfo.className +
10829            //                   " = " + res.priority);
10830            res.match = match;
10831            res.isDefault = info.hasDefault;
10832            res.labelRes = info.labelRes;
10833            res.nonLocalizedLabel = info.nonLocalizedLabel;
10834            if (userNeedsBadging(userId)) {
10835                res.noResourceId = true;
10836            } else {
10837                res.icon = info.icon;
10838            }
10839            res.iconResourceId = info.icon;
10840            res.system = res.activityInfo.applicationInfo.isSystemApp();
10841            return res;
10842        }
10843
10844        @Override
10845        protected void sortResults(List<ResolveInfo> results) {
10846            Collections.sort(results, mResolvePrioritySorter);
10847        }
10848
10849        @Override
10850        protected void dumpFilter(PrintWriter out, String prefix,
10851                PackageParser.ActivityIntentInfo filter) {
10852            out.print(prefix); out.print(
10853                    Integer.toHexString(System.identityHashCode(filter.activity)));
10854                    out.print(' ');
10855                    filter.activity.printComponentShortName(out);
10856                    out.print(" filter ");
10857                    out.println(Integer.toHexString(System.identityHashCode(filter)));
10858        }
10859
10860        @Override
10861        protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) {
10862            return filter.activity;
10863        }
10864
10865        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
10866            PackageParser.Activity activity = (PackageParser.Activity)label;
10867            out.print(prefix); out.print(
10868                    Integer.toHexString(System.identityHashCode(activity)));
10869                    out.print(' ');
10870                    activity.printComponentShortName(out);
10871            if (count > 1) {
10872                out.print(" ("); out.print(count); out.print(" filters)");
10873            }
10874            out.println();
10875        }
10876
10877        // Keys are String (activity class name), values are Activity.
10878        private final ArrayMap<ComponentName, PackageParser.Activity> mActivities
10879                = new ArrayMap<ComponentName, PackageParser.Activity>();
10880        private int mFlags;
10881    }
10882
10883    private final class ServiceIntentResolver
10884            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
10885        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
10886                boolean defaultOnly, int userId) {
10887            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
10888            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
10889        }
10890
10891        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
10892                int userId) {
10893            if (!sUserManager.exists(userId)) return null;
10894            mFlags = flags;
10895            return super.queryIntent(intent, resolvedType,
10896                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
10897        }
10898
10899        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
10900                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
10901            if (!sUserManager.exists(userId)) return null;
10902            if (packageServices == null) {
10903                return null;
10904            }
10905            mFlags = flags;
10906            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
10907            final int N = packageServices.size();
10908            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
10909                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
10910
10911            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
10912            for (int i = 0; i < N; ++i) {
10913                intentFilters = packageServices.get(i).intents;
10914                if (intentFilters != null && intentFilters.size() > 0) {
10915                    PackageParser.ServiceIntentInfo[] array =
10916                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
10917                    intentFilters.toArray(array);
10918                    listCut.add(array);
10919                }
10920            }
10921            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
10922        }
10923
10924        public final void addService(PackageParser.Service s) {
10925            mServices.put(s.getComponentName(), s);
10926            if (DEBUG_SHOW_INFO) {
10927                Log.v(TAG, "  "
10928                        + (s.info.nonLocalizedLabel != null
10929                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
10930                Log.v(TAG, "    Class=" + s.info.name);
10931            }
10932            final int NI = s.intents.size();
10933            int j;
10934            for (j=0; j<NI; j++) {
10935                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
10936                if (DEBUG_SHOW_INFO) {
10937                    Log.v(TAG, "    IntentFilter:");
10938                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
10939                }
10940                if (!intent.debugCheck()) {
10941                    Log.w(TAG, "==> For Service " + s.info.name);
10942                }
10943                addFilter(intent);
10944            }
10945        }
10946
10947        public final void removeService(PackageParser.Service s) {
10948            mServices.remove(s.getComponentName());
10949            if (DEBUG_SHOW_INFO) {
10950                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
10951                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
10952                Log.v(TAG, "    Class=" + s.info.name);
10953            }
10954            final int NI = s.intents.size();
10955            int j;
10956            for (j=0; j<NI; j++) {
10957                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
10958                if (DEBUG_SHOW_INFO) {
10959                    Log.v(TAG, "    IntentFilter:");
10960                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
10961                }
10962                removeFilter(intent);
10963            }
10964        }
10965
10966        @Override
10967        protected boolean allowFilterResult(
10968                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
10969            ServiceInfo filterSi = filter.service.info;
10970            for (int i=dest.size()-1; i>=0; i--) {
10971                ServiceInfo destAi = dest.get(i).serviceInfo;
10972                if (destAi.name == filterSi.name
10973                        && destAi.packageName == filterSi.packageName) {
10974                    return false;
10975                }
10976            }
10977            return true;
10978        }
10979
10980        @Override
10981        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
10982            return new PackageParser.ServiceIntentInfo[size];
10983        }
10984
10985        @Override
10986        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
10987            if (!sUserManager.exists(userId)) return true;
10988            PackageParser.Package p = filter.service.owner;
10989            if (p != null) {
10990                PackageSetting ps = (PackageSetting)p.mExtras;
10991                if (ps != null) {
10992                    // System apps are never considered stopped for purposes of
10993                    // filtering, because there may be no way for the user to
10994                    // actually re-launch them.
10995                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
10996                            && ps.getStopped(userId);
10997                }
10998            }
10999            return false;
11000        }
11001
11002        @Override
11003        protected boolean isPackageForFilter(String packageName,
11004                PackageParser.ServiceIntentInfo info) {
11005            return packageName.equals(info.service.owner.packageName);
11006        }
11007
11008        @Override
11009        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
11010                int match, int userId) {
11011            if (!sUserManager.exists(userId)) return null;
11012            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
11013            if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) {
11014                return null;
11015            }
11016            final PackageParser.Service service = info.service;
11017            PackageSetting ps = (PackageSetting) service.owner.mExtras;
11018            if (ps == null) {
11019                return null;
11020            }
11021            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
11022                    ps.readUserState(userId), userId);
11023            if (si == null) {
11024                return null;
11025            }
11026            final ResolveInfo res = new ResolveInfo();
11027            res.serviceInfo = si;
11028            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
11029                res.filter = filter;
11030            }
11031            res.priority = info.getPriority();
11032            res.preferredOrder = service.owner.mPreferredOrder;
11033            res.match = match;
11034            res.isDefault = info.hasDefault;
11035            res.labelRes = info.labelRes;
11036            res.nonLocalizedLabel = info.nonLocalizedLabel;
11037            res.icon = info.icon;
11038            res.system = res.serviceInfo.applicationInfo.isSystemApp();
11039            return res;
11040        }
11041
11042        @Override
11043        protected void sortResults(List<ResolveInfo> results) {
11044            Collections.sort(results, mResolvePrioritySorter);
11045        }
11046
11047        @Override
11048        protected void dumpFilter(PrintWriter out, String prefix,
11049                PackageParser.ServiceIntentInfo filter) {
11050            out.print(prefix); out.print(
11051                    Integer.toHexString(System.identityHashCode(filter.service)));
11052                    out.print(' ');
11053                    filter.service.printComponentShortName(out);
11054                    out.print(" filter ");
11055                    out.println(Integer.toHexString(System.identityHashCode(filter)));
11056        }
11057
11058        @Override
11059        protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) {
11060            return filter.service;
11061        }
11062
11063        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
11064            PackageParser.Service service = (PackageParser.Service)label;
11065            out.print(prefix); out.print(
11066                    Integer.toHexString(System.identityHashCode(service)));
11067                    out.print(' ');
11068                    service.printComponentShortName(out);
11069            if (count > 1) {
11070                out.print(" ("); out.print(count); out.print(" filters)");
11071            }
11072            out.println();
11073        }
11074
11075//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
11076//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
11077//            final List<ResolveInfo> retList = Lists.newArrayList();
11078//            while (i.hasNext()) {
11079//                final ResolveInfo resolveInfo = (ResolveInfo) i;
11080//                if (isEnabledLP(resolveInfo.serviceInfo)) {
11081//                    retList.add(resolveInfo);
11082//                }
11083//            }
11084//            return retList;
11085//        }
11086
11087        // Keys are String (activity class name), values are Activity.
11088        private final ArrayMap<ComponentName, PackageParser.Service> mServices
11089                = new ArrayMap<ComponentName, PackageParser.Service>();
11090        private int mFlags;
11091    };
11092
11093    private final class ProviderIntentResolver
11094            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
11095        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
11096                boolean defaultOnly, int userId) {
11097            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
11098            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
11099        }
11100
11101        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
11102                int userId) {
11103            if (!sUserManager.exists(userId))
11104                return null;
11105            mFlags = flags;
11106            return super.queryIntent(intent, resolvedType,
11107                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
11108        }
11109
11110        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
11111                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
11112            if (!sUserManager.exists(userId))
11113                return null;
11114            if (packageProviders == null) {
11115                return null;
11116            }
11117            mFlags = flags;
11118            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
11119            final int N = packageProviders.size();
11120            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
11121                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
11122
11123            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
11124            for (int i = 0; i < N; ++i) {
11125                intentFilters = packageProviders.get(i).intents;
11126                if (intentFilters != null && intentFilters.size() > 0) {
11127                    PackageParser.ProviderIntentInfo[] array =
11128                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
11129                    intentFilters.toArray(array);
11130                    listCut.add(array);
11131                }
11132            }
11133            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
11134        }
11135
11136        public final void addProvider(PackageParser.Provider p) {
11137            if (mProviders.containsKey(p.getComponentName())) {
11138                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
11139                return;
11140            }
11141
11142            mProviders.put(p.getComponentName(), p);
11143            if (DEBUG_SHOW_INFO) {
11144                Log.v(TAG, "  "
11145                        + (p.info.nonLocalizedLabel != null
11146                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
11147                Log.v(TAG, "    Class=" + p.info.name);
11148            }
11149            final int NI = p.intents.size();
11150            int j;
11151            for (j = 0; j < NI; j++) {
11152                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
11153                if (DEBUG_SHOW_INFO) {
11154                    Log.v(TAG, "    IntentFilter:");
11155                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
11156                }
11157                if (!intent.debugCheck()) {
11158                    Log.w(TAG, "==> For Provider " + p.info.name);
11159                }
11160                addFilter(intent);
11161            }
11162        }
11163
11164        public final void removeProvider(PackageParser.Provider p) {
11165            mProviders.remove(p.getComponentName());
11166            if (DEBUG_SHOW_INFO) {
11167                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
11168                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
11169                Log.v(TAG, "    Class=" + p.info.name);
11170            }
11171            final int NI = p.intents.size();
11172            int j;
11173            for (j = 0; j < NI; j++) {
11174                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
11175                if (DEBUG_SHOW_INFO) {
11176                    Log.v(TAG, "    IntentFilter:");
11177                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
11178                }
11179                removeFilter(intent);
11180            }
11181        }
11182
11183        @Override
11184        protected boolean allowFilterResult(
11185                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
11186            ProviderInfo filterPi = filter.provider.info;
11187            for (int i = dest.size() - 1; i >= 0; i--) {
11188                ProviderInfo destPi = dest.get(i).providerInfo;
11189                if (destPi.name == filterPi.name
11190                        && destPi.packageName == filterPi.packageName) {
11191                    return false;
11192                }
11193            }
11194            return true;
11195        }
11196
11197        @Override
11198        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
11199            return new PackageParser.ProviderIntentInfo[size];
11200        }
11201
11202        @Override
11203        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
11204            if (!sUserManager.exists(userId))
11205                return true;
11206            PackageParser.Package p = filter.provider.owner;
11207            if (p != null) {
11208                PackageSetting ps = (PackageSetting) p.mExtras;
11209                if (ps != null) {
11210                    // System apps are never considered stopped for purposes of
11211                    // filtering, because there may be no way for the user to
11212                    // actually re-launch them.
11213                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
11214                            && ps.getStopped(userId);
11215                }
11216            }
11217            return false;
11218        }
11219
11220        @Override
11221        protected boolean isPackageForFilter(String packageName,
11222                PackageParser.ProviderIntentInfo info) {
11223            return packageName.equals(info.provider.owner.packageName);
11224        }
11225
11226        @Override
11227        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
11228                int match, int userId) {
11229            if (!sUserManager.exists(userId))
11230                return null;
11231            final PackageParser.ProviderIntentInfo info = filter;
11232            if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) {
11233                return null;
11234            }
11235            final PackageParser.Provider provider = info.provider;
11236            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
11237            if (ps == null) {
11238                return null;
11239            }
11240            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
11241                    ps.readUserState(userId), userId);
11242            if (pi == null) {
11243                return null;
11244            }
11245            final ResolveInfo res = new ResolveInfo();
11246            res.providerInfo = pi;
11247            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
11248                res.filter = filter;
11249            }
11250            res.priority = info.getPriority();
11251            res.preferredOrder = provider.owner.mPreferredOrder;
11252            res.match = match;
11253            res.isDefault = info.hasDefault;
11254            res.labelRes = info.labelRes;
11255            res.nonLocalizedLabel = info.nonLocalizedLabel;
11256            res.icon = info.icon;
11257            res.system = res.providerInfo.applicationInfo.isSystemApp();
11258            return res;
11259        }
11260
11261        @Override
11262        protected void sortResults(List<ResolveInfo> results) {
11263            Collections.sort(results, mResolvePrioritySorter);
11264        }
11265
11266        @Override
11267        protected void dumpFilter(PrintWriter out, String prefix,
11268                PackageParser.ProviderIntentInfo filter) {
11269            out.print(prefix);
11270            out.print(
11271                    Integer.toHexString(System.identityHashCode(filter.provider)));
11272            out.print(' ');
11273            filter.provider.printComponentShortName(out);
11274            out.print(" filter ");
11275            out.println(Integer.toHexString(System.identityHashCode(filter)));
11276        }
11277
11278        @Override
11279        protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) {
11280            return filter.provider;
11281        }
11282
11283        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
11284            PackageParser.Provider provider = (PackageParser.Provider)label;
11285            out.print(prefix); out.print(
11286                    Integer.toHexString(System.identityHashCode(provider)));
11287                    out.print(' ');
11288                    provider.printComponentShortName(out);
11289            if (count > 1) {
11290                out.print(" ("); out.print(count); out.print(" filters)");
11291            }
11292            out.println();
11293        }
11294
11295        private final ArrayMap<ComponentName, PackageParser.Provider> mProviders
11296                = new ArrayMap<ComponentName, PackageParser.Provider>();
11297        private int mFlags;
11298    }
11299
11300    private static final class EphemeralIntentResolver
11301            extends IntentResolver<EphemeralResolveIntentInfo, EphemeralResolveInfo> {
11302        @Override
11303        protected EphemeralResolveIntentInfo[] newArray(int size) {
11304            return new EphemeralResolveIntentInfo[size];
11305        }
11306
11307        @Override
11308        protected boolean isPackageForFilter(String packageName, EphemeralResolveIntentInfo info) {
11309            return true;
11310        }
11311
11312        @Override
11313        protected EphemeralResolveInfo newResult(EphemeralResolveIntentInfo info, int match,
11314                int userId) {
11315            if (!sUserManager.exists(userId)) {
11316                return null;
11317            }
11318            return info.getEphemeralResolveInfo();
11319        }
11320    }
11321
11322    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
11323            new Comparator<ResolveInfo>() {
11324        public int compare(ResolveInfo r1, ResolveInfo r2) {
11325            int v1 = r1.priority;
11326            int v2 = r2.priority;
11327            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
11328            if (v1 != v2) {
11329                return (v1 > v2) ? -1 : 1;
11330            }
11331            v1 = r1.preferredOrder;
11332            v2 = r2.preferredOrder;
11333            if (v1 != v2) {
11334                return (v1 > v2) ? -1 : 1;
11335            }
11336            if (r1.isDefault != r2.isDefault) {
11337                return r1.isDefault ? -1 : 1;
11338            }
11339            v1 = r1.match;
11340            v2 = r2.match;
11341            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
11342            if (v1 != v2) {
11343                return (v1 > v2) ? -1 : 1;
11344            }
11345            if (r1.system != r2.system) {
11346                return r1.system ? -1 : 1;
11347            }
11348            if (r1.activityInfo != null) {
11349                return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName);
11350            }
11351            if (r1.serviceInfo != null) {
11352                return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName);
11353            }
11354            if (r1.providerInfo != null) {
11355                return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName);
11356            }
11357            return 0;
11358        }
11359    };
11360
11361    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
11362            new Comparator<ProviderInfo>() {
11363        public int compare(ProviderInfo p1, ProviderInfo p2) {
11364            final int v1 = p1.initOrder;
11365            final int v2 = p2.initOrder;
11366            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
11367        }
11368    };
11369
11370    final void sendPackageBroadcast(final String action, final String pkg, final Bundle extras,
11371            final int flags, final String targetPkg, final IIntentReceiver finishedReceiver,
11372            final int[] userIds) {
11373        mHandler.post(new Runnable() {
11374            @Override
11375            public void run() {
11376                try {
11377                    final IActivityManager am = ActivityManagerNative.getDefault();
11378                    if (am == null) return;
11379                    final int[] resolvedUserIds;
11380                    if (userIds == null) {
11381                        resolvedUserIds = am.getRunningUserIds();
11382                    } else {
11383                        resolvedUserIds = userIds;
11384                    }
11385                    for (int id : resolvedUserIds) {
11386                        final Intent intent = new Intent(action,
11387                                pkg != null ? Uri.fromParts("package", pkg, null) : null);
11388                        if (extras != null) {
11389                            intent.putExtras(extras);
11390                        }
11391                        if (targetPkg != null) {
11392                            intent.setPackage(targetPkg);
11393                        }
11394                        // Modify the UID when posting to other users
11395                        int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
11396                        if (uid > 0 && UserHandle.getUserId(uid) != id) {
11397                            uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
11398                            intent.putExtra(Intent.EXTRA_UID, uid);
11399                        }
11400                        intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
11401                        intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags);
11402                        if (DEBUG_BROADCASTS) {
11403                            RuntimeException here = new RuntimeException("here");
11404                            here.fillInStackTrace();
11405                            Slog.d(TAG, "Sending to user " + id + ": "
11406                                    + intent.toShortString(false, true, false, false)
11407                                    + " " + intent.getExtras(), here);
11408                        }
11409                        am.broadcastIntent(null, intent, null, finishedReceiver,
11410                                0, null, null, null, android.app.AppOpsManager.OP_NONE,
11411                                null, finishedReceiver != null, false, id);
11412                    }
11413                } catch (RemoteException ex) {
11414                }
11415            }
11416        });
11417    }
11418
11419    /**
11420     * Check if the external storage media is available. This is true if there
11421     * is a mounted external storage medium or if the external storage is
11422     * emulated.
11423     */
11424    private boolean isExternalMediaAvailable() {
11425        return mMediaMounted || Environment.isExternalStorageEmulated();
11426    }
11427
11428    @Override
11429    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
11430        // writer
11431        synchronized (mPackages) {
11432            if (!isExternalMediaAvailable()) {
11433                // If the external storage is no longer mounted at this point,
11434                // the caller may not have been able to delete all of this
11435                // packages files and can not delete any more.  Bail.
11436                return null;
11437            }
11438            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
11439            if (lastPackage != null) {
11440                pkgs.remove(lastPackage);
11441            }
11442            if (pkgs.size() > 0) {
11443                return pkgs.get(0);
11444            }
11445        }
11446        return null;
11447    }
11448
11449    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
11450        final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
11451                userId, andCode ? 1 : 0, packageName);
11452        if (mSystemReady) {
11453            msg.sendToTarget();
11454        } else {
11455            if (mPostSystemReadyMessages == null) {
11456                mPostSystemReadyMessages = new ArrayList<>();
11457            }
11458            mPostSystemReadyMessages.add(msg);
11459        }
11460    }
11461
11462    void startCleaningPackages() {
11463        // reader
11464        if (!isExternalMediaAvailable()) {
11465            return;
11466        }
11467        synchronized (mPackages) {
11468            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
11469                return;
11470            }
11471        }
11472        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
11473        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
11474        IActivityManager am = ActivityManagerNative.getDefault();
11475        if (am != null) {
11476            try {
11477                am.startService(null, intent, null, mContext.getOpPackageName(),
11478                        UserHandle.USER_SYSTEM);
11479            } catch (RemoteException e) {
11480            }
11481        }
11482    }
11483
11484    @Override
11485    public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer,
11486            int installFlags, String installerPackageName, int userId) {
11487        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
11488
11489        final int callingUid = Binder.getCallingUid();
11490        enforceCrossUserPermission(callingUid, userId,
11491                true /* requireFullPermission */, true /* checkShell */, "installPackageAsUser");
11492
11493        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
11494            try {
11495                if (observer != null) {
11496                    observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null);
11497                }
11498            } catch (RemoteException re) {
11499            }
11500            return;
11501        }
11502
11503        if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) {
11504            installFlags |= PackageManager.INSTALL_FROM_ADB;
11505
11506        } else {
11507            // Caller holds INSTALL_PACKAGES permission, so we're less strict
11508            // about installerPackageName.
11509
11510            installFlags &= ~PackageManager.INSTALL_FROM_ADB;
11511            installFlags &= ~PackageManager.INSTALL_ALL_USERS;
11512        }
11513
11514        UserHandle user;
11515        if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) {
11516            user = UserHandle.ALL;
11517        } else {
11518            user = new UserHandle(userId);
11519        }
11520
11521        // Only system components can circumvent runtime permissions when installing.
11522        if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0
11523                && mContext.checkCallingOrSelfPermission(Manifest.permission
11524                .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) {
11525            throw new SecurityException("You need the "
11526                    + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission "
11527                    + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag");
11528        }
11529
11530        final File originFile = new File(originPath);
11531        final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile);
11532
11533        final Message msg = mHandler.obtainMessage(INIT_COPY);
11534        final VerificationInfo verificationInfo = new VerificationInfo(
11535                null /*originatingUri*/, null /*referrer*/, -1 /*originatingUid*/, callingUid);
11536        final InstallParams params = new InstallParams(origin, null /*moveInfo*/, observer,
11537                installFlags, installerPackageName, null /*volumeUuid*/, verificationInfo, user,
11538                null /*packageAbiOverride*/, null /*grantedPermissions*/,
11539                null /*certificates*/);
11540        params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params));
11541        msg.obj = params;
11542
11543        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser",
11544                System.identityHashCode(msg.obj));
11545        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
11546                System.identityHashCode(msg.obj));
11547
11548        mHandler.sendMessage(msg);
11549    }
11550
11551    void installStage(String packageName, File stagedDir, String stagedCid,
11552            IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams,
11553            String installerPackageName, int installerUid, UserHandle user,
11554            Certificate[][] certificates) {
11555        if (DEBUG_EPHEMERAL) {
11556            if ((sessionParams.installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) {
11557                Slog.d(TAG, "Ephemeral install of " + packageName);
11558            }
11559        }
11560        final VerificationInfo verificationInfo = new VerificationInfo(
11561                sessionParams.originatingUri, sessionParams.referrerUri,
11562                sessionParams.originatingUid, installerUid);
11563
11564        final OriginInfo origin;
11565        if (stagedDir != null) {
11566            origin = OriginInfo.fromStagedFile(stagedDir);
11567        } else {
11568            origin = OriginInfo.fromStagedContainer(stagedCid);
11569        }
11570
11571        final Message msg = mHandler.obtainMessage(INIT_COPY);
11572        final InstallParams params = new InstallParams(origin, null, observer,
11573                sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid,
11574                verificationInfo, user, sessionParams.abiOverride,
11575                sessionParams.grantedRuntimePermissions, certificates);
11576        params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params));
11577        msg.obj = params;
11578
11579        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage",
11580                System.identityHashCode(msg.obj));
11581        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
11582                System.identityHashCode(msg.obj));
11583
11584        mHandler.sendMessage(msg);
11585    }
11586
11587    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting,
11588            int userId) {
11589        final boolean isSystem = isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
11590        sendPackageAddedForUser(packageName, isSystem, pkgSetting.appId, userId);
11591    }
11592
11593    private void sendPackageAddedForUser(String packageName, boolean isSystem,
11594            int appId, int userId) {
11595        Bundle extras = new Bundle(1);
11596        extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, appId));
11597
11598        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
11599                packageName, extras, 0, null, null, new int[] {userId});
11600        try {
11601            IActivityManager am = ActivityManagerNative.getDefault();
11602            if (isSystem && am.isUserRunning(userId, 0)) {
11603                // The just-installed/enabled app is bundled on the system, so presumed
11604                // to be able to run automatically without needing an explicit launch.
11605                // Send it a BOOT_COMPLETED if it would ordinarily have gotten one.
11606                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED)
11607                        .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES)
11608                        .setPackage(packageName);
11609                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null,
11610                        android.app.AppOpsManager.OP_NONE, null, false, false, userId);
11611            }
11612        } catch (RemoteException e) {
11613            // shouldn't happen
11614            Slog.w(TAG, "Unable to bootstrap installed package", e);
11615        }
11616    }
11617
11618    @Override
11619    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
11620            int userId) {
11621        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
11622        PackageSetting pkgSetting;
11623        final int uid = Binder.getCallingUid();
11624        enforceCrossUserPermission(uid, userId,
11625                true /* requireFullPermission */, true /* checkShell */,
11626                "setApplicationHiddenSetting for user " + userId);
11627
11628        if (hidden && isPackageDeviceAdmin(packageName, userId)) {
11629            Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
11630            return false;
11631        }
11632
11633        long callingId = Binder.clearCallingIdentity();
11634        try {
11635            boolean sendAdded = false;
11636            boolean sendRemoved = false;
11637            // writer
11638            synchronized (mPackages) {
11639                pkgSetting = mSettings.mPackages.get(packageName);
11640                if (pkgSetting == null) {
11641                    return false;
11642                }
11643                if (pkgSetting.getHidden(userId) != hidden) {
11644                    pkgSetting.setHidden(hidden, userId);
11645                    mSettings.writePackageRestrictionsLPr(userId);
11646                    if (hidden) {
11647                        sendRemoved = true;
11648                    } else {
11649                        sendAdded = true;
11650                    }
11651                }
11652            }
11653            if (sendAdded) {
11654                sendPackageAddedForUser(packageName, pkgSetting, userId);
11655                return true;
11656            }
11657            if (sendRemoved) {
11658                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
11659                        "hiding pkg");
11660                sendApplicationHiddenForUser(packageName, pkgSetting, userId);
11661                return true;
11662            }
11663        } finally {
11664            Binder.restoreCallingIdentity(callingId);
11665        }
11666        return false;
11667    }
11668
11669    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
11670            int userId) {
11671        final PackageRemovedInfo info = new PackageRemovedInfo();
11672        info.removedPackage = packageName;
11673        info.removedUsers = new int[] {userId};
11674        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
11675        info.sendPackageRemovedBroadcasts(true /*killApp*/);
11676    }
11677
11678    private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended) {
11679        if (pkgList.length > 0) {
11680            Bundle extras = new Bundle(1);
11681            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
11682
11683            sendPackageBroadcast(
11684                    suspended ? Intent.ACTION_PACKAGES_SUSPENDED
11685                            : Intent.ACTION_PACKAGES_UNSUSPENDED,
11686                    null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null,
11687                    new int[] {userId});
11688        }
11689    }
11690
11691    /**
11692     * Returns true if application is not found or there was an error. Otherwise it returns
11693     * the hidden state of the package for the given user.
11694     */
11695    @Override
11696    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
11697        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
11698        enforceCrossUserPermission(Binder.getCallingUid(), userId,
11699                true /* requireFullPermission */, false /* checkShell */,
11700                "getApplicationHidden for user " + userId);
11701        PackageSetting pkgSetting;
11702        long callingId = Binder.clearCallingIdentity();
11703        try {
11704            // writer
11705            synchronized (mPackages) {
11706                pkgSetting = mSettings.mPackages.get(packageName);
11707                if (pkgSetting == null) {
11708                    return true;
11709                }
11710                return pkgSetting.getHidden(userId);
11711            }
11712        } finally {
11713            Binder.restoreCallingIdentity(callingId);
11714        }
11715    }
11716
11717    /**
11718     * @hide
11719     */
11720    @Override
11721    public int installExistingPackageAsUser(String packageName, int userId) {
11722        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
11723                null);
11724        PackageSetting pkgSetting;
11725        final int uid = Binder.getCallingUid();
11726        enforceCrossUserPermission(uid, userId,
11727                true /* requireFullPermission */, true /* checkShell */,
11728                "installExistingPackage for user " + userId);
11729        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
11730            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
11731        }
11732
11733        long callingId = Binder.clearCallingIdentity();
11734        try {
11735            boolean installed = false;
11736
11737            // writer
11738            synchronized (mPackages) {
11739                pkgSetting = mSettings.mPackages.get(packageName);
11740                if (pkgSetting == null) {
11741                    return PackageManager.INSTALL_FAILED_INVALID_URI;
11742                }
11743                if (!pkgSetting.getInstalled(userId)) {
11744                    pkgSetting.setInstalled(true, userId);
11745                    pkgSetting.setHidden(false, userId);
11746                    mSettings.writePackageRestrictionsLPr(userId);
11747                    installed = true;
11748                }
11749            }
11750
11751            if (installed) {
11752                if (pkgSetting.pkg != null) {
11753                    synchronized (mInstallLock) {
11754                        // We don't need to freeze for a brand new install
11755                        prepareAppDataAfterInstallLIF(pkgSetting.pkg);
11756                    }
11757                }
11758                sendPackageAddedForUser(packageName, pkgSetting, userId);
11759            }
11760        } finally {
11761            Binder.restoreCallingIdentity(callingId);
11762        }
11763
11764        return PackageManager.INSTALL_SUCCEEDED;
11765    }
11766
11767    boolean isUserRestricted(int userId, String restrictionKey) {
11768        Bundle restrictions = sUserManager.getUserRestrictions(userId);
11769        if (restrictions.getBoolean(restrictionKey, false)) {
11770            Log.w(TAG, "User is restricted: " + restrictionKey);
11771            return true;
11772        }
11773        return false;
11774    }
11775
11776    @Override
11777    public String[] setPackagesSuspendedAsUser(String[] packageNames, boolean suspended,
11778            int userId) {
11779        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
11780        enforceCrossUserPermission(Binder.getCallingUid(), userId,
11781                true /* requireFullPermission */, true /* checkShell */,
11782                "setPackagesSuspended for user " + userId);
11783
11784        if (ArrayUtils.isEmpty(packageNames)) {
11785            return packageNames;
11786        }
11787
11788        // List of package names for whom the suspended state has changed.
11789        List<String> changedPackages = new ArrayList<>(packageNames.length);
11790        // List of package names for whom the suspended state is not set as requested in this
11791        // method.
11792        List<String> unactionedPackages = new ArrayList<>(packageNames.length);
11793        long callingId = Binder.clearCallingIdentity();
11794        try {
11795            for (int i = 0; i < packageNames.length; i++) {
11796                String packageName = packageNames[i];
11797                boolean changed = false;
11798                final int appId;
11799                synchronized (mPackages) {
11800                    final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
11801                    if (pkgSetting == null) {
11802                        Slog.w(TAG, "Could not find package setting for package \"" + packageName
11803                                + "\". Skipping suspending/un-suspending.");
11804                        unactionedPackages.add(packageName);
11805                        continue;
11806                    }
11807                    appId = pkgSetting.appId;
11808                    if (pkgSetting.getSuspended(userId) != suspended) {
11809                        if (!canSuspendPackageForUserLocked(packageName, userId)) {
11810                            unactionedPackages.add(packageName);
11811                            continue;
11812                        }
11813                        pkgSetting.setSuspended(suspended, userId);
11814                        mSettings.writePackageRestrictionsLPr(userId);
11815                        changed = true;
11816                        changedPackages.add(packageName);
11817                    }
11818                }
11819
11820                if (changed && suspended) {
11821                    killApplication(packageName, UserHandle.getUid(userId, appId),
11822                            "suspending package");
11823                }
11824            }
11825        } finally {
11826            Binder.restoreCallingIdentity(callingId);
11827        }
11828
11829        if (!changedPackages.isEmpty()) {
11830            sendPackagesSuspendedForUser(changedPackages.toArray(
11831                    new String[changedPackages.size()]), userId, suspended);
11832        }
11833
11834        return unactionedPackages.toArray(new String[unactionedPackages.size()]);
11835    }
11836
11837    @Override
11838    public boolean isPackageSuspendedForUser(String packageName, int userId) {
11839        enforceCrossUserPermission(Binder.getCallingUid(), userId,
11840                true /* requireFullPermission */, false /* checkShell */,
11841                "isPackageSuspendedForUser for user " + userId);
11842        synchronized (mPackages) {
11843            final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
11844            if (pkgSetting == null) {
11845                throw new IllegalArgumentException("Unknown target package: " + packageName);
11846            }
11847            return pkgSetting.getSuspended(userId);
11848        }
11849    }
11850
11851    private boolean canSuspendPackageForUserLocked(String packageName, int userId) {
11852        if (isPackageDeviceAdmin(packageName, userId)) {
11853            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
11854                    + "\": has an active device admin");
11855            return false;
11856        }
11857
11858        String activeLauncherPackageName = getActiveLauncherPackageName(userId);
11859        if (packageName.equals(activeLauncherPackageName)) {
11860            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
11861                    + "\": contains the active launcher");
11862            return false;
11863        }
11864
11865        if (packageName.equals(mRequiredInstallerPackage)) {
11866            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
11867                    + "\": required for package installation");
11868            return false;
11869        }
11870
11871        if (packageName.equals(mRequiredVerifierPackage)) {
11872            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
11873                    + "\": required for package verification");
11874            return false;
11875        }
11876
11877        if (packageName.equals(getDefaultDialerPackageName(userId))) {
11878            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
11879                    + "\": is the default dialer");
11880            return false;
11881        }
11882
11883        return true;
11884    }
11885
11886    private String getActiveLauncherPackageName(int userId) {
11887        Intent intent = new Intent(Intent.ACTION_MAIN);
11888        intent.addCategory(Intent.CATEGORY_HOME);
11889        ResolveInfo resolveInfo = resolveIntent(
11890                intent,
11891                intent.resolveTypeIfNeeded(mContext.getContentResolver()),
11892                PackageManager.MATCH_DEFAULT_ONLY,
11893                userId);
11894
11895        return resolveInfo == null ? null : resolveInfo.activityInfo.packageName;
11896    }
11897
11898    private String getDefaultDialerPackageName(int userId) {
11899        synchronized (mPackages) {
11900            return mSettings.getDefaultDialerPackageNameLPw(userId);
11901        }
11902    }
11903
11904    @Override
11905    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
11906        mContext.enforceCallingOrSelfPermission(
11907                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
11908                "Only package verification agents can verify applications");
11909
11910        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
11911        final PackageVerificationResponse response = new PackageVerificationResponse(
11912                verificationCode, Binder.getCallingUid());
11913        msg.arg1 = id;
11914        msg.obj = response;
11915        mHandler.sendMessage(msg);
11916    }
11917
11918    @Override
11919    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
11920            long millisecondsToDelay) {
11921        mContext.enforceCallingOrSelfPermission(
11922                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
11923                "Only package verification agents can extend verification timeouts");
11924
11925        final PackageVerificationState state = mPendingVerification.get(id);
11926        final PackageVerificationResponse response = new PackageVerificationResponse(
11927                verificationCodeAtTimeout, Binder.getCallingUid());
11928
11929        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
11930            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
11931        }
11932        if (millisecondsToDelay < 0) {
11933            millisecondsToDelay = 0;
11934        }
11935        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
11936                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
11937            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
11938        }
11939
11940        if ((state != null) && !state.timeoutExtended()) {
11941            state.extendTimeout();
11942
11943            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
11944            msg.arg1 = id;
11945            msg.obj = response;
11946            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
11947        }
11948    }
11949
11950    private void broadcastPackageVerified(int verificationId, Uri packageUri,
11951            int verificationCode, UserHandle user) {
11952        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
11953        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
11954        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
11955        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
11956        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
11957
11958        mContext.sendBroadcastAsUser(intent, user,
11959                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
11960    }
11961
11962    private ComponentName matchComponentForVerifier(String packageName,
11963            List<ResolveInfo> receivers) {
11964        ActivityInfo targetReceiver = null;
11965
11966        final int NR = receivers.size();
11967        for (int i = 0; i < NR; i++) {
11968            final ResolveInfo info = receivers.get(i);
11969            if (info.activityInfo == null) {
11970                continue;
11971            }
11972
11973            if (packageName.equals(info.activityInfo.packageName)) {
11974                targetReceiver = info.activityInfo;
11975                break;
11976            }
11977        }
11978
11979        if (targetReceiver == null) {
11980            return null;
11981        }
11982
11983        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
11984    }
11985
11986    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
11987            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
11988        if (pkgInfo.verifiers.length == 0) {
11989            return null;
11990        }
11991
11992        final int N = pkgInfo.verifiers.length;
11993        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
11994        for (int i = 0; i < N; i++) {
11995            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
11996
11997            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
11998                    receivers);
11999            if (comp == null) {
12000                continue;
12001            }
12002
12003            final int verifierUid = getUidForVerifier(verifierInfo);
12004            if (verifierUid == -1) {
12005                continue;
12006            }
12007
12008            if (DEBUG_VERIFY) {
12009                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
12010                        + " with the correct signature");
12011            }
12012            sufficientVerifiers.add(comp);
12013            verificationState.addSufficientVerifier(verifierUid);
12014        }
12015
12016        return sufficientVerifiers;
12017    }
12018
12019    private int getUidForVerifier(VerifierInfo verifierInfo) {
12020        synchronized (mPackages) {
12021            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
12022            if (pkg == null) {
12023                return -1;
12024            } else if (pkg.mSignatures.length != 1) {
12025                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
12026                        + " has more than one signature; ignoring");
12027                return -1;
12028            }
12029
12030            /*
12031             * If the public key of the package's signature does not match
12032             * our expected public key, then this is a different package and
12033             * we should skip.
12034             */
12035
12036            final byte[] expectedPublicKey;
12037            try {
12038                final Signature verifierSig = pkg.mSignatures[0];
12039                final PublicKey publicKey = verifierSig.getPublicKey();
12040                expectedPublicKey = publicKey.getEncoded();
12041            } catch (CertificateException e) {
12042                return -1;
12043            }
12044
12045            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
12046
12047            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
12048                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
12049                        + " does not have the expected public key; ignoring");
12050                return -1;
12051            }
12052
12053            return pkg.applicationInfo.uid;
12054        }
12055    }
12056
12057    @Override
12058    public void finishPackageInstall(int token, boolean didLaunch) {
12059        enforceSystemOrRoot("Only the system is allowed to finish installs");
12060
12061        if (DEBUG_INSTALL) {
12062            Slog.v(TAG, "BM finishing package install for " + token);
12063        }
12064        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
12065
12066        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, didLaunch ? 1 : 0);
12067        mHandler.sendMessage(msg);
12068    }
12069
12070    /**
12071     * Get the verification agent timeout.
12072     *
12073     * @return verification timeout in milliseconds
12074     */
12075    private long getVerificationTimeout() {
12076        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
12077                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
12078                DEFAULT_VERIFICATION_TIMEOUT);
12079    }
12080
12081    /**
12082     * Get the default verification agent response code.
12083     *
12084     * @return default verification response code
12085     */
12086    private int getDefaultVerificationResponse() {
12087        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
12088                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
12089                DEFAULT_VERIFICATION_RESPONSE);
12090    }
12091
12092    /**
12093     * Check whether or not package verification has been enabled.
12094     *
12095     * @return true if verification should be performed
12096     */
12097    private boolean isVerificationEnabled(int userId, int installFlags) {
12098        if (!DEFAULT_VERIFY_ENABLE) {
12099            return false;
12100        }
12101        // Ephemeral apps don't get the full verification treatment
12102        if ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) {
12103            if (DEBUG_EPHEMERAL) {
12104                Slog.d(TAG, "INSTALL_EPHEMERAL so skipping verification");
12105            }
12106            return false;
12107        }
12108
12109        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
12110
12111        // Check if installing from ADB
12112        if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
12113            // Do not run verification in a test harness environment
12114            if (ActivityManager.isRunningInTestHarness()) {
12115                return false;
12116            }
12117            if (ensureVerifyAppsEnabled) {
12118                return true;
12119            }
12120            // Check if the developer does not want package verification for ADB installs
12121            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
12122                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
12123                return false;
12124            }
12125        }
12126
12127        if (ensureVerifyAppsEnabled) {
12128            return true;
12129        }
12130
12131        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
12132                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
12133    }
12134
12135    @Override
12136    public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains)
12137            throws RemoteException {
12138        mContext.enforceCallingOrSelfPermission(
12139                Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
12140                "Only intentfilter verification agents can verify applications");
12141
12142        final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED);
12143        final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse(
12144                Binder.getCallingUid(), verificationCode, failedDomains);
12145        msg.arg1 = id;
12146        msg.obj = response;
12147        mHandler.sendMessage(msg);
12148    }
12149
12150    @Override
12151    public int getIntentVerificationStatus(String packageName, int userId) {
12152        synchronized (mPackages) {
12153            return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
12154        }
12155    }
12156
12157    @Override
12158    public boolean updateIntentVerificationStatus(String packageName, int status, int userId) {
12159        mContext.enforceCallingOrSelfPermission(
12160                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
12161
12162        boolean result = false;
12163        synchronized (mPackages) {
12164            result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId);
12165        }
12166        if (result) {
12167            scheduleWritePackageRestrictionsLocked(userId);
12168        }
12169        return result;
12170    }
12171
12172    @Override
12173    public @NonNull ParceledListSlice<IntentFilterVerificationInfo> getIntentFilterVerifications(
12174            String packageName) {
12175        synchronized (mPackages) {
12176            return new ParceledListSlice<>(mSettings.getIntentFilterVerificationsLPr(packageName));
12177        }
12178    }
12179
12180    @Override
12181    public @NonNull ParceledListSlice<IntentFilter> getAllIntentFilters(String packageName) {
12182        if (TextUtils.isEmpty(packageName)) {
12183            return ParceledListSlice.emptyList();
12184        }
12185        synchronized (mPackages) {
12186            PackageParser.Package pkg = mPackages.get(packageName);
12187            if (pkg == null || pkg.activities == null) {
12188                return ParceledListSlice.emptyList();
12189            }
12190            final int count = pkg.activities.size();
12191            ArrayList<IntentFilter> result = new ArrayList<>();
12192            for (int n=0; n<count; n++) {
12193                PackageParser.Activity activity = pkg.activities.get(n);
12194                if (activity.intents != null && activity.intents.size() > 0) {
12195                    result.addAll(activity.intents);
12196                }
12197            }
12198            return new ParceledListSlice<>(result);
12199        }
12200    }
12201
12202    @Override
12203    public boolean setDefaultBrowserPackageName(String packageName, int userId) {
12204        mContext.enforceCallingOrSelfPermission(
12205                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
12206
12207        synchronized (mPackages) {
12208            boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId);
12209            if (packageName != null) {
12210                result |= updateIntentVerificationStatus(packageName,
12211                        PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS,
12212                        userId);
12213                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr(
12214                        packageName, userId);
12215            }
12216            return result;
12217        }
12218    }
12219
12220    @Override
12221    public String getDefaultBrowserPackageName(int userId) {
12222        synchronized (mPackages) {
12223            return mSettings.getDefaultBrowserPackageNameLPw(userId);
12224        }
12225    }
12226
12227    /**
12228     * Get the "allow unknown sources" setting.
12229     *
12230     * @return the current "allow unknown sources" setting
12231     */
12232    private int getUnknownSourcesSettings() {
12233        return android.provider.Settings.Secure.getInt(mContext.getContentResolver(),
12234                android.provider.Settings.Secure.INSTALL_NON_MARKET_APPS,
12235                -1);
12236    }
12237
12238    @Override
12239    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
12240        final int uid = Binder.getCallingUid();
12241        // writer
12242        synchronized (mPackages) {
12243            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
12244            if (targetPackageSetting == null) {
12245                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
12246            }
12247
12248            PackageSetting installerPackageSetting;
12249            if (installerPackageName != null) {
12250                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
12251                if (installerPackageSetting == null) {
12252                    throw new IllegalArgumentException("Unknown installer package: "
12253                            + installerPackageName);
12254                }
12255            } else {
12256                installerPackageSetting = null;
12257            }
12258
12259            Signature[] callerSignature;
12260            Object obj = mSettings.getUserIdLPr(uid);
12261            if (obj != null) {
12262                if (obj instanceof SharedUserSetting) {
12263                    callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
12264                } else if (obj instanceof PackageSetting) {
12265                    callerSignature = ((PackageSetting)obj).signatures.mSignatures;
12266                } else {
12267                    throw new SecurityException("Bad object " + obj + " for uid " + uid);
12268                }
12269            } else {
12270                throw new SecurityException("Unknown calling UID: " + uid);
12271            }
12272
12273            // Verify: can't set installerPackageName to a package that is
12274            // not signed with the same cert as the caller.
12275            if (installerPackageSetting != null) {
12276                if (compareSignatures(callerSignature,
12277                        installerPackageSetting.signatures.mSignatures)
12278                        != PackageManager.SIGNATURE_MATCH) {
12279                    throw new SecurityException(
12280                            "Caller does not have same cert as new installer package "
12281                            + installerPackageName);
12282                }
12283            }
12284
12285            // Verify: if target already has an installer package, it must
12286            // be signed with the same cert as the caller.
12287            if (targetPackageSetting.installerPackageName != null) {
12288                PackageSetting setting = mSettings.mPackages.get(
12289                        targetPackageSetting.installerPackageName);
12290                // If the currently set package isn't valid, then it's always
12291                // okay to change it.
12292                if (setting != null) {
12293                    if (compareSignatures(callerSignature,
12294                            setting.signatures.mSignatures)
12295                            != PackageManager.SIGNATURE_MATCH) {
12296                        throw new SecurityException(
12297                                "Caller does not have same cert as old installer package "
12298                                + targetPackageSetting.installerPackageName);
12299                    }
12300                }
12301            }
12302
12303            // Okay!
12304            targetPackageSetting.installerPackageName = installerPackageName;
12305            if (installerPackageName != null) {
12306                mSettings.mInstallerPackages.add(installerPackageName);
12307            }
12308            scheduleWriteSettingsLocked();
12309        }
12310    }
12311
12312    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
12313        // Queue up an async operation since the package installation may take a little while.
12314        mHandler.post(new Runnable() {
12315            public void run() {
12316                mHandler.removeCallbacks(this);
12317                 // Result object to be returned
12318                PackageInstalledInfo res = new PackageInstalledInfo();
12319                res.setReturnCode(currentStatus);
12320                res.uid = -1;
12321                res.pkg = null;
12322                res.removedInfo = null;
12323                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
12324                    args.doPreInstall(res.returnCode);
12325                    synchronized (mInstallLock) {
12326                        installPackageTracedLI(args, res);
12327                    }
12328                    args.doPostInstall(res.returnCode, res.uid);
12329                }
12330
12331                // A restore should be performed at this point if (a) the install
12332                // succeeded, (b) the operation is not an update, and (c) the new
12333                // package has not opted out of backup participation.
12334                final boolean update = res.removedInfo != null
12335                        && res.removedInfo.removedPackage != null;
12336                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
12337                boolean doRestore = !update
12338                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
12339
12340                // Set up the post-install work request bookkeeping.  This will be used
12341                // and cleaned up by the post-install event handling regardless of whether
12342                // there's a restore pass performed.  Token values are >= 1.
12343                int token;
12344                if (mNextInstallToken < 0) mNextInstallToken = 1;
12345                token = mNextInstallToken++;
12346
12347                PostInstallData data = new PostInstallData(args, res);
12348                mRunningInstalls.put(token, data);
12349                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
12350
12351                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
12352                    // Pass responsibility to the Backup Manager.  It will perform a
12353                    // restore if appropriate, then pass responsibility back to the
12354                    // Package Manager to run the post-install observer callbacks
12355                    // and broadcasts.
12356                    IBackupManager bm = IBackupManager.Stub.asInterface(
12357                            ServiceManager.getService(Context.BACKUP_SERVICE));
12358                    if (bm != null) {
12359                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
12360                                + " to BM for possible restore");
12361                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
12362                        try {
12363                            // TODO: http://b/22388012
12364                            if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) {
12365                                bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
12366                            } else {
12367                                doRestore = false;
12368                            }
12369                        } catch (RemoteException e) {
12370                            // can't happen; the backup manager is local
12371                        } catch (Exception e) {
12372                            Slog.e(TAG, "Exception trying to enqueue restore", e);
12373                            doRestore = false;
12374                        }
12375                    } else {
12376                        Slog.e(TAG, "Backup Manager not found!");
12377                        doRestore = false;
12378                    }
12379                }
12380
12381                if (!doRestore) {
12382                    // No restore possible, or the Backup Manager was mysteriously not
12383                    // available -- just fire the post-install work request directly.
12384                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
12385
12386                    Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token);
12387
12388                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
12389                    mHandler.sendMessage(msg);
12390                }
12391            }
12392        });
12393    }
12394
12395    /**
12396     * Callback from PackageSettings whenever an app is first transitioned out of the
12397     * 'stopped' state.  Normally we just issue the broadcast, but we can't do that if
12398     * the app was "launched" for a restoreAtInstall operation.  Therefore we check
12399     * here whether the app is the target of an ongoing install, and only send the
12400     * broadcast immediately if it is not in that state.  If it *is* undergoing a restore,
12401     * the first-launch broadcast will be sent implicitly on that basis in POST_INSTALL
12402     * handling.
12403     */
12404    void notifyFirstLaunch(final String pkgName, final String installerPackage, final int userId) {
12405        // Serialize this with the rest of the install-process message chain.  In the
12406        // restore-at-install case, this Runnable will necessarily run before the
12407        // POST_INSTALL message is processed, so the contents of mRunningInstalls
12408        // are coherent.  In the non-restore case, the app has already completed install
12409        // and been launched through some other means, so it is not in a problematic
12410        // state for observers to see the FIRST_LAUNCH signal.
12411        mHandler.post(new Runnable() {
12412            @Override
12413            public void run() {
12414                for (int i = 0; i < mRunningInstalls.size(); i++) {
12415                    final PostInstallData data = mRunningInstalls.valueAt(i);
12416                    if (pkgName.equals(data.res.pkg.applicationInfo.packageName)) {
12417                        // right package; but is it for the right user?
12418                        for (int uIndex = 0; uIndex < data.res.newUsers.length; uIndex++) {
12419                            if (userId == data.res.newUsers[uIndex]) {
12420                                if (DEBUG_BACKUP) {
12421                                    Slog.i(TAG, "Package " + pkgName
12422                                            + " being restored so deferring FIRST_LAUNCH");
12423                                }
12424                                return;
12425                            }
12426                        }
12427                    }
12428                }
12429                // didn't find it, so not being restored
12430                if (DEBUG_BACKUP) {
12431                    Slog.i(TAG, "Package " + pkgName + " sending normal FIRST_LAUNCH");
12432                }
12433                sendFirstLaunchBroadcast(pkgName, installerPackage, new int[] {userId});
12434            }
12435        });
12436    }
12437
12438    private void sendFirstLaunchBroadcast(String pkgName, String installerPkg, int[] userIds) {
12439        sendPackageBroadcast(Intent.ACTION_PACKAGE_FIRST_LAUNCH, pkgName, null, 0,
12440                installerPkg, null, userIds);
12441    }
12442
12443    private abstract class HandlerParams {
12444        private static final int MAX_RETRIES = 4;
12445
12446        /**
12447         * Number of times startCopy() has been attempted and had a non-fatal
12448         * error.
12449         */
12450        private int mRetries = 0;
12451
12452        /** User handle for the user requesting the information or installation. */
12453        private final UserHandle mUser;
12454        String traceMethod;
12455        int traceCookie;
12456
12457        HandlerParams(UserHandle user) {
12458            mUser = user;
12459        }
12460
12461        UserHandle getUser() {
12462            return mUser;
12463        }
12464
12465        HandlerParams setTraceMethod(String traceMethod) {
12466            this.traceMethod = traceMethod;
12467            return this;
12468        }
12469
12470        HandlerParams setTraceCookie(int traceCookie) {
12471            this.traceCookie = traceCookie;
12472            return this;
12473        }
12474
12475        final boolean startCopy() {
12476            boolean res;
12477            try {
12478                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
12479
12480                if (++mRetries > MAX_RETRIES) {
12481                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
12482                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
12483                    handleServiceError();
12484                    return false;
12485                } else {
12486                    handleStartCopy();
12487                    res = true;
12488                }
12489            } catch (RemoteException e) {
12490                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
12491                mHandler.sendEmptyMessage(MCS_RECONNECT);
12492                res = false;
12493            }
12494            handleReturnCode();
12495            return res;
12496        }
12497
12498        final void serviceError() {
12499            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
12500            handleServiceError();
12501            handleReturnCode();
12502        }
12503
12504        abstract void handleStartCopy() throws RemoteException;
12505        abstract void handleServiceError();
12506        abstract void handleReturnCode();
12507    }
12508
12509    class MeasureParams extends HandlerParams {
12510        private final PackageStats mStats;
12511        private boolean mSuccess;
12512
12513        private final IPackageStatsObserver mObserver;
12514
12515        public MeasureParams(PackageStats stats, IPackageStatsObserver observer) {
12516            super(new UserHandle(stats.userHandle));
12517            mObserver = observer;
12518            mStats = stats;
12519        }
12520
12521        @Override
12522        public String toString() {
12523            return "MeasureParams{"
12524                + Integer.toHexString(System.identityHashCode(this))
12525                + " " + mStats.packageName + "}";
12526        }
12527
12528        @Override
12529        void handleStartCopy() throws RemoteException {
12530            synchronized (mInstallLock) {
12531                mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats);
12532            }
12533
12534            if (mSuccess) {
12535                final boolean mounted;
12536                if (Environment.isExternalStorageEmulated()) {
12537                    mounted = true;
12538                } else {
12539                    final String status = Environment.getExternalStorageState();
12540                    mounted = (Environment.MEDIA_MOUNTED.equals(status)
12541                            || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status));
12542                }
12543
12544                if (mounted) {
12545                    final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle);
12546
12547                    mStats.externalCacheSize = calculateDirectorySize(mContainerService,
12548                            userEnv.buildExternalStorageAppCacheDirs(mStats.packageName));
12549
12550                    mStats.externalDataSize = calculateDirectorySize(mContainerService,
12551                            userEnv.buildExternalStorageAppDataDirs(mStats.packageName));
12552
12553                    // Always subtract cache size, since it's a subdirectory
12554                    mStats.externalDataSize -= mStats.externalCacheSize;
12555
12556                    mStats.externalMediaSize = calculateDirectorySize(mContainerService,
12557                            userEnv.buildExternalStorageAppMediaDirs(mStats.packageName));
12558
12559                    mStats.externalObbSize = calculateDirectorySize(mContainerService,
12560                            userEnv.buildExternalStorageAppObbDirs(mStats.packageName));
12561                }
12562            }
12563        }
12564
12565        @Override
12566        void handleReturnCode() {
12567            if (mObserver != null) {
12568                try {
12569                    mObserver.onGetStatsCompleted(mStats, mSuccess);
12570                } catch (RemoteException e) {
12571                    Slog.i(TAG, "Observer no longer exists.");
12572                }
12573            }
12574        }
12575
12576        @Override
12577        void handleServiceError() {
12578            Slog.e(TAG, "Could not measure application " + mStats.packageName
12579                            + " external storage");
12580        }
12581    }
12582
12583    private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths)
12584            throws RemoteException {
12585        long result = 0;
12586        for (File path : paths) {
12587            result += mcs.calculateDirectorySize(path.getAbsolutePath());
12588        }
12589        return result;
12590    }
12591
12592    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
12593        for (File path : paths) {
12594            try {
12595                mcs.clearDirectory(path.getAbsolutePath());
12596            } catch (RemoteException e) {
12597            }
12598        }
12599    }
12600
12601    static class OriginInfo {
12602        /**
12603         * Location where install is coming from, before it has been
12604         * copied/renamed into place. This could be a single monolithic APK
12605         * file, or a cluster directory. This location may be untrusted.
12606         */
12607        final File file;
12608        final String cid;
12609
12610        /**
12611         * Flag indicating that {@link #file} or {@link #cid} has already been
12612         * staged, meaning downstream users don't need to defensively copy the
12613         * contents.
12614         */
12615        final boolean staged;
12616
12617        /**
12618         * Flag indicating that {@link #file} or {@link #cid} is an already
12619         * installed app that is being moved.
12620         */
12621        final boolean existing;
12622
12623        final String resolvedPath;
12624        final File resolvedFile;
12625
12626        static OriginInfo fromNothing() {
12627            return new OriginInfo(null, null, false, false);
12628        }
12629
12630        static OriginInfo fromUntrustedFile(File file) {
12631            return new OriginInfo(file, null, false, false);
12632        }
12633
12634        static OriginInfo fromExistingFile(File file) {
12635            return new OriginInfo(file, null, false, true);
12636        }
12637
12638        static OriginInfo fromStagedFile(File file) {
12639            return new OriginInfo(file, null, true, false);
12640        }
12641
12642        static OriginInfo fromStagedContainer(String cid) {
12643            return new OriginInfo(null, cid, true, false);
12644        }
12645
12646        private OriginInfo(File file, String cid, boolean staged, boolean existing) {
12647            this.file = file;
12648            this.cid = cid;
12649            this.staged = staged;
12650            this.existing = existing;
12651
12652            if (cid != null) {
12653                resolvedPath = PackageHelper.getSdDir(cid);
12654                resolvedFile = new File(resolvedPath);
12655            } else if (file != null) {
12656                resolvedPath = file.getAbsolutePath();
12657                resolvedFile = file;
12658            } else {
12659                resolvedPath = null;
12660                resolvedFile = null;
12661            }
12662        }
12663    }
12664
12665    static class MoveInfo {
12666        final int moveId;
12667        final String fromUuid;
12668        final String toUuid;
12669        final String packageName;
12670        final String dataAppName;
12671        final int appId;
12672        final String seinfo;
12673        final int targetSdkVersion;
12674
12675        public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName,
12676                String dataAppName, int appId, String seinfo, int targetSdkVersion) {
12677            this.moveId = moveId;
12678            this.fromUuid = fromUuid;
12679            this.toUuid = toUuid;
12680            this.packageName = packageName;
12681            this.dataAppName = dataAppName;
12682            this.appId = appId;
12683            this.seinfo = seinfo;
12684            this.targetSdkVersion = targetSdkVersion;
12685        }
12686    }
12687
12688    static class VerificationInfo {
12689        /** A constant used to indicate that a uid value is not present. */
12690        public static final int NO_UID = -1;
12691
12692        /** URI referencing where the package was downloaded from. */
12693        final Uri originatingUri;
12694
12695        /** HTTP referrer URI associated with the originatingURI. */
12696        final Uri referrer;
12697
12698        /** UID of the application that the install request originated from. */
12699        final int originatingUid;
12700
12701        /** UID of application requesting the install */
12702        final int installerUid;
12703
12704        VerificationInfo(Uri originatingUri, Uri referrer, int originatingUid, int installerUid) {
12705            this.originatingUri = originatingUri;
12706            this.referrer = referrer;
12707            this.originatingUid = originatingUid;
12708            this.installerUid = installerUid;
12709        }
12710    }
12711
12712    class InstallParams extends HandlerParams {
12713        final OriginInfo origin;
12714        final MoveInfo move;
12715        final IPackageInstallObserver2 observer;
12716        int installFlags;
12717        final String installerPackageName;
12718        final String volumeUuid;
12719        private InstallArgs mArgs;
12720        private int mRet;
12721        final String packageAbiOverride;
12722        final String[] grantedRuntimePermissions;
12723        final VerificationInfo verificationInfo;
12724        final Certificate[][] certificates;
12725
12726        InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
12727                int installFlags, String installerPackageName, String volumeUuid,
12728                VerificationInfo verificationInfo, UserHandle user, String packageAbiOverride,
12729                String[] grantedPermissions, Certificate[][] certificates) {
12730            super(user);
12731            this.origin = origin;
12732            this.move = move;
12733            this.observer = observer;
12734            this.installFlags = installFlags;
12735            this.installerPackageName = installerPackageName;
12736            this.volumeUuid = volumeUuid;
12737            this.verificationInfo = verificationInfo;
12738            this.packageAbiOverride = packageAbiOverride;
12739            this.grantedRuntimePermissions = grantedPermissions;
12740            this.certificates = certificates;
12741        }
12742
12743        @Override
12744        public String toString() {
12745            return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
12746                    + " file=" + origin.file + " cid=" + origin.cid + "}";
12747        }
12748
12749        private int installLocationPolicy(PackageInfoLite pkgLite) {
12750            String packageName = pkgLite.packageName;
12751            int installLocation = pkgLite.installLocation;
12752            boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
12753            // reader
12754            synchronized (mPackages) {
12755                // Currently installed package which the new package is attempting to replace or
12756                // null if no such package is installed.
12757                PackageParser.Package installedPkg = mPackages.get(packageName);
12758                // Package which currently owns the data which the new package will own if installed.
12759                // If an app is unstalled while keeping data (e.g., adb uninstall -k), installedPkg
12760                // will be null whereas dataOwnerPkg will contain information about the package
12761                // which was uninstalled while keeping its data.
12762                PackageParser.Package dataOwnerPkg = installedPkg;
12763                if (dataOwnerPkg  == null) {
12764                    PackageSetting ps = mSettings.mPackages.get(packageName);
12765                    if (ps != null) {
12766                        dataOwnerPkg = ps.pkg;
12767                    }
12768                }
12769
12770                if (dataOwnerPkg != null) {
12771                    // If installed, the package will get access to data left on the device by its
12772                    // predecessor. As a security measure, this is permited only if this is not a
12773                    // version downgrade or if the predecessor package is marked as debuggable and
12774                    // a downgrade is explicitly requested.
12775                    //
12776                    // On debuggable platform builds, downgrades are permitted even for
12777                    // non-debuggable packages to make testing easier. Debuggable platform builds do
12778                    // not offer security guarantees and thus it's OK to disable some security
12779                    // mechanisms to make debugging/testing easier on those builds. However, even on
12780                    // debuggable builds downgrades of packages are permitted only if requested via
12781                    // installFlags. This is because we aim to keep the behavior of debuggable
12782                    // platform builds as close as possible to the behavior of non-debuggable
12783                    // platform builds.
12784                    final boolean downgradeRequested =
12785                            (installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) != 0;
12786                    final boolean packageDebuggable =
12787                                (dataOwnerPkg.applicationInfo.flags
12788                                        & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
12789                    final boolean downgradePermitted =
12790                            (downgradeRequested) && ((Build.IS_DEBUGGABLE) || (packageDebuggable));
12791                    if (!downgradePermitted) {
12792                        try {
12793                            checkDowngrade(dataOwnerPkg, pkgLite);
12794                        } catch (PackageManagerException e) {
12795                            Slog.w(TAG, "Downgrade detected: " + e.getMessage());
12796                            return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
12797                        }
12798                    }
12799                }
12800
12801                if (installedPkg != null) {
12802                    if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
12803                        // Check for updated system application.
12804                        if ((installedPkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
12805                            if (onSd) {
12806                                Slog.w(TAG, "Cannot install update to system app on sdcard");
12807                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
12808                            }
12809                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
12810                        } else {
12811                            if (onSd) {
12812                                // Install flag overrides everything.
12813                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
12814                            }
12815                            // If current upgrade specifies particular preference
12816                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
12817                                // Application explicitly specified internal.
12818                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
12819                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
12820                                // App explictly prefers external. Let policy decide
12821                            } else {
12822                                // Prefer previous location
12823                                if (isExternal(installedPkg)) {
12824                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
12825                                }
12826                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
12827                            }
12828                        }
12829                    } else {
12830                        // Invalid install. Return error code
12831                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
12832                    }
12833                }
12834            }
12835            // All the special cases have been taken care of.
12836            // Return result based on recommended install location.
12837            if (onSd) {
12838                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
12839            }
12840            return pkgLite.recommendedInstallLocation;
12841        }
12842
12843        /*
12844         * Invoke remote method to get package information and install
12845         * location values. Override install location based on default
12846         * policy if needed and then create install arguments based
12847         * on the install location.
12848         */
12849        public void handleStartCopy() throws RemoteException {
12850            int ret = PackageManager.INSTALL_SUCCEEDED;
12851
12852            // If we're already staged, we've firmly committed to an install location
12853            if (origin.staged) {
12854                if (origin.file != null) {
12855                    installFlags |= PackageManager.INSTALL_INTERNAL;
12856                    installFlags &= ~PackageManager.INSTALL_EXTERNAL;
12857                } else if (origin.cid != null) {
12858                    installFlags |= PackageManager.INSTALL_EXTERNAL;
12859                    installFlags &= ~PackageManager.INSTALL_INTERNAL;
12860                } else {
12861                    throw new IllegalStateException("Invalid stage location");
12862                }
12863            }
12864
12865            final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
12866            final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
12867            final boolean ephemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0;
12868            PackageInfoLite pkgLite = null;
12869
12870            if (onInt && onSd) {
12871                // Check if both bits are set.
12872                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
12873                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
12874            } else if (onSd && ephemeral) {
12875                Slog.w(TAG,  "Conflicting flags specified for installing ephemeral on external");
12876                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
12877            } else {
12878                pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
12879                        packageAbiOverride);
12880
12881                if (DEBUG_EPHEMERAL && ephemeral) {
12882                    Slog.v(TAG, "pkgLite for install: " + pkgLite);
12883                }
12884
12885                /*
12886                 * If we have too little free space, try to free cache
12887                 * before giving up.
12888                 */
12889                if (!origin.staged && pkgLite.recommendedInstallLocation
12890                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
12891                    // TODO: focus freeing disk space on the target device
12892                    final StorageManager storage = StorageManager.from(mContext);
12893                    final long lowThreshold = storage.getStorageLowBytes(
12894                            Environment.getDataDirectory());
12895
12896                    final long sizeBytes = mContainerService.calculateInstalledSize(
12897                            origin.resolvedPath, isForwardLocked(), packageAbiOverride);
12898
12899                    try {
12900                        mInstaller.freeCache(null, sizeBytes + lowThreshold);
12901                        pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
12902                                installFlags, packageAbiOverride);
12903                    } catch (InstallerException e) {
12904                        Slog.w(TAG, "Failed to free cache", e);
12905                    }
12906
12907                    /*
12908                     * The cache free must have deleted the file we
12909                     * downloaded to install.
12910                     *
12911                     * TODO: fix the "freeCache" call to not delete
12912                     *       the file we care about.
12913                     */
12914                    if (pkgLite.recommendedInstallLocation
12915                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
12916                        pkgLite.recommendedInstallLocation
12917                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
12918                    }
12919                }
12920            }
12921
12922            if (ret == PackageManager.INSTALL_SUCCEEDED) {
12923                int loc = pkgLite.recommendedInstallLocation;
12924                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
12925                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
12926                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
12927                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
12928                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
12929                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
12930                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
12931                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
12932                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
12933                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
12934                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
12935                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
12936                } else {
12937                    // Override with defaults if needed.
12938                    loc = installLocationPolicy(pkgLite);
12939                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
12940                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
12941                    } else if (!onSd && !onInt) {
12942                        // Override install location with flags
12943                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
12944                            // Set the flag to install on external media.
12945                            installFlags |= PackageManager.INSTALL_EXTERNAL;
12946                            installFlags &= ~PackageManager.INSTALL_INTERNAL;
12947                        } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) {
12948                            if (DEBUG_EPHEMERAL) {
12949                                Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag");
12950                            }
12951                            installFlags |= PackageManager.INSTALL_EPHEMERAL;
12952                            installFlags &= ~(PackageManager.INSTALL_EXTERNAL
12953                                    |PackageManager.INSTALL_INTERNAL);
12954                        } else {
12955                            // Make sure the flag for installing on external
12956                            // media is unset
12957                            installFlags |= PackageManager.INSTALL_INTERNAL;
12958                            installFlags &= ~PackageManager.INSTALL_EXTERNAL;
12959                        }
12960                    }
12961                }
12962            }
12963
12964            final InstallArgs args = createInstallArgs(this);
12965            mArgs = args;
12966
12967            if (ret == PackageManager.INSTALL_SUCCEEDED) {
12968                // TODO: http://b/22976637
12969                // Apps installed for "all" users use the device owner to verify the app
12970                UserHandle verifierUser = getUser();
12971                if (verifierUser == UserHandle.ALL) {
12972                    verifierUser = UserHandle.SYSTEM;
12973                }
12974
12975                /*
12976                 * Determine if we have any installed package verifiers. If we
12977                 * do, then we'll defer to them to verify the packages.
12978                 */
12979                final int requiredUid = mRequiredVerifierPackage == null ? -1
12980                        : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
12981                                verifierUser.getIdentifier());
12982                if (!origin.existing && requiredUid != -1
12983                        && isVerificationEnabled(verifierUser.getIdentifier(), installFlags)) {
12984                    final Intent verification = new Intent(
12985                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
12986                    verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
12987                    verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
12988                            PACKAGE_MIME_TYPE);
12989                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
12990
12991                    // Query all live verifiers based on current user state
12992                    final List<ResolveInfo> receivers = queryIntentReceiversInternal(verification,
12993                            PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier());
12994
12995                    if (DEBUG_VERIFY) {
12996                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
12997                                + verification.toString() + " with " + pkgLite.verifiers.length
12998                                + " optional verifiers");
12999                    }
13000
13001                    final int verificationId = mPendingVerificationToken++;
13002
13003                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
13004
13005                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
13006                            installerPackageName);
13007
13008                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
13009                            installFlags);
13010
13011                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
13012                            pkgLite.packageName);
13013
13014                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
13015                            pkgLite.versionCode);
13016
13017                    if (verificationInfo != null) {
13018                        if (verificationInfo.originatingUri != null) {
13019                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
13020                                    verificationInfo.originatingUri);
13021                        }
13022                        if (verificationInfo.referrer != null) {
13023                            verification.putExtra(Intent.EXTRA_REFERRER,
13024                                    verificationInfo.referrer);
13025                        }
13026                        if (verificationInfo.originatingUid >= 0) {
13027                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
13028                                    verificationInfo.originatingUid);
13029                        }
13030                        if (verificationInfo.installerUid >= 0) {
13031                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
13032                                    verificationInfo.installerUid);
13033                        }
13034                    }
13035
13036                    final PackageVerificationState verificationState = new PackageVerificationState(
13037                            requiredUid, args);
13038
13039                    mPendingVerification.append(verificationId, verificationState);
13040
13041                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
13042                            receivers, verificationState);
13043
13044                    /*
13045                     * If any sufficient verifiers were listed in the package
13046                     * manifest, attempt to ask them.
13047                     */
13048                    if (sufficientVerifiers != null) {
13049                        final int N = sufficientVerifiers.size();
13050                        if (N == 0) {
13051                            Slog.i(TAG, "Additional verifiers required, but none installed.");
13052                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
13053                        } else {
13054                            for (int i = 0; i < N; i++) {
13055                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
13056
13057                                final Intent sufficientIntent = new Intent(verification);
13058                                sufficientIntent.setComponent(verifierComponent);
13059                                mContext.sendBroadcastAsUser(sufficientIntent, verifierUser);
13060                            }
13061                        }
13062                    }
13063
13064                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
13065                            mRequiredVerifierPackage, receivers);
13066                    if (ret == PackageManager.INSTALL_SUCCEEDED
13067                            && mRequiredVerifierPackage != null) {
13068                        Trace.asyncTraceBegin(
13069                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
13070                        /*
13071                         * Send the intent to the required verification agent,
13072                         * but only start the verification timeout after the
13073                         * target BroadcastReceivers have run.
13074                         */
13075                        verification.setComponent(requiredVerifierComponent);
13076                        mContext.sendOrderedBroadcastAsUser(verification, verifierUser,
13077                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
13078                                new BroadcastReceiver() {
13079                                    @Override
13080                                    public void onReceive(Context context, Intent intent) {
13081                                        final Message msg = mHandler
13082                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
13083                                        msg.arg1 = verificationId;
13084                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
13085                                    }
13086                                }, null, 0, null, null);
13087
13088                        /*
13089                         * We don't want the copy to proceed until verification
13090                         * succeeds, so null out this field.
13091                         */
13092                        mArgs = null;
13093                    }
13094                } else {
13095                    /*
13096                     * No package verification is enabled, so immediately start
13097                     * the remote call to initiate copy using temporary file.
13098                     */
13099                    ret = args.copyApk(mContainerService, true);
13100                }
13101            }
13102
13103            mRet = ret;
13104        }
13105
13106        @Override
13107        void handleReturnCode() {
13108            // If mArgs is null, then MCS couldn't be reached. When it
13109            // reconnects, it will try again to install. At that point, this
13110            // will succeed.
13111            if (mArgs != null) {
13112                processPendingInstall(mArgs, mRet);
13113            }
13114        }
13115
13116        @Override
13117        void handleServiceError() {
13118            mArgs = createInstallArgs(this);
13119            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
13120        }
13121
13122        public boolean isForwardLocked() {
13123            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
13124        }
13125    }
13126
13127    /**
13128     * Used during creation of InstallArgs
13129     *
13130     * @param installFlags package installation flags
13131     * @return true if should be installed on external storage
13132     */
13133    private static boolean installOnExternalAsec(int installFlags) {
13134        if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) {
13135            return false;
13136        }
13137        if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
13138            return true;
13139        }
13140        return false;
13141    }
13142
13143    /**
13144     * Used during creation of InstallArgs
13145     *
13146     * @param installFlags package installation flags
13147     * @return true if should be installed as forward locked
13148     */
13149    private static boolean installForwardLocked(int installFlags) {
13150        return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
13151    }
13152
13153    private InstallArgs createInstallArgs(InstallParams params) {
13154        if (params.move != null) {
13155            return new MoveInstallArgs(params);
13156        } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) {
13157            return new AsecInstallArgs(params);
13158        } else {
13159            return new FileInstallArgs(params);
13160        }
13161    }
13162
13163    /**
13164     * Create args that describe an existing installed package. Typically used
13165     * when cleaning up old installs, or used as a move source.
13166     */
13167    private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
13168            String resourcePath, String[] instructionSets) {
13169        final boolean isInAsec;
13170        if (installOnExternalAsec(installFlags)) {
13171            /* Apps on SD card are always in ASEC containers. */
13172            isInAsec = true;
13173        } else if (installForwardLocked(installFlags)
13174                && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) {
13175            /*
13176             * Forward-locked apps are only in ASEC containers if they're the
13177             * new style
13178             */
13179            isInAsec = true;
13180        } else {
13181            isInAsec = false;
13182        }
13183
13184        if (isInAsec) {
13185            return new AsecInstallArgs(codePath, instructionSets,
13186                    installOnExternalAsec(installFlags), installForwardLocked(installFlags));
13187        } else {
13188            return new FileInstallArgs(codePath, resourcePath, instructionSets);
13189        }
13190    }
13191
13192    static abstract class InstallArgs {
13193        /** @see InstallParams#origin */
13194        final OriginInfo origin;
13195        /** @see InstallParams#move */
13196        final MoveInfo move;
13197
13198        final IPackageInstallObserver2 observer;
13199        // Always refers to PackageManager flags only
13200        final int installFlags;
13201        final String installerPackageName;
13202        final String volumeUuid;
13203        final UserHandle user;
13204        final String abiOverride;
13205        final String[] installGrantPermissions;
13206        /** If non-null, drop an async trace when the install completes */
13207        final String traceMethod;
13208        final int traceCookie;
13209        final Certificate[][] certificates;
13210
13211        // The list of instruction sets supported by this app. This is currently
13212        // only used during the rmdex() phase to clean up resources. We can get rid of this
13213        // if we move dex files under the common app path.
13214        /* nullable */ String[] instructionSets;
13215
13216        InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
13217                int installFlags, String installerPackageName, String volumeUuid,
13218                UserHandle user, String[] instructionSets,
13219                String abiOverride, String[] installGrantPermissions,
13220                String traceMethod, int traceCookie, Certificate[][] certificates) {
13221            this.origin = origin;
13222            this.move = move;
13223            this.installFlags = installFlags;
13224            this.observer = observer;
13225            this.installerPackageName = installerPackageName;
13226            this.volumeUuid = volumeUuid;
13227            this.user = user;
13228            this.instructionSets = instructionSets;
13229            this.abiOverride = abiOverride;
13230            this.installGrantPermissions = installGrantPermissions;
13231            this.traceMethod = traceMethod;
13232            this.traceCookie = traceCookie;
13233            this.certificates = certificates;
13234        }
13235
13236        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
13237        abstract int doPreInstall(int status);
13238
13239        /**
13240         * Rename package into final resting place. All paths on the given
13241         * scanned package should be updated to reflect the rename.
13242         */
13243        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
13244        abstract int doPostInstall(int status, int uid);
13245
13246        /** @see PackageSettingBase#codePathString */
13247        abstract String getCodePath();
13248        /** @see PackageSettingBase#resourcePathString */
13249        abstract String getResourcePath();
13250
13251        // Need installer lock especially for dex file removal.
13252        abstract void cleanUpResourcesLI();
13253        abstract boolean doPostDeleteLI(boolean delete);
13254
13255        /**
13256         * Called before the source arguments are copied. This is used mostly
13257         * for MoveParams when it needs to read the source file to put it in the
13258         * destination.
13259         */
13260        int doPreCopy() {
13261            return PackageManager.INSTALL_SUCCEEDED;
13262        }
13263
13264        /**
13265         * Called after the source arguments are copied. This is used mostly for
13266         * MoveParams when it needs to read the source file to put it in the
13267         * destination.
13268         */
13269        int doPostCopy(int uid) {
13270            return PackageManager.INSTALL_SUCCEEDED;
13271        }
13272
13273        protected boolean isFwdLocked() {
13274            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
13275        }
13276
13277        protected boolean isExternalAsec() {
13278            return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
13279        }
13280
13281        protected boolean isEphemeral() {
13282            return (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0;
13283        }
13284
13285        UserHandle getUser() {
13286            return user;
13287        }
13288    }
13289
13290    private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) {
13291        if (!allCodePaths.isEmpty()) {
13292            if (instructionSets == null) {
13293                throw new IllegalStateException("instructionSet == null");
13294            }
13295            String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
13296            for (String codePath : allCodePaths) {
13297                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
13298                    try {
13299                        mInstaller.rmdex(codePath, dexCodeInstructionSet);
13300                    } catch (InstallerException ignored) {
13301                    }
13302                }
13303            }
13304        }
13305    }
13306
13307    /**
13308     * Logic to handle installation of non-ASEC applications, including copying
13309     * and renaming logic.
13310     */
13311    class FileInstallArgs extends InstallArgs {
13312        private File codeFile;
13313        private File resourceFile;
13314
13315        // Example topology:
13316        // /data/app/com.example/base.apk
13317        // /data/app/com.example/split_foo.apk
13318        // /data/app/com.example/lib/arm/libfoo.so
13319        // /data/app/com.example/lib/arm64/libfoo.so
13320        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
13321
13322        /** New install */
13323        FileInstallArgs(InstallParams params) {
13324            super(params.origin, params.move, params.observer, params.installFlags,
13325                    params.installerPackageName, params.volumeUuid,
13326                    params.getUser(), null /*instructionSets*/, params.packageAbiOverride,
13327                    params.grantedRuntimePermissions,
13328                    params.traceMethod, params.traceCookie, params.certificates);
13329            if (isFwdLocked()) {
13330                throw new IllegalArgumentException("Forward locking only supported in ASEC");
13331            }
13332        }
13333
13334        /** Existing install */
13335        FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) {
13336            super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets,
13337                    null, null, null, 0, null /*certificates*/);
13338            this.codeFile = (codePath != null) ? new File(codePath) : null;
13339            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
13340        }
13341
13342        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
13343            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk");
13344            try {
13345                return doCopyApk(imcs, temp);
13346            } finally {
13347                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
13348            }
13349        }
13350
13351        private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
13352            if (origin.staged) {
13353                if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy");
13354                codeFile = origin.file;
13355                resourceFile = origin.file;
13356                return PackageManager.INSTALL_SUCCEEDED;
13357            }
13358
13359            try {
13360                final boolean isEphemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0;
13361                final File tempDir =
13362                        mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral);
13363                codeFile = tempDir;
13364                resourceFile = tempDir;
13365            } catch (IOException e) {
13366                Slog.w(TAG, "Failed to create copy file: " + e);
13367                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
13368            }
13369
13370            final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
13371                @Override
13372                public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
13373                    if (!FileUtils.isValidExtFilename(name)) {
13374                        throw new IllegalArgumentException("Invalid filename: " + name);
13375                    }
13376                    try {
13377                        final File file = new File(codeFile, name);
13378                        final FileDescriptor fd = Os.open(file.getAbsolutePath(),
13379                                O_RDWR | O_CREAT, 0644);
13380                        Os.chmod(file.getAbsolutePath(), 0644);
13381                        return new ParcelFileDescriptor(fd);
13382                    } catch (ErrnoException e) {
13383                        throw new RemoteException("Failed to open: " + e.getMessage());
13384                    }
13385                }
13386            };
13387
13388            int ret = PackageManager.INSTALL_SUCCEEDED;
13389            ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
13390            if (ret != PackageManager.INSTALL_SUCCEEDED) {
13391                Slog.e(TAG, "Failed to copy package");
13392                return ret;
13393            }
13394
13395            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
13396            NativeLibraryHelper.Handle handle = null;
13397            try {
13398                handle = NativeLibraryHelper.Handle.create(codeFile);
13399                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
13400                        abiOverride);
13401            } catch (IOException e) {
13402                Slog.e(TAG, "Copying native libraries failed", e);
13403                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
13404            } finally {
13405                IoUtils.closeQuietly(handle);
13406            }
13407
13408            return ret;
13409        }
13410
13411        int doPreInstall(int status) {
13412            if (status != PackageManager.INSTALL_SUCCEEDED) {
13413                cleanUp();
13414            }
13415            return status;
13416        }
13417
13418        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
13419            if (status != PackageManager.INSTALL_SUCCEEDED) {
13420                cleanUp();
13421                return false;
13422            }
13423
13424            final File targetDir = codeFile.getParentFile();
13425            final File beforeCodeFile = codeFile;
13426            final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName);
13427
13428            if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
13429            try {
13430                Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
13431            } catch (ErrnoException e) {
13432                Slog.w(TAG, "Failed to rename", e);
13433                return false;
13434            }
13435
13436            if (!SELinux.restoreconRecursive(afterCodeFile)) {
13437                Slog.w(TAG, "Failed to restorecon");
13438                return false;
13439            }
13440
13441            // Reflect the rename internally
13442            codeFile = afterCodeFile;
13443            resourceFile = afterCodeFile;
13444
13445            // Reflect the rename in scanned details
13446            pkg.setCodePath(afterCodeFile.getAbsolutePath());
13447            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
13448                    afterCodeFile, pkg.baseCodePath));
13449            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
13450                    afterCodeFile, pkg.splitCodePaths));
13451
13452            // Reflect the rename in app info
13453            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
13454            pkg.setApplicationInfoCodePath(pkg.codePath);
13455            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
13456            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
13457            pkg.setApplicationInfoResourcePath(pkg.codePath);
13458            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
13459            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
13460
13461            return true;
13462        }
13463
13464        int doPostInstall(int status, int uid) {
13465            if (status != PackageManager.INSTALL_SUCCEEDED) {
13466                cleanUp();
13467            }
13468            return status;
13469        }
13470
13471        @Override
13472        String getCodePath() {
13473            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
13474        }
13475
13476        @Override
13477        String getResourcePath() {
13478            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
13479        }
13480
13481        private boolean cleanUp() {
13482            if (codeFile == null || !codeFile.exists()) {
13483                return false;
13484            }
13485
13486            removeCodePathLI(codeFile);
13487
13488            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
13489                resourceFile.delete();
13490            }
13491
13492            return true;
13493        }
13494
13495        void cleanUpResourcesLI() {
13496            // Try enumerating all code paths before deleting
13497            List<String> allCodePaths = Collections.EMPTY_LIST;
13498            if (codeFile != null && codeFile.exists()) {
13499                try {
13500                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
13501                    allCodePaths = pkg.getAllCodePaths();
13502                } catch (PackageParserException e) {
13503                    // Ignored; we tried our best
13504                }
13505            }
13506
13507            cleanUp();
13508            removeDexFiles(allCodePaths, instructionSets);
13509        }
13510
13511        boolean doPostDeleteLI(boolean delete) {
13512            // XXX err, shouldn't we respect the delete flag?
13513            cleanUpResourcesLI();
13514            return true;
13515        }
13516    }
13517
13518    private boolean isAsecExternal(String cid) {
13519        final String asecPath = PackageHelper.getSdFilesystem(cid);
13520        return !asecPath.startsWith(mAsecInternalPath);
13521    }
13522
13523    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
13524            PackageManagerException {
13525        if (copyRet < 0) {
13526            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
13527                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
13528                throw new PackageManagerException(copyRet, message);
13529            }
13530        }
13531    }
13532
13533    /**
13534     * Extract the MountService "container ID" from the full code path of an
13535     * .apk.
13536     */
13537    static String cidFromCodePath(String fullCodePath) {
13538        int eidx = fullCodePath.lastIndexOf("/");
13539        String subStr1 = fullCodePath.substring(0, eidx);
13540        int sidx = subStr1.lastIndexOf("/");
13541        return subStr1.substring(sidx+1, eidx);
13542    }
13543
13544    /**
13545     * Logic to handle installation of ASEC applications, including copying and
13546     * renaming logic.
13547     */
13548    class AsecInstallArgs extends InstallArgs {
13549        static final String RES_FILE_NAME = "pkg.apk";
13550        static final String PUBLIC_RES_FILE_NAME = "res.zip";
13551
13552        String cid;
13553        String packagePath;
13554        String resourcePath;
13555
13556        /** New install */
13557        AsecInstallArgs(InstallParams params) {
13558            super(params.origin, params.move, params.observer, params.installFlags,
13559                    params.installerPackageName, params.volumeUuid,
13560                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
13561                    params.grantedRuntimePermissions,
13562                    params.traceMethod, params.traceCookie, params.certificates);
13563        }
13564
13565        /** Existing install */
13566        AsecInstallArgs(String fullCodePath, String[] instructionSets,
13567                        boolean isExternal, boolean isForwardLocked) {
13568            super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0)
13569              | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
13570                    instructionSets, null, null, null, 0, null /*certificates*/);
13571            // Hackily pretend we're still looking at a full code path
13572            if (!fullCodePath.endsWith(RES_FILE_NAME)) {
13573                fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath();
13574            }
13575
13576            // Extract cid from fullCodePath
13577            int eidx = fullCodePath.lastIndexOf("/");
13578            String subStr1 = fullCodePath.substring(0, eidx);
13579            int sidx = subStr1.lastIndexOf("/");
13580            cid = subStr1.substring(sidx+1, eidx);
13581            setMountPath(subStr1);
13582        }
13583
13584        AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) {
13585            super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0)
13586              | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
13587                    instructionSets, null, null, null, 0, null /*certificates*/);
13588            this.cid = cid;
13589            setMountPath(PackageHelper.getSdDir(cid));
13590        }
13591
13592        void createCopyFile() {
13593            cid = mInstallerService.allocateExternalStageCidLegacy();
13594        }
13595
13596        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
13597            if (origin.staged && origin.cid != null) {
13598                if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy");
13599                cid = origin.cid;
13600                setMountPath(PackageHelper.getSdDir(cid));
13601                return PackageManager.INSTALL_SUCCEEDED;
13602            }
13603
13604            if (temp) {
13605                createCopyFile();
13606            } else {
13607                /*
13608                 * Pre-emptively destroy the container since it's destroyed if
13609                 * copying fails due to it existing anyway.
13610                 */
13611                PackageHelper.destroySdDir(cid);
13612            }
13613
13614            final String newMountPath = imcs.copyPackageToContainer(
13615                    origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(),
13616                    isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */));
13617
13618            if (newMountPath != null) {
13619                setMountPath(newMountPath);
13620                return PackageManager.INSTALL_SUCCEEDED;
13621            } else {
13622                return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
13623            }
13624        }
13625
13626        @Override
13627        String getCodePath() {
13628            return packagePath;
13629        }
13630
13631        @Override
13632        String getResourcePath() {
13633            return resourcePath;
13634        }
13635
13636        int doPreInstall(int status) {
13637            if (status != PackageManager.INSTALL_SUCCEEDED) {
13638                // Destroy container
13639                PackageHelper.destroySdDir(cid);
13640            } else {
13641                boolean mounted = PackageHelper.isContainerMounted(cid);
13642                if (!mounted) {
13643                    String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(),
13644                            Process.SYSTEM_UID);
13645                    if (newMountPath != null) {
13646                        setMountPath(newMountPath);
13647                    } else {
13648                        return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
13649                    }
13650                }
13651            }
13652            return status;
13653        }
13654
13655        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
13656            String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME);
13657            String newMountPath = null;
13658            if (PackageHelper.isContainerMounted(cid)) {
13659                // Unmount the container
13660                if (!PackageHelper.unMountSdDir(cid)) {
13661                    Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
13662                    return false;
13663                }
13664            }
13665            if (!PackageHelper.renameSdDir(cid, newCacheId)) {
13666                Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
13667                        " which might be stale. Will try to clean up.");
13668                // Clean up the stale container and proceed to recreate.
13669                if (!PackageHelper.destroySdDir(newCacheId)) {
13670                    Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
13671                    return false;
13672                }
13673                // Successfully cleaned up stale container. Try to rename again.
13674                if (!PackageHelper.renameSdDir(cid, newCacheId)) {
13675                    Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
13676                            + " inspite of cleaning it up.");
13677                    return false;
13678                }
13679            }
13680            if (!PackageHelper.isContainerMounted(newCacheId)) {
13681                Slog.w(TAG, "Mounting container " + newCacheId);
13682                newMountPath = PackageHelper.mountSdDir(newCacheId,
13683                        getEncryptKey(), Process.SYSTEM_UID);
13684            } else {
13685                newMountPath = PackageHelper.getSdDir(newCacheId);
13686            }
13687            if (newMountPath == null) {
13688                Slog.w(TAG, "Failed to get cache path for  " + newCacheId);
13689                return false;
13690            }
13691            Log.i(TAG, "Succesfully renamed " + cid +
13692                    " to " + newCacheId +
13693                    " at new path: " + newMountPath);
13694            cid = newCacheId;
13695
13696            final File beforeCodeFile = new File(packagePath);
13697            setMountPath(newMountPath);
13698            final File afterCodeFile = new File(packagePath);
13699
13700            // Reflect the rename in scanned details
13701            pkg.setCodePath(afterCodeFile.getAbsolutePath());
13702            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
13703                    afterCodeFile, pkg.baseCodePath));
13704            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
13705                    afterCodeFile, pkg.splitCodePaths));
13706
13707            // Reflect the rename in app info
13708            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
13709            pkg.setApplicationInfoCodePath(pkg.codePath);
13710            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
13711            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
13712            pkg.setApplicationInfoResourcePath(pkg.codePath);
13713            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
13714            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
13715
13716            return true;
13717        }
13718
13719        private void setMountPath(String mountPath) {
13720            final File mountFile = new File(mountPath);
13721
13722            final File monolithicFile = new File(mountFile, RES_FILE_NAME);
13723            if (monolithicFile.exists()) {
13724                packagePath = monolithicFile.getAbsolutePath();
13725                if (isFwdLocked()) {
13726                    resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath();
13727                } else {
13728                    resourcePath = packagePath;
13729                }
13730            } else {
13731                packagePath = mountFile.getAbsolutePath();
13732                resourcePath = packagePath;
13733            }
13734        }
13735
13736        int doPostInstall(int status, int uid) {
13737            if (status != PackageManager.INSTALL_SUCCEEDED) {
13738                cleanUp();
13739            } else {
13740                final int groupOwner;
13741                final String protectedFile;
13742                if (isFwdLocked()) {
13743                    groupOwner = UserHandle.getSharedAppGid(uid);
13744                    protectedFile = RES_FILE_NAME;
13745                } else {
13746                    groupOwner = -1;
13747                    protectedFile = null;
13748                }
13749
13750                if (uid < Process.FIRST_APPLICATION_UID
13751                        || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) {
13752                    Slog.e(TAG, "Failed to finalize " + cid);
13753                    PackageHelper.destroySdDir(cid);
13754                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
13755                }
13756
13757                boolean mounted = PackageHelper.isContainerMounted(cid);
13758                if (!mounted) {
13759                    PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid());
13760                }
13761            }
13762            return status;
13763        }
13764
13765        private void cleanUp() {
13766            if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp");
13767
13768            // Destroy secure container
13769            PackageHelper.destroySdDir(cid);
13770        }
13771
13772        private List<String> getAllCodePaths() {
13773            final File codeFile = new File(getCodePath());
13774            if (codeFile != null && codeFile.exists()) {
13775                try {
13776                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
13777                    return pkg.getAllCodePaths();
13778                } catch (PackageParserException e) {
13779                    // Ignored; we tried our best
13780                }
13781            }
13782            return Collections.EMPTY_LIST;
13783        }
13784
13785        void cleanUpResourcesLI() {
13786            // Enumerate all code paths before deleting
13787            cleanUpResourcesLI(getAllCodePaths());
13788        }
13789
13790        private void cleanUpResourcesLI(List<String> allCodePaths) {
13791            cleanUp();
13792            removeDexFiles(allCodePaths, instructionSets);
13793        }
13794
13795        String getPackageName() {
13796            return getAsecPackageName(cid);
13797        }
13798
13799        boolean doPostDeleteLI(boolean delete) {
13800            if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete);
13801            final List<String> allCodePaths = getAllCodePaths();
13802            boolean mounted = PackageHelper.isContainerMounted(cid);
13803            if (mounted) {
13804                // Unmount first
13805                if (PackageHelper.unMountSdDir(cid)) {
13806                    mounted = false;
13807                }
13808            }
13809            if (!mounted && delete) {
13810                cleanUpResourcesLI(allCodePaths);
13811            }
13812            return !mounted;
13813        }
13814
13815        @Override
13816        int doPreCopy() {
13817            if (isFwdLocked()) {
13818                if (!PackageHelper.fixSdPermissions(cid, getPackageUid(DEFAULT_CONTAINER_PACKAGE,
13819                        MATCH_SYSTEM_ONLY, UserHandle.USER_SYSTEM), RES_FILE_NAME)) {
13820                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
13821                }
13822            }
13823
13824            return PackageManager.INSTALL_SUCCEEDED;
13825        }
13826
13827        @Override
13828        int doPostCopy(int uid) {
13829            if (isFwdLocked()) {
13830                if (uid < Process.FIRST_APPLICATION_UID
13831                        || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid),
13832                                RES_FILE_NAME)) {
13833                    Slog.e(TAG, "Failed to finalize " + cid);
13834                    PackageHelper.destroySdDir(cid);
13835                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
13836                }
13837            }
13838
13839            return PackageManager.INSTALL_SUCCEEDED;
13840        }
13841    }
13842
13843    /**
13844     * Logic to handle movement of existing installed applications.
13845     */
13846    class MoveInstallArgs extends InstallArgs {
13847        private File codeFile;
13848        private File resourceFile;
13849
13850        /** New install */
13851        MoveInstallArgs(InstallParams params) {
13852            super(params.origin, params.move, params.observer, params.installFlags,
13853                    params.installerPackageName, params.volumeUuid,
13854                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
13855                    params.grantedRuntimePermissions,
13856                    params.traceMethod, params.traceCookie, params.certificates);
13857        }
13858
13859        int copyApk(IMediaContainerService imcs, boolean temp) {
13860            if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from "
13861                    + move.fromUuid + " to " + move.toUuid);
13862            synchronized (mInstaller) {
13863                try {
13864                    mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName,
13865                            move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion);
13866                } catch (InstallerException e) {
13867                    Slog.w(TAG, "Failed to move app", e);
13868                    return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
13869                }
13870            }
13871
13872            codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName);
13873            resourceFile = codeFile;
13874            if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile);
13875
13876            return PackageManager.INSTALL_SUCCEEDED;
13877        }
13878
13879        int doPreInstall(int status) {
13880            if (status != PackageManager.INSTALL_SUCCEEDED) {
13881                cleanUp(move.toUuid);
13882            }
13883            return status;
13884        }
13885
13886        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
13887            if (status != PackageManager.INSTALL_SUCCEEDED) {
13888                cleanUp(move.toUuid);
13889                return false;
13890            }
13891
13892            // Reflect the move in app info
13893            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
13894            pkg.setApplicationInfoCodePath(pkg.codePath);
13895            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
13896            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
13897            pkg.setApplicationInfoResourcePath(pkg.codePath);
13898            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
13899            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
13900
13901            return true;
13902        }
13903
13904        int doPostInstall(int status, int uid) {
13905            if (status == PackageManager.INSTALL_SUCCEEDED) {
13906                cleanUp(move.fromUuid);
13907            } else {
13908                cleanUp(move.toUuid);
13909            }
13910            return status;
13911        }
13912
13913        @Override
13914        String getCodePath() {
13915            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
13916        }
13917
13918        @Override
13919        String getResourcePath() {
13920            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
13921        }
13922
13923        private boolean cleanUp(String volumeUuid) {
13924            final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid),
13925                    move.dataAppName);
13926            Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid);
13927            final int[] userIds = sUserManager.getUserIds();
13928            synchronized (mInstallLock) {
13929                // Clean up both app data and code
13930                // All package moves are frozen until finished
13931                for (int userId : userIds) {
13932                    try {
13933                        mInstaller.destroyAppData(volumeUuid, move.packageName, userId,
13934                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 0);
13935                    } catch (InstallerException e) {
13936                        Slog.w(TAG, String.valueOf(e));
13937                    }
13938                }
13939                removeCodePathLI(codeFile);
13940            }
13941            return true;
13942        }
13943
13944        void cleanUpResourcesLI() {
13945            throw new UnsupportedOperationException();
13946        }
13947
13948        boolean doPostDeleteLI(boolean delete) {
13949            throw new UnsupportedOperationException();
13950        }
13951    }
13952
13953    static String getAsecPackageName(String packageCid) {
13954        int idx = packageCid.lastIndexOf("-");
13955        if (idx == -1) {
13956            return packageCid;
13957        }
13958        return packageCid.substring(0, idx);
13959    }
13960
13961    // Utility method used to create code paths based on package name and available index.
13962    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
13963        String idxStr = "";
13964        int idx = 1;
13965        // Fall back to default value of idx=1 if prefix is not
13966        // part of oldCodePath
13967        if (oldCodePath != null) {
13968            String subStr = oldCodePath;
13969            // Drop the suffix right away
13970            if (suffix != null && subStr.endsWith(suffix)) {
13971                subStr = subStr.substring(0, subStr.length() - suffix.length());
13972            }
13973            // If oldCodePath already contains prefix find out the
13974            // ending index to either increment or decrement.
13975            int sidx = subStr.lastIndexOf(prefix);
13976            if (sidx != -1) {
13977                subStr = subStr.substring(sidx + prefix.length());
13978                if (subStr != null) {
13979                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
13980                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
13981                    }
13982                    try {
13983                        idx = Integer.parseInt(subStr);
13984                        if (idx <= 1) {
13985                            idx++;
13986                        } else {
13987                            idx--;
13988                        }
13989                    } catch(NumberFormatException e) {
13990                    }
13991                }
13992            }
13993        }
13994        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
13995        return prefix + idxStr;
13996    }
13997
13998    private File getNextCodePath(File targetDir, String packageName) {
13999        int suffix = 1;
14000        File result;
14001        do {
14002            result = new File(targetDir, packageName + "-" + suffix);
14003            suffix++;
14004        } while (result.exists());
14005        return result;
14006    }
14007
14008    // Utility method that returns the relative package path with respect
14009    // to the installation directory. Like say for /data/data/com.test-1.apk
14010    // string com.test-1 is returned.
14011    static String deriveCodePathName(String codePath) {
14012        if (codePath == null) {
14013            return null;
14014        }
14015        final File codeFile = new File(codePath);
14016        final String name = codeFile.getName();
14017        if (codeFile.isDirectory()) {
14018            return name;
14019        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
14020            final int lastDot = name.lastIndexOf('.');
14021            return name.substring(0, lastDot);
14022        } else {
14023            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
14024            return null;
14025        }
14026    }
14027
14028    static class PackageInstalledInfo {
14029        String name;
14030        int uid;
14031        // The set of users that originally had this package installed.
14032        int[] origUsers;
14033        // The set of users that now have this package installed.
14034        int[] newUsers;
14035        PackageParser.Package pkg;
14036        int returnCode;
14037        String returnMsg;
14038        PackageRemovedInfo removedInfo;
14039        ArrayMap<String, PackageInstalledInfo> addedChildPackages;
14040
14041        public void setError(int code, String msg) {
14042            setReturnCode(code);
14043            setReturnMessage(msg);
14044            Slog.w(TAG, msg);
14045        }
14046
14047        public void setError(String msg, PackageParserException e) {
14048            setReturnCode(e.error);
14049            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
14050            Slog.w(TAG, msg, e);
14051        }
14052
14053        public void setError(String msg, PackageManagerException e) {
14054            returnCode = e.error;
14055            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
14056            Slog.w(TAG, msg, e);
14057        }
14058
14059        public void setReturnCode(int returnCode) {
14060            this.returnCode = returnCode;
14061            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
14062            for (int i = 0; i < childCount; i++) {
14063                addedChildPackages.valueAt(i).returnCode = returnCode;
14064            }
14065        }
14066
14067        private void setReturnMessage(String returnMsg) {
14068            this.returnMsg = returnMsg;
14069            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
14070            for (int i = 0; i < childCount; i++) {
14071                addedChildPackages.valueAt(i).returnMsg = returnMsg;
14072            }
14073        }
14074
14075        // In some error cases we want to convey more info back to the observer
14076        String origPackage;
14077        String origPermission;
14078    }
14079
14080    /*
14081     * Install a non-existing package.
14082     */
14083    private void installNewPackageLIF(PackageParser.Package pkg, final int policyFlags,
14084            int scanFlags, UserHandle user, String installerPackageName, String volumeUuid,
14085            PackageInstalledInfo res) {
14086        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage");
14087
14088        // Remember this for later, in case we need to rollback this install
14089        String pkgName = pkg.packageName;
14090
14091        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
14092
14093        synchronized(mPackages) {
14094            if (mSettings.mRenamedPackages.containsKey(pkgName)) {
14095                // A package with the same name is already installed, though
14096                // it has been renamed to an older name.  The package we
14097                // are trying to install should be installed as an update to
14098                // the existing one, but that has not been requested, so bail.
14099                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
14100                        + " without first uninstalling package running as "
14101                        + mSettings.mRenamedPackages.get(pkgName));
14102                return;
14103            }
14104            if (mPackages.containsKey(pkgName)) {
14105                // Don't allow installation over an existing package with the same name.
14106                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
14107                        + " without first uninstalling.");
14108                return;
14109            }
14110        }
14111
14112        try {
14113            PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags,
14114                    System.currentTimeMillis(), user);
14115
14116            updateSettingsLI(newPackage, installerPackageName, null, res, user);
14117
14118            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
14119                prepareAppDataAfterInstallLIF(newPackage);
14120
14121            } else {
14122                // Remove package from internal structures, but keep around any
14123                // data that might have already existed
14124                deletePackageLIF(pkgName, UserHandle.ALL, false, null,
14125                        PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null);
14126            }
14127        } catch (PackageManagerException e) {
14128            res.setError("Package couldn't be installed in " + pkg.codePath, e);
14129        }
14130
14131        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
14132    }
14133
14134    private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) {
14135        // Can't rotate keys during boot or if sharedUser.
14136        if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null
14137                || !oldPs.keySetData.isUsingUpgradeKeySets()) {
14138            return false;
14139        }
14140        // app is using upgradeKeySets; make sure all are valid
14141        KeySetManagerService ksms = mSettings.mKeySetManagerService;
14142        long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets();
14143        for (int i = 0; i < upgradeKeySets.length; i++) {
14144            if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) {
14145                Slog.wtf(TAG, "Package "
14146                         + (oldPs.name != null ? oldPs.name : "<null>")
14147                         + " contains upgrade-key-set reference to unknown key-set: "
14148                         + upgradeKeySets[i]
14149                         + " reverting to signatures check.");
14150                return false;
14151            }
14152        }
14153        return true;
14154    }
14155
14156    private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) {
14157        // Upgrade keysets are being used.  Determine if new package has a superset of the
14158        // required keys.
14159        long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets();
14160        KeySetManagerService ksms = mSettings.mKeySetManagerService;
14161        for (int i = 0; i < upgradeKeySets.length; i++) {
14162            Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]);
14163            if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) {
14164                return true;
14165            }
14166        }
14167        return false;
14168    }
14169
14170    private static void updateDigest(MessageDigest digest, File file) throws IOException {
14171        try (DigestInputStream digestStream =
14172                new DigestInputStream(new FileInputStream(file), digest)) {
14173            while (digestStream.read() != -1) {} // nothing to do; just plow through the file
14174        }
14175    }
14176
14177    private void replacePackageLIF(PackageParser.Package pkg, final int policyFlags, int scanFlags,
14178            UserHandle user, String installerPackageName, PackageInstalledInfo res) {
14179        final boolean isEphemeral = (policyFlags & PackageParser.PARSE_IS_EPHEMERAL) != 0;
14180
14181        final PackageParser.Package oldPackage;
14182        final String pkgName = pkg.packageName;
14183        final int[] allUsers;
14184        final int[] installedUsers;
14185
14186        synchronized(mPackages) {
14187            oldPackage = mPackages.get(pkgName);
14188            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
14189
14190            // don't allow upgrade to target a release SDK from a pre-release SDK
14191            final boolean oldTargetsPreRelease = oldPackage.applicationInfo.targetSdkVersion
14192                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
14193            final boolean newTargetsPreRelease = pkg.applicationInfo.targetSdkVersion
14194                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
14195            if (oldTargetsPreRelease
14196                    && !newTargetsPreRelease
14197                    && ((policyFlags & PackageParser.PARSE_FORCE_SDK) == 0)) {
14198                Slog.w(TAG, "Can't install package targeting released sdk");
14199                res.setReturnCode(PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE);
14200                return;
14201            }
14202
14203            // don't allow an upgrade from full to ephemeral
14204            final boolean oldIsEphemeral = oldPackage.applicationInfo.isEphemeralApp();
14205            if (isEphemeral && !oldIsEphemeral) {
14206                // can't downgrade from full to ephemeral
14207                Slog.w(TAG, "Can't replace app with ephemeral: " + pkgName);
14208                res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID);
14209                return;
14210            }
14211
14212            // verify signatures are valid
14213            final PackageSetting ps = mSettings.mPackages.get(pkgName);
14214            if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
14215                if (!checkUpgradeKeySetLP(ps, pkg)) {
14216                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
14217                            "New package not signed by keys specified by upgrade-keysets: "
14218                                    + pkgName);
14219                    return;
14220                }
14221            } else {
14222                // default to original signature matching
14223                if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
14224                        != PackageManager.SIGNATURE_MATCH) {
14225                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
14226                            "New package has a different signature: " + pkgName);
14227                    return;
14228                }
14229            }
14230
14231            // don't allow a system upgrade unless the upgrade hash matches
14232            if (oldPackage.restrictUpdateHash != null && oldPackage.isSystemApp()) {
14233                byte[] digestBytes = null;
14234                try {
14235                    final MessageDigest digest = MessageDigest.getInstance("SHA-512");
14236                    updateDigest(digest, new File(pkg.baseCodePath));
14237                    if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
14238                        for (String path : pkg.splitCodePaths) {
14239                            updateDigest(digest, new File(path));
14240                        }
14241                    }
14242                    digestBytes = digest.digest();
14243                } catch (NoSuchAlgorithmException | IOException e) {
14244                    res.setError(INSTALL_FAILED_INVALID_APK,
14245                            "Could not compute hash: " + pkgName);
14246                    return;
14247                }
14248                if (!Arrays.equals(oldPackage.restrictUpdateHash, digestBytes)) {
14249                    res.setError(INSTALL_FAILED_INVALID_APK,
14250                            "New package fails restrict-update check: " + pkgName);
14251                    return;
14252                }
14253                // retain upgrade restriction
14254                pkg.restrictUpdateHash = oldPackage.restrictUpdateHash;
14255            }
14256
14257            // Check for shared user id changes
14258            String invalidPackageName =
14259                    getParentOrChildPackageChangedSharedUser(oldPackage, pkg);
14260            if (invalidPackageName != null) {
14261                res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
14262                        "Package " + invalidPackageName + " tried to change user "
14263                                + oldPackage.mSharedUserId);
14264                return;
14265            }
14266
14267            // In case of rollback, remember per-user/profile install state
14268            allUsers = sUserManager.getUserIds();
14269            installedUsers = ps.queryInstalledUsers(allUsers, true);
14270        }
14271
14272        // Update what is removed
14273        res.removedInfo = new PackageRemovedInfo();
14274        res.removedInfo.uid = oldPackage.applicationInfo.uid;
14275        res.removedInfo.removedPackage = oldPackage.packageName;
14276        res.removedInfo.isUpdate = true;
14277        res.removedInfo.origUsers = installedUsers;
14278        final int childCount = (oldPackage.childPackages != null)
14279                ? oldPackage.childPackages.size() : 0;
14280        for (int i = 0; i < childCount; i++) {
14281            boolean childPackageUpdated = false;
14282            PackageParser.Package childPkg = oldPackage.childPackages.get(i);
14283            if (res.addedChildPackages != null) {
14284                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
14285                if (childRes != null) {
14286                    childRes.removedInfo.uid = childPkg.applicationInfo.uid;
14287                    childRes.removedInfo.removedPackage = childPkg.packageName;
14288                    childRes.removedInfo.isUpdate = true;
14289                    childPackageUpdated = true;
14290                }
14291            }
14292            if (!childPackageUpdated) {
14293                PackageRemovedInfo childRemovedRes = new PackageRemovedInfo();
14294                childRemovedRes.removedPackage = childPkg.packageName;
14295                childRemovedRes.isUpdate = false;
14296                childRemovedRes.dataRemoved = true;
14297                synchronized (mPackages) {
14298                    PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName);
14299                    if (childPs != null) {
14300                        childRemovedRes.origUsers = childPs.queryInstalledUsers(allUsers, true);
14301                    }
14302                }
14303                if (res.removedInfo.removedChildPackages == null) {
14304                    res.removedInfo.removedChildPackages = new ArrayMap<>();
14305                }
14306                res.removedInfo.removedChildPackages.put(childPkg.packageName, childRemovedRes);
14307            }
14308        }
14309
14310        boolean sysPkg = (isSystemApp(oldPackage));
14311        if (sysPkg) {
14312            // Set the system/privileged flags as needed
14313            final boolean privileged =
14314                    (oldPackage.applicationInfo.privateFlags
14315                            & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
14316            final int systemPolicyFlags = policyFlags
14317                    | PackageParser.PARSE_IS_SYSTEM
14318                    | (privileged ? PackageParser.PARSE_IS_PRIVILEGED : 0);
14319
14320            replaceSystemPackageLIF(oldPackage, pkg, systemPolicyFlags, scanFlags,
14321                    user, allUsers, installerPackageName, res);
14322        } else {
14323            replaceNonSystemPackageLIF(oldPackage, pkg, policyFlags, scanFlags,
14324                    user, allUsers, installerPackageName, res);
14325        }
14326    }
14327
14328    public List<String> getPreviousCodePaths(String packageName) {
14329        final PackageSetting ps = mSettings.mPackages.get(packageName);
14330        final List<String> result = new ArrayList<String>();
14331        if (ps != null && ps.oldCodePaths != null) {
14332            result.addAll(ps.oldCodePaths);
14333        }
14334        return result;
14335    }
14336
14337    private void replaceNonSystemPackageLIF(PackageParser.Package deletedPackage,
14338            PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user,
14339            int[] allUsers, String installerPackageName, PackageInstalledInfo res) {
14340        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
14341                + deletedPackage);
14342
14343        String pkgName = deletedPackage.packageName;
14344        boolean deletedPkg = true;
14345        boolean addedPkg = false;
14346        boolean updatedSettings = false;
14347        final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0;
14348        final int deleteFlags = PackageManager.DELETE_KEEP_DATA
14349                | (killApp ? 0 : PackageManager.DELETE_DONT_KILL_APP);
14350
14351        final long origUpdateTime = (pkg.mExtras != null)
14352                ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0;
14353
14354        // First delete the existing package while retaining the data directory
14355        if (!deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
14356                res.removedInfo, true, pkg)) {
14357            // If the existing package wasn't successfully deleted
14358            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
14359            deletedPkg = false;
14360        } else {
14361            // Successfully deleted the old package; proceed with replace.
14362
14363            // If deleted package lived in a container, give users a chance to
14364            // relinquish resources before killing.
14365            if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) {
14366                if (DEBUG_INSTALL) {
14367                    Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
14368                }
14369                final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
14370                final ArrayList<String> pkgList = new ArrayList<String>(1);
14371                pkgList.add(deletedPackage.applicationInfo.packageName);
14372                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
14373            }
14374
14375            clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
14376                    | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
14377            clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL);
14378
14379            try {
14380                final PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags,
14381                        scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
14382                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user);
14383
14384                // Update the in-memory copy of the previous code paths.
14385                PackageSetting ps = mSettings.mPackages.get(pkgName);
14386                if (!killApp) {
14387                    if (ps.oldCodePaths == null) {
14388                        ps.oldCodePaths = new ArraySet<>();
14389                    }
14390                    Collections.addAll(ps.oldCodePaths, deletedPackage.baseCodePath);
14391                    if (deletedPackage.splitCodePaths != null) {
14392                        Collections.addAll(ps.oldCodePaths, deletedPackage.splitCodePaths);
14393                    }
14394                } else {
14395                    ps.oldCodePaths = null;
14396                }
14397                if (ps.childPackageNames != null) {
14398                    for (int i = ps.childPackageNames.size() - 1; i >= 0; --i) {
14399                        final String childPkgName = ps.childPackageNames.get(i);
14400                        final PackageSetting childPs = mSettings.mPackages.get(childPkgName);
14401                        childPs.oldCodePaths = ps.oldCodePaths;
14402                    }
14403                }
14404                prepareAppDataAfterInstallLIF(newPackage);
14405                addedPkg = true;
14406            } catch (PackageManagerException e) {
14407                res.setError("Package couldn't be installed in " + pkg.codePath, e);
14408            }
14409        }
14410
14411        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
14412            if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
14413
14414            // Revert all internal state mutations and added folders for the failed install
14415            if (addedPkg) {
14416                deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
14417                        res.removedInfo, true, null);
14418            }
14419
14420            // Restore the old package
14421            if (deletedPkg) {
14422                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
14423                File restoreFile = new File(deletedPackage.codePath);
14424                // Parse old package
14425                boolean oldExternal = isExternal(deletedPackage);
14426                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
14427                        (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) |
14428                        (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
14429                int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
14430                try {
14431                    scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime,
14432                            null);
14433                } catch (PackageManagerException e) {
14434                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
14435                            + e.getMessage());
14436                    return;
14437                }
14438
14439                synchronized (mPackages) {
14440                    // Ensure the installer package name up to date
14441                    setInstallerPackageNameLPw(deletedPackage, installerPackageName);
14442
14443                    // Update permissions for restored package
14444                    updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
14445
14446                    mSettings.writeLPr();
14447                }
14448
14449                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
14450            }
14451        } else {
14452            synchronized (mPackages) {
14453                PackageSetting ps = mSettings.peekPackageLPr(pkg.packageName);
14454                if (ps != null) {
14455                    res.removedInfo.removedForAllUsers = mPackages.get(ps.name) == null;
14456                    if (res.removedInfo.removedChildPackages != null) {
14457                        final int childCount = res.removedInfo.removedChildPackages.size();
14458                        // Iterate in reverse as we may modify the collection
14459                        for (int i = childCount - 1; i >= 0; i--) {
14460                            String childPackageName = res.removedInfo.removedChildPackages.keyAt(i);
14461                            if (res.addedChildPackages.containsKey(childPackageName)) {
14462                                res.removedInfo.removedChildPackages.removeAt(i);
14463                            } else {
14464                                PackageRemovedInfo childInfo = res.removedInfo
14465                                        .removedChildPackages.valueAt(i);
14466                                childInfo.removedForAllUsers = mPackages.get(
14467                                        childInfo.removedPackage) == null;
14468                            }
14469                        }
14470                    }
14471                }
14472            }
14473        }
14474    }
14475
14476    private void replaceSystemPackageLIF(PackageParser.Package deletedPackage,
14477            PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user,
14478            int[] allUsers, String installerPackageName, PackageInstalledInfo res) {
14479        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
14480                + ", old=" + deletedPackage);
14481
14482        final boolean disabledSystem;
14483
14484        // Remove existing system package
14485        removePackageLI(deletedPackage, true);
14486
14487        synchronized (mPackages) {
14488            disabledSystem = disableSystemPackageLPw(deletedPackage, pkg);
14489        }
14490        if (!disabledSystem) {
14491            // We didn't need to disable the .apk as a current system package,
14492            // which means we are replacing another update that is already
14493            // installed.  We need to make sure to delete the older one's .apk.
14494            res.removedInfo.args = createInstallArgsForExisting(0,
14495                    deletedPackage.applicationInfo.getCodePath(),
14496                    deletedPackage.applicationInfo.getResourcePath(),
14497                    getAppDexInstructionSets(deletedPackage.applicationInfo));
14498        } else {
14499            res.removedInfo.args = null;
14500        }
14501
14502        // Successfully disabled the old package. Now proceed with re-installation
14503        clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
14504                | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
14505        clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL);
14506
14507        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
14508        pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP,
14509                ApplicationInfo.FLAG_UPDATED_SYSTEM_APP);
14510
14511        PackageParser.Package newPackage = null;
14512        try {
14513            // Add the package to the internal data structures
14514            newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags, 0, user);
14515
14516            // Set the update and install times
14517            PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras;
14518            setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime,
14519                    System.currentTimeMillis());
14520
14521            // Update the package dynamic state if succeeded
14522            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
14523                // Now that the install succeeded make sure we remove data
14524                // directories for any child package the update removed.
14525                final int deletedChildCount = (deletedPackage.childPackages != null)
14526                        ? deletedPackage.childPackages.size() : 0;
14527                final int newChildCount = (newPackage.childPackages != null)
14528                        ? newPackage.childPackages.size() : 0;
14529                for (int i = 0; i < deletedChildCount; i++) {
14530                    PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i);
14531                    boolean childPackageDeleted = true;
14532                    for (int j = 0; j < newChildCount; j++) {
14533                        PackageParser.Package newChildPkg = newPackage.childPackages.get(j);
14534                        if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) {
14535                            childPackageDeleted = false;
14536                            break;
14537                        }
14538                    }
14539                    if (childPackageDeleted) {
14540                        PackageSetting ps = mSettings.getDisabledSystemPkgLPr(
14541                                deletedChildPkg.packageName);
14542                        if (ps != null && res.removedInfo.removedChildPackages != null) {
14543                            PackageRemovedInfo removedChildRes = res.removedInfo
14544                                    .removedChildPackages.get(deletedChildPkg.packageName);
14545                            removePackageDataLIF(ps, allUsers, removedChildRes, 0, false);
14546                            removedChildRes.removedForAllUsers = mPackages.get(ps.name) == null;
14547                        }
14548                    }
14549                }
14550
14551                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user);
14552                prepareAppDataAfterInstallLIF(newPackage);
14553            }
14554        } catch (PackageManagerException e) {
14555            res.setReturnCode(INSTALL_FAILED_INTERNAL_ERROR);
14556            res.setError("Package couldn't be installed in " + pkg.codePath, e);
14557        }
14558
14559        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
14560            // Re installation failed. Restore old information
14561            // Remove new pkg information
14562            if (newPackage != null) {
14563                removeInstalledPackageLI(newPackage, true);
14564            }
14565            // Add back the old system package
14566            try {
14567                scanPackageTracedLI(deletedPackage, policyFlags, SCAN_UPDATE_SIGNATURE, 0, user);
14568            } catch (PackageManagerException e) {
14569                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
14570            }
14571
14572            synchronized (mPackages) {
14573                if (disabledSystem) {
14574                    enableSystemPackageLPw(deletedPackage);
14575                }
14576
14577                // Ensure the installer package name up to date
14578                setInstallerPackageNameLPw(deletedPackage, installerPackageName);
14579
14580                // Update permissions for restored package
14581                updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
14582
14583                mSettings.writeLPr();
14584            }
14585
14586            Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName
14587                    + " after failed upgrade");
14588        }
14589    }
14590
14591    /**
14592     * Checks whether the parent or any of the child packages have a change shared
14593     * user. For a package to be a valid update the shred users of the parent and
14594     * the children should match. We may later support changing child shared users.
14595     * @param oldPkg The updated package.
14596     * @param newPkg The update package.
14597     * @return The shared user that change between the versions.
14598     */
14599    private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg,
14600            PackageParser.Package newPkg) {
14601        // Check parent shared user
14602        if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) {
14603            return newPkg.packageName;
14604        }
14605        // Check child shared users
14606        final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
14607        final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0;
14608        for (int i = 0; i < newChildCount; i++) {
14609            PackageParser.Package newChildPkg = newPkg.childPackages.get(i);
14610            // If this child was present, did it have the same shared user?
14611            for (int j = 0; j < oldChildCount; j++) {
14612                PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j);
14613                if (newChildPkg.packageName.equals(oldChildPkg.packageName)
14614                        && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) {
14615                    return newChildPkg.packageName;
14616                }
14617            }
14618        }
14619        return null;
14620    }
14621
14622    private void removeNativeBinariesLI(PackageSetting ps) {
14623        // Remove the lib path for the parent package
14624        if (ps != null) {
14625            NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString);
14626            // Remove the lib path for the child packages
14627            final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
14628            for (int i = 0; i < childCount; i++) {
14629                PackageSetting childPs = null;
14630                synchronized (mPackages) {
14631                    childPs = mSettings.peekPackageLPr(ps.childPackageNames.get(i));
14632                }
14633                if (childPs != null) {
14634                    NativeLibraryHelper.removeNativeBinariesLI(childPs
14635                            .legacyNativeLibraryPathString);
14636                }
14637            }
14638        }
14639    }
14640
14641    private void enableSystemPackageLPw(PackageParser.Package pkg) {
14642        // Enable the parent package
14643        mSettings.enableSystemPackageLPw(pkg.packageName);
14644        // Enable the child packages
14645        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
14646        for (int i = 0; i < childCount; i++) {
14647            PackageParser.Package childPkg = pkg.childPackages.get(i);
14648            mSettings.enableSystemPackageLPw(childPkg.packageName);
14649        }
14650    }
14651
14652    private boolean disableSystemPackageLPw(PackageParser.Package oldPkg,
14653            PackageParser.Package newPkg) {
14654        // Disable the parent package (parent always replaced)
14655        boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true);
14656        // Disable the child packages
14657        final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
14658        for (int i = 0; i < childCount; i++) {
14659            PackageParser.Package childPkg = oldPkg.childPackages.get(i);
14660            final boolean replace = newPkg.hasChildPackage(childPkg.packageName);
14661            disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace);
14662        }
14663        return disabled;
14664    }
14665
14666    private void setInstallerPackageNameLPw(PackageParser.Package pkg,
14667            String installerPackageName) {
14668        // Enable the parent package
14669        mSettings.setInstallerPackageName(pkg.packageName, installerPackageName);
14670        // Enable the child packages
14671        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
14672        for (int i = 0; i < childCount; i++) {
14673            PackageParser.Package childPkg = pkg.childPackages.get(i);
14674            mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName);
14675        }
14676    }
14677
14678    private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) {
14679        // Collect all used permissions in the UID
14680        ArraySet<String> usedPermissions = new ArraySet<>();
14681        final int packageCount = su.packages.size();
14682        for (int i = 0; i < packageCount; i++) {
14683            PackageSetting ps = su.packages.valueAt(i);
14684            if (ps.pkg == null) {
14685                continue;
14686            }
14687            final int requestedPermCount = ps.pkg.requestedPermissions.size();
14688            for (int j = 0; j < requestedPermCount; j++) {
14689                String permission = ps.pkg.requestedPermissions.get(j);
14690                BasePermission bp = mSettings.mPermissions.get(permission);
14691                if (bp != null) {
14692                    usedPermissions.add(permission);
14693                }
14694            }
14695        }
14696
14697        PermissionsState permissionsState = su.getPermissionsState();
14698        // Prune install permissions
14699        List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates();
14700        final int installPermCount = installPermStates.size();
14701        for (int i = installPermCount - 1; i >= 0;  i--) {
14702            PermissionState permissionState = installPermStates.get(i);
14703            if (!usedPermissions.contains(permissionState.getName())) {
14704                BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
14705                if (bp != null) {
14706                    permissionsState.revokeInstallPermission(bp);
14707                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
14708                            PackageManager.MASK_PERMISSION_FLAGS, 0);
14709                }
14710            }
14711        }
14712
14713        int[] runtimePermissionChangedUserIds = EmptyArray.INT;
14714
14715        // Prune runtime permissions
14716        for (int userId : allUserIds) {
14717            List<PermissionState> runtimePermStates = permissionsState
14718                    .getRuntimePermissionStates(userId);
14719            final int runtimePermCount = runtimePermStates.size();
14720            for (int i = runtimePermCount - 1; i >= 0; i--) {
14721                PermissionState permissionState = runtimePermStates.get(i);
14722                if (!usedPermissions.contains(permissionState.getName())) {
14723                    BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
14724                    if (bp != null) {
14725                        permissionsState.revokeRuntimePermission(bp, userId);
14726                        permissionsState.updatePermissionFlags(bp, userId,
14727                                PackageManager.MASK_PERMISSION_FLAGS, 0);
14728                        runtimePermissionChangedUserIds = ArrayUtils.appendInt(
14729                                runtimePermissionChangedUserIds, userId);
14730                    }
14731                }
14732            }
14733        }
14734
14735        return runtimePermissionChangedUserIds;
14736    }
14737
14738    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
14739            int[] allUsers, PackageInstalledInfo res, UserHandle user) {
14740        // Update the parent package setting
14741        updateSettingsInternalLI(newPackage, installerPackageName, allUsers, res.origUsers,
14742                res, user);
14743        // Update the child packages setting
14744        final int childCount = (newPackage.childPackages != null)
14745                ? newPackage.childPackages.size() : 0;
14746        for (int i = 0; i < childCount; i++) {
14747            PackageParser.Package childPackage = newPackage.childPackages.get(i);
14748            PackageInstalledInfo childRes = res.addedChildPackages.get(childPackage.packageName);
14749            updateSettingsInternalLI(childPackage, installerPackageName, allUsers,
14750                    childRes.origUsers, childRes, user);
14751        }
14752    }
14753
14754    private void updateSettingsInternalLI(PackageParser.Package newPackage,
14755            String installerPackageName, int[] allUsers, int[] installedForUsers,
14756            PackageInstalledInfo res, UserHandle user) {
14757        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
14758
14759        String pkgName = newPackage.packageName;
14760        synchronized (mPackages) {
14761            //write settings. the installStatus will be incomplete at this stage.
14762            //note that the new package setting would have already been
14763            //added to mPackages. It hasn't been persisted yet.
14764            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
14765            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
14766            mSettings.writeLPr();
14767            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
14768        }
14769
14770        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath);
14771        synchronized (mPackages) {
14772            updatePermissionsLPw(newPackage.packageName, newPackage,
14773                    UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
14774                            ? UPDATE_PERMISSIONS_ALL : 0));
14775            // For system-bundled packages, we assume that installing an upgraded version
14776            // of the package implies that the user actually wants to run that new code,
14777            // so we enable the package.
14778            PackageSetting ps = mSettings.mPackages.get(pkgName);
14779            final int userId = user.getIdentifier();
14780            if (ps != null) {
14781                if (isSystemApp(newPackage)) {
14782                    if (DEBUG_INSTALL) {
14783                        Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
14784                    }
14785                    // Enable system package for requested users
14786                    if (res.origUsers != null) {
14787                        for (int origUserId : res.origUsers) {
14788                            if (userId == UserHandle.USER_ALL || userId == origUserId) {
14789                                ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
14790                                        origUserId, installerPackageName);
14791                            }
14792                        }
14793                    }
14794                    // Also convey the prior install/uninstall state
14795                    if (allUsers != null && installedForUsers != null) {
14796                        for (int currentUserId : allUsers) {
14797                            final boolean installed = ArrayUtils.contains(
14798                                    installedForUsers, currentUserId);
14799                            if (DEBUG_INSTALL) {
14800                                Slog.d(TAG, "    user " + currentUserId + " => " + installed);
14801                            }
14802                            ps.setInstalled(installed, currentUserId);
14803                        }
14804                        // these install state changes will be persisted in the
14805                        // upcoming call to mSettings.writeLPr().
14806                    }
14807                }
14808                // It's implied that when a user requests installation, they want the app to be
14809                // installed and enabled.
14810                if (userId != UserHandle.USER_ALL) {
14811                    ps.setInstalled(true, userId);
14812                    ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName);
14813                }
14814            }
14815            res.name = pkgName;
14816            res.uid = newPackage.applicationInfo.uid;
14817            res.pkg = newPackage;
14818            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
14819            mSettings.setInstallerPackageName(pkgName, installerPackageName);
14820            res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
14821            //to update install status
14822            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
14823            mSettings.writeLPr();
14824            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
14825        }
14826
14827        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
14828    }
14829
14830    private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) {
14831        try {
14832            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage");
14833            installPackageLI(args, res);
14834        } finally {
14835            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
14836        }
14837    }
14838
14839    private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
14840        final int installFlags = args.installFlags;
14841        final String installerPackageName = args.installerPackageName;
14842        final String volumeUuid = args.volumeUuid;
14843        final File tmpPackageFile = new File(args.getCodePath());
14844        final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
14845        final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0)
14846                || (args.volumeUuid != null));
14847        final boolean ephemeral = ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0);
14848        final boolean forceSdk = ((installFlags & PackageManager.INSTALL_FORCE_SDK) != 0);
14849        boolean replace = false;
14850        int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE;
14851        if (args.move != null) {
14852            // moving a complete application; perform an initial scan on the new install location
14853            scanFlags |= SCAN_INITIAL;
14854        }
14855        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
14856            scanFlags |= SCAN_DONT_KILL_APP;
14857        }
14858
14859        // Result object to be returned
14860        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
14861
14862        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
14863
14864        // Sanity check
14865        if (ephemeral && (forwardLocked || onExternal)) {
14866            Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked
14867                    + " external=" + onExternal);
14868            res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID);
14869            return;
14870        }
14871
14872        // Retrieve PackageSettings and parse package
14873        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
14874                | PackageParser.PARSE_ENFORCE_CODE
14875                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
14876                | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0)
14877                | (ephemeral ? PackageParser.PARSE_IS_EPHEMERAL : 0)
14878                | (forceSdk ? PackageParser.PARSE_FORCE_SDK : 0);
14879        PackageParser pp = new PackageParser();
14880        pp.setSeparateProcesses(mSeparateProcesses);
14881        pp.setDisplayMetrics(mMetrics);
14882
14883        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
14884        final PackageParser.Package pkg;
14885        try {
14886            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
14887        } catch (PackageParserException e) {
14888            res.setError("Failed parse during installPackageLI", e);
14889            return;
14890        } finally {
14891            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
14892        }
14893
14894        // If we are installing a clustered package add results for the children
14895        if (pkg.childPackages != null) {
14896            synchronized (mPackages) {
14897                final int childCount = pkg.childPackages.size();
14898                for (int i = 0; i < childCount; i++) {
14899                    PackageParser.Package childPkg = pkg.childPackages.get(i);
14900                    PackageInstalledInfo childRes = new PackageInstalledInfo();
14901                    childRes.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
14902                    childRes.pkg = childPkg;
14903                    childRes.name = childPkg.packageName;
14904                    PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName);
14905                    if (childPs != null) {
14906                        childRes.origUsers = childPs.queryInstalledUsers(
14907                                sUserManager.getUserIds(), true);
14908                    }
14909                    if ((mPackages.containsKey(childPkg.packageName))) {
14910                        childRes.removedInfo = new PackageRemovedInfo();
14911                        childRes.removedInfo.removedPackage = childPkg.packageName;
14912                    }
14913                    if (res.addedChildPackages == null) {
14914                        res.addedChildPackages = new ArrayMap<>();
14915                    }
14916                    res.addedChildPackages.put(childPkg.packageName, childRes);
14917                }
14918            }
14919        }
14920
14921        // If package doesn't declare API override, mark that we have an install
14922        // time CPU ABI override.
14923        if (TextUtils.isEmpty(pkg.cpuAbiOverride)) {
14924            pkg.cpuAbiOverride = args.abiOverride;
14925        }
14926
14927        String pkgName = res.name = pkg.packageName;
14928        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
14929            if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
14930                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
14931                return;
14932            }
14933        }
14934
14935        try {
14936            // either use what we've been given or parse directly from the APK
14937            if (args.certificates != null) {
14938                try {
14939                    PackageParser.populateCertificates(pkg, args.certificates);
14940                } catch (PackageParserException e) {
14941                    // there was something wrong with the certificates we were given;
14942                    // try to pull them from the APK
14943                    PackageParser.collectCertificates(pkg, parseFlags);
14944                }
14945            } else {
14946                PackageParser.collectCertificates(pkg, parseFlags);
14947            }
14948        } catch (PackageParserException e) {
14949            res.setError("Failed collect during installPackageLI", e);
14950            return;
14951        }
14952
14953        // Get rid of all references to package scan path via parser.
14954        pp = null;
14955        String oldCodePath = null;
14956        boolean systemApp = false;
14957        synchronized (mPackages) {
14958            // Check if installing already existing package
14959            if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
14960                String oldName = mSettings.mRenamedPackages.get(pkgName);
14961                if (pkg.mOriginalPackages != null
14962                        && pkg.mOriginalPackages.contains(oldName)
14963                        && mPackages.containsKey(oldName)) {
14964                    // This package is derived from an original package,
14965                    // and this device has been updating from that original
14966                    // name.  We must continue using the original name, so
14967                    // rename the new package here.
14968                    pkg.setPackageName(oldName);
14969                    pkgName = pkg.packageName;
14970                    replace = true;
14971                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
14972                            + oldName + " pkgName=" + pkgName);
14973                } else if (mPackages.containsKey(pkgName)) {
14974                    // This package, under its official name, already exists
14975                    // on the device; we should replace it.
14976                    replace = true;
14977                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
14978                }
14979
14980                // Child packages are installed through the parent package
14981                if (pkg.parentPackage != null) {
14982                    res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
14983                            "Package " + pkg.packageName + " is child of package "
14984                                    + pkg.parentPackage.parentPackage + ". Child packages "
14985                                    + "can be updated only through the parent package.");
14986                    return;
14987                }
14988
14989                if (replace) {
14990                    // Prevent apps opting out from runtime permissions
14991                    PackageParser.Package oldPackage = mPackages.get(pkgName);
14992                    final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion;
14993                    final int newTargetSdk = pkg.applicationInfo.targetSdkVersion;
14994                    if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1
14995                            && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) {
14996                        res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE,
14997                                "Package " + pkg.packageName + " new target SDK " + newTargetSdk
14998                                        + " doesn't support runtime permissions but the old"
14999                                        + " target SDK " + oldTargetSdk + " does.");
15000                        return;
15001                    }
15002
15003                    // Prevent installing of child packages
15004                    if (oldPackage.parentPackage != null) {
15005                        res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
15006                                "Package " + pkg.packageName + " is child of package "
15007                                        + oldPackage.parentPackage + ". Child packages "
15008                                        + "can be updated only through the parent package.");
15009                        return;
15010                    }
15011                }
15012            }
15013
15014            PackageSetting ps = mSettings.mPackages.get(pkgName);
15015            if (ps != null) {
15016                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
15017
15018                // Quick sanity check that we're signed correctly if updating;
15019                // we'll check this again later when scanning, but we want to
15020                // bail early here before tripping over redefined permissions.
15021                if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
15022                    if (!checkUpgradeKeySetLP(ps, pkg)) {
15023                        res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
15024                                + pkg.packageName + " upgrade keys do not match the "
15025                                + "previously installed version");
15026                        return;
15027                    }
15028                } else {
15029                    try {
15030                        verifySignaturesLP(ps, pkg);
15031                    } catch (PackageManagerException e) {
15032                        res.setError(e.error, e.getMessage());
15033                        return;
15034                    }
15035                }
15036
15037                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
15038                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
15039                    systemApp = (ps.pkg.applicationInfo.flags &
15040                            ApplicationInfo.FLAG_SYSTEM) != 0;
15041                }
15042                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
15043            }
15044
15045            // Check whether the newly-scanned package wants to define an already-defined perm
15046            int N = pkg.permissions.size();
15047            for (int i = N-1; i >= 0; i--) {
15048                PackageParser.Permission perm = pkg.permissions.get(i);
15049                BasePermission bp = mSettings.mPermissions.get(perm.info.name);
15050                if (bp != null) {
15051                    // If the defining package is signed with our cert, it's okay.  This
15052                    // also includes the "updating the same package" case, of course.
15053                    // "updating same package" could also involve key-rotation.
15054                    final boolean sigsOk;
15055                    if (bp.sourcePackage.equals(pkg.packageName)
15056                            && (bp.packageSetting instanceof PackageSetting)
15057                            && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting,
15058                                    scanFlags))) {
15059                        sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg);
15060                    } else {
15061                        sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures,
15062                                pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
15063                    }
15064                    if (!sigsOk) {
15065                        // If the owning package is the system itself, we log but allow
15066                        // install to proceed; we fail the install on all other permission
15067                        // redefinitions.
15068                        if (!bp.sourcePackage.equals("android")) {
15069                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
15070                                    + pkg.packageName + " attempting to redeclare permission "
15071                                    + perm.info.name + " already owned by " + bp.sourcePackage);
15072                            res.origPermission = perm.info.name;
15073                            res.origPackage = bp.sourcePackage;
15074                            return;
15075                        } else {
15076                            Slog.w(TAG, "Package " + pkg.packageName
15077                                    + " attempting to redeclare system permission "
15078                                    + perm.info.name + "; ignoring new declaration");
15079                            pkg.permissions.remove(i);
15080                        }
15081                    }
15082                }
15083            }
15084        }
15085
15086        if (systemApp) {
15087            if (onExternal) {
15088                // Abort update; system app can't be replaced with app on sdcard
15089                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
15090                        "Cannot install updates to system apps on sdcard");
15091                return;
15092            } else if (ephemeral) {
15093                // Abort update; system app can't be replaced with an ephemeral app
15094                res.setError(INSTALL_FAILED_EPHEMERAL_INVALID,
15095                        "Cannot update a system app with an ephemeral app");
15096                return;
15097            }
15098        }
15099
15100        if (args.move != null) {
15101            // We did an in-place move, so dex is ready to roll
15102            scanFlags |= SCAN_NO_DEX;
15103            scanFlags |= SCAN_MOVE;
15104
15105            synchronized (mPackages) {
15106                final PackageSetting ps = mSettings.mPackages.get(pkgName);
15107                if (ps == null) {
15108                    res.setError(INSTALL_FAILED_INTERNAL_ERROR,
15109                            "Missing settings for moved package " + pkgName);
15110                }
15111
15112                // We moved the entire application as-is, so bring over the
15113                // previously derived ABI information.
15114                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
15115                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
15116            }
15117
15118        } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) {
15119            // Enable SCAN_NO_DEX flag to skip dexopt at a later stage
15120            scanFlags |= SCAN_NO_DEX;
15121
15122            try {
15123                String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ?
15124                    args.abiOverride : pkg.cpuAbiOverride);
15125                derivePackageAbi(pkg, new File(pkg.codePath), abiOverride,
15126                        true /* extract libs */);
15127            } catch (PackageManagerException pme) {
15128                Slog.e(TAG, "Error deriving application ABI", pme);
15129                res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI");
15130                return;
15131            }
15132
15133            // Shared libraries for the package need to be updated.
15134            synchronized (mPackages) {
15135                try {
15136                    updateSharedLibrariesLPw(pkg, null);
15137                } catch (PackageManagerException e) {
15138                    Slog.e(TAG, "updateSharedLibrariesLPw failed: " + e.getMessage());
15139                }
15140            }
15141            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
15142            // Do not run PackageDexOptimizer through the local performDexOpt
15143            // method because `pkg` may not be in `mPackages` yet.
15144            //
15145            // Also, don't fail application installs if the dexopt step fails.
15146            mPackageDexOptimizer.performDexOpt(pkg, pkg.usesLibraryFiles,
15147                    null /* instructionSets */, false /* checkProfiles */,
15148                    getCompilerFilterForReason(REASON_INSTALL));
15149            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
15150
15151            // Notify BackgroundDexOptService that the package has been changed.
15152            // If this is an update of a package which used to fail to compile,
15153            // BDOS will remove it from its blacklist.
15154            BackgroundDexOptService.notifyPackageChanged(pkg.packageName);
15155        }
15156
15157        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
15158            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
15159            return;
15160        }
15161
15162        startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg);
15163
15164        try (PackageFreezer freezer = freezePackageForInstall(pkgName, installFlags,
15165                "installPackageLI")) {
15166            if (replace) {
15167                replacePackageLIF(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user,
15168                        installerPackageName, res);
15169            } else {
15170                installNewPackageLIF(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
15171                        args.user, installerPackageName, volumeUuid, res);
15172            }
15173        }
15174        synchronized (mPackages) {
15175            final PackageSetting ps = mSettings.mPackages.get(pkgName);
15176            if (ps != null) {
15177                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
15178            }
15179
15180            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
15181            for (int i = 0; i < childCount; i++) {
15182                PackageParser.Package childPkg = pkg.childPackages.get(i);
15183                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
15184                PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName);
15185                if (childPs != null) {
15186                    childRes.newUsers = childPs.queryInstalledUsers(
15187                            sUserManager.getUserIds(), true);
15188                }
15189            }
15190        }
15191    }
15192
15193    private void startIntentFilterVerifications(int userId, boolean replacing,
15194            PackageParser.Package pkg) {
15195        if (mIntentFilterVerifierComponent == null) {
15196            Slog.w(TAG, "No IntentFilter verification will not be done as "
15197                    + "there is no IntentFilterVerifier available!");
15198            return;
15199        }
15200
15201        final int verifierUid = getPackageUid(
15202                mIntentFilterVerifierComponent.getPackageName(),
15203                MATCH_DEBUG_TRIAGED_MISSING,
15204                (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId);
15205
15206        Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
15207        msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid);
15208        mHandler.sendMessage(msg);
15209
15210        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
15211        for (int i = 0; i < childCount; i++) {
15212            PackageParser.Package childPkg = pkg.childPackages.get(i);
15213            msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
15214            msg.obj = new IFVerificationParams(childPkg, replacing, userId, verifierUid);
15215            mHandler.sendMessage(msg);
15216        }
15217    }
15218
15219    private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing,
15220            PackageParser.Package pkg) {
15221        int size = pkg.activities.size();
15222        if (size == 0) {
15223            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
15224                    "No activity, so no need to verify any IntentFilter!");
15225            return;
15226        }
15227
15228        final boolean hasDomainURLs = hasDomainURLs(pkg);
15229        if (!hasDomainURLs) {
15230            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
15231                    "No domain URLs, so no need to verify any IntentFilter!");
15232            return;
15233        }
15234
15235        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId
15236                + " if any IntentFilter from the " + size
15237                + " Activities needs verification ...");
15238
15239        int count = 0;
15240        final String packageName = pkg.packageName;
15241
15242        synchronized (mPackages) {
15243            // If this is a new install and we see that we've already run verification for this
15244            // package, we have nothing to do: it means the state was restored from backup.
15245            if (!replacing) {
15246                IntentFilterVerificationInfo ivi =
15247                        mSettings.getIntentFilterVerificationLPr(packageName);
15248                if (ivi != null) {
15249                    if (DEBUG_DOMAIN_VERIFICATION) {
15250                        Slog.i(TAG, "Package " + packageName+ " already verified: status="
15251                                + ivi.getStatusString());
15252                    }
15253                    return;
15254                }
15255            }
15256
15257            // If any filters need to be verified, then all need to be.
15258            boolean needToVerify = false;
15259            for (PackageParser.Activity a : pkg.activities) {
15260                for (ActivityIntentInfo filter : a.intents) {
15261                    if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) {
15262                        if (DEBUG_DOMAIN_VERIFICATION) {
15263                            Slog.d(TAG, "Intent filter needs verification, so processing all filters");
15264                        }
15265                        needToVerify = true;
15266                        break;
15267                    }
15268                }
15269            }
15270
15271            if (needToVerify) {
15272                final int verificationId = mIntentFilterVerificationToken++;
15273                for (PackageParser.Activity a : pkg.activities) {
15274                    for (ActivityIntentInfo filter : a.intents) {
15275                        if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) {
15276                            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
15277                                    "Verification needed for IntentFilter:" + filter.toString());
15278                            mIntentFilterVerifier.addOneIntentFilterVerification(
15279                                    verifierUid, userId, verificationId, filter, packageName);
15280                            count++;
15281                        }
15282                    }
15283                }
15284            }
15285        }
15286
15287        if (count > 0) {
15288            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count
15289                    + " IntentFilter verification" + (count > 1 ? "s" : "")
15290                    +  " for userId:" + userId);
15291            mIntentFilterVerifier.startVerifications(userId);
15292        } else {
15293            if (DEBUG_DOMAIN_VERIFICATION) {
15294                Slog.d(TAG, "No filters or not all autoVerify for " + packageName);
15295            }
15296        }
15297    }
15298
15299    private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) {
15300        final ComponentName cn  = filter.activity.getComponentName();
15301        final String packageName = cn.getPackageName();
15302
15303        IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr(
15304                packageName);
15305        if (ivi == null) {
15306            return true;
15307        }
15308        int status = ivi.getStatus();
15309        switch (status) {
15310            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
15311            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
15312                return true;
15313
15314            default:
15315                // Nothing to do
15316                return false;
15317        }
15318    }
15319
15320    private static boolean isMultiArch(ApplicationInfo info) {
15321        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
15322    }
15323
15324    private static boolean isExternal(PackageParser.Package pkg) {
15325        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
15326    }
15327
15328    private static boolean isExternal(PackageSetting ps) {
15329        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
15330    }
15331
15332    private static boolean isEphemeral(PackageParser.Package pkg) {
15333        return pkg.applicationInfo.isEphemeralApp();
15334    }
15335
15336    private static boolean isEphemeral(PackageSetting ps) {
15337        return ps.pkg != null && isEphemeral(ps.pkg);
15338    }
15339
15340    private static boolean isSystemApp(PackageParser.Package pkg) {
15341        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
15342    }
15343
15344    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
15345        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
15346    }
15347
15348    private static boolean hasDomainURLs(PackageParser.Package pkg) {
15349        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0;
15350    }
15351
15352    private static boolean isSystemApp(PackageSetting ps) {
15353        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
15354    }
15355
15356    private static boolean isUpdatedSystemApp(PackageSetting ps) {
15357        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
15358    }
15359
15360    private int packageFlagsToInstallFlags(PackageSetting ps) {
15361        int installFlags = 0;
15362        if (isEphemeral(ps)) {
15363            installFlags |= PackageManager.INSTALL_EPHEMERAL;
15364        }
15365        if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) {
15366            // This existing package was an external ASEC install when we have
15367            // the external flag without a UUID
15368            installFlags |= PackageManager.INSTALL_EXTERNAL;
15369        }
15370        if (ps.isForwardLocked()) {
15371            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
15372        }
15373        return installFlags;
15374    }
15375
15376    private String getVolumeUuidForPackage(PackageParser.Package pkg) {
15377        if (isExternal(pkg)) {
15378            if (TextUtils.isEmpty(pkg.volumeUuid)) {
15379                return StorageManager.UUID_PRIMARY_PHYSICAL;
15380            } else {
15381                return pkg.volumeUuid;
15382            }
15383        } else {
15384            return StorageManager.UUID_PRIVATE_INTERNAL;
15385        }
15386    }
15387
15388    private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) {
15389        if (isExternal(pkg)) {
15390            if (TextUtils.isEmpty(pkg.volumeUuid)) {
15391                return mSettings.getExternalVersion();
15392            } else {
15393                return mSettings.findOrCreateVersion(pkg.volumeUuid);
15394            }
15395        } else {
15396            return mSettings.getInternalVersion();
15397        }
15398    }
15399
15400    private void deleteTempPackageFiles() {
15401        final FilenameFilter filter = new FilenameFilter() {
15402            public boolean accept(File dir, String name) {
15403                return name.startsWith("vmdl") && name.endsWith(".tmp");
15404            }
15405        };
15406        for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) {
15407            file.delete();
15408        }
15409    }
15410
15411    @Override
15412    public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId,
15413            int flags) {
15414        deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId,
15415                flags);
15416    }
15417
15418    @Override
15419    public void deletePackage(final String packageName,
15420            final IPackageDeleteObserver2 observer, final int userId, final int deleteFlags) {
15421        mContext.enforceCallingOrSelfPermission(
15422                android.Manifest.permission.DELETE_PACKAGES, null);
15423        Preconditions.checkNotNull(packageName);
15424        Preconditions.checkNotNull(observer);
15425        final int uid = Binder.getCallingUid();
15426        final boolean deleteAllUsers = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0;
15427        final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId };
15428        if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) {
15429            mContext.enforceCallingOrSelfPermission(
15430                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
15431                    "deletePackage for user " + userId);
15432        }
15433
15434        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
15435            try {
15436                observer.onPackageDeleted(packageName,
15437                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
15438            } catch (RemoteException re) {
15439            }
15440            return;
15441        }
15442
15443        if (!deleteAllUsers && getBlockUninstallForUser(packageName, userId)) {
15444            try {
15445                observer.onPackageDeleted(packageName,
15446                        PackageManager.DELETE_FAILED_OWNER_BLOCKED, null);
15447            } catch (RemoteException re) {
15448            }
15449            return;
15450        }
15451
15452        if (DEBUG_REMOVE) {
15453            Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId
15454                    + " deleteAllUsers: " + deleteAllUsers );
15455        }
15456        // Queue up an async operation since the package deletion may take a little while.
15457        mHandler.post(new Runnable() {
15458            public void run() {
15459                mHandler.removeCallbacks(this);
15460                int returnCode;
15461                if (!deleteAllUsers) {
15462                    returnCode = deletePackageX(packageName, userId, deleteFlags);
15463                } else {
15464                    int[] blockUninstallUserIds = getBlockUninstallForUsers(packageName, users);
15465                    // If nobody is blocking uninstall, proceed with delete for all users
15466                    if (ArrayUtils.isEmpty(blockUninstallUserIds)) {
15467                        returnCode = deletePackageX(packageName, userId, deleteFlags);
15468                    } else {
15469                        // Otherwise uninstall individually for users with blockUninstalls=false
15470                        final int userFlags = deleteFlags & ~PackageManager.DELETE_ALL_USERS;
15471                        for (int userId : users) {
15472                            if (!ArrayUtils.contains(blockUninstallUserIds, userId)) {
15473                                returnCode = deletePackageX(packageName, userId, userFlags);
15474                                if (returnCode != PackageManager.DELETE_SUCCEEDED) {
15475                                    Slog.w(TAG, "Package delete failed for user " + userId
15476                                            + ", returnCode " + returnCode);
15477                                }
15478                            }
15479                        }
15480                        // The app has only been marked uninstalled for certain users.
15481                        // We still need to report that delete was blocked
15482                        returnCode = PackageManager.DELETE_FAILED_OWNER_BLOCKED;
15483                    }
15484                }
15485                try {
15486                    observer.onPackageDeleted(packageName, returnCode, null);
15487                } catch (RemoteException e) {
15488                    Log.i(TAG, "Observer no longer exists.");
15489                } //end catch
15490            } //end run
15491        });
15492    }
15493
15494    private int[] getBlockUninstallForUsers(String packageName, int[] userIds) {
15495        int[] result = EMPTY_INT_ARRAY;
15496        for (int userId : userIds) {
15497            if (getBlockUninstallForUser(packageName, userId)) {
15498                result = ArrayUtils.appendInt(result, userId);
15499            }
15500        }
15501        return result;
15502    }
15503
15504    @Override
15505    public boolean isPackageDeviceAdminOnAnyUser(String packageName) {
15506        return isPackageDeviceAdmin(packageName, UserHandle.USER_ALL);
15507    }
15508
15509    private boolean isPackageDeviceAdmin(String packageName, int userId) {
15510        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
15511                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
15512        try {
15513            if (dpm != null) {
15514                final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent(
15515                        /* callingUserOnly =*/ false);
15516                final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null
15517                        : deviceOwnerComponentName.getPackageName();
15518                // Does the package contains the device owner?
15519                // TODO Do we have to do it even if userId != UserHandle.USER_ALL?  Otherwise,
15520                // this check is probably not needed, since DO should be registered as a device
15521                // admin on some user too. (Original bug for this: b/17657954)
15522                if (packageName.equals(deviceOwnerPackageName)) {
15523                    return true;
15524                }
15525                // Does it contain a device admin for any user?
15526                int[] users;
15527                if (userId == UserHandle.USER_ALL) {
15528                    users = sUserManager.getUserIds();
15529                } else {
15530                    users = new int[]{userId};
15531                }
15532                for (int i = 0; i < users.length; ++i) {
15533                    if (dpm.packageHasActiveAdmins(packageName, users[i])) {
15534                        return true;
15535                    }
15536                }
15537            }
15538        } catch (RemoteException e) {
15539        }
15540        return false;
15541    }
15542
15543    private boolean shouldKeepUninstalledPackageLPr(String packageName) {
15544        return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName);
15545    }
15546
15547    /**
15548     *  This method is an internal method that could be get invoked either
15549     *  to delete an installed package or to clean up a failed installation.
15550     *  After deleting an installed package, a broadcast is sent to notify any
15551     *  listeners that the package has been removed. For cleaning up a failed
15552     *  installation, the broadcast is not necessary since the package's
15553     *  installation wouldn't have sent the initial broadcast either
15554     *  The key steps in deleting a package are
15555     *  deleting the package information in internal structures like mPackages,
15556     *  deleting the packages base directories through installd
15557     *  updating mSettings to reflect current status
15558     *  persisting settings for later use
15559     *  sending a broadcast if necessary
15560     */
15561    private int deletePackageX(String packageName, int userId, int deleteFlags) {
15562        final PackageRemovedInfo info = new PackageRemovedInfo();
15563        final boolean res;
15564
15565        final UserHandle removeForUser = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0
15566                ? UserHandle.ALL : new UserHandle(userId);
15567
15568        if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) {
15569            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
15570            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
15571        }
15572
15573        PackageSetting uninstalledPs = null;
15574
15575        // for the uninstall-updates case and restricted profiles, remember the per-
15576        // user handle installed state
15577        int[] allUsers;
15578        synchronized (mPackages) {
15579            uninstalledPs = mSettings.mPackages.get(packageName);
15580            if (uninstalledPs == null) {
15581                Slog.w(TAG, "Not removing non-existent package " + packageName);
15582                return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
15583            }
15584            allUsers = sUserManager.getUserIds();
15585            info.origUsers = uninstalledPs.queryInstalledUsers(allUsers, true);
15586        }
15587
15588        synchronized (mInstallLock) {
15589            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
15590            try (PackageFreezer freezer = freezePackageForDelete(packageName, deleteFlags,
15591                    "deletePackageX")) {
15592                res = deletePackageLIF(packageName, removeForUser, true, allUsers,
15593                        deleteFlags | REMOVE_CHATTY, info, true, null);
15594            }
15595            synchronized (mPackages) {
15596                if (res) {
15597                    mEphemeralApplicationRegistry.onPackageUninstalledLPw(uninstalledPs.pkg);
15598                }
15599            }
15600        }
15601
15602        if (res) {
15603            final boolean killApp = (deleteFlags & PackageManager.DELETE_DONT_KILL_APP) == 0;
15604            info.sendPackageRemovedBroadcasts(killApp);
15605            info.sendSystemPackageUpdatedBroadcasts();
15606            info.sendSystemPackageAppearedBroadcasts();
15607        }
15608        // Force a gc here.
15609        Runtime.getRuntime().gc();
15610        // Delete the resources here after sending the broadcast to let
15611        // other processes clean up before deleting resources.
15612        if (info.args != null) {
15613            synchronized (mInstallLock) {
15614                info.args.doPostDeleteLI(true);
15615            }
15616        }
15617
15618        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
15619    }
15620
15621    class PackageRemovedInfo {
15622        String removedPackage;
15623        int uid = -1;
15624        int removedAppId = -1;
15625        int[] origUsers;
15626        int[] removedUsers = null;
15627        boolean isRemovedPackageSystemUpdate = false;
15628        boolean isUpdate;
15629        boolean dataRemoved;
15630        boolean removedForAllUsers;
15631        // Clean up resources deleted packages.
15632        InstallArgs args = null;
15633        ArrayMap<String, PackageRemovedInfo> removedChildPackages;
15634        ArrayMap<String, PackageInstalledInfo> appearedChildPackages;
15635
15636        void sendPackageRemovedBroadcasts(boolean killApp) {
15637            sendPackageRemovedBroadcastInternal(killApp);
15638            final int childCount = removedChildPackages != null ? removedChildPackages.size() : 0;
15639            for (int i = 0; i < childCount; i++) {
15640                PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
15641                childInfo.sendPackageRemovedBroadcastInternal(killApp);
15642            }
15643        }
15644
15645        void sendSystemPackageUpdatedBroadcasts() {
15646            if (isRemovedPackageSystemUpdate) {
15647                sendSystemPackageUpdatedBroadcastsInternal();
15648                final int childCount = (removedChildPackages != null)
15649                        ? removedChildPackages.size() : 0;
15650                for (int i = 0; i < childCount; i++) {
15651                    PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
15652                    if (childInfo.isRemovedPackageSystemUpdate) {
15653                        childInfo.sendSystemPackageUpdatedBroadcastsInternal();
15654                    }
15655                }
15656            }
15657        }
15658
15659        void sendSystemPackageAppearedBroadcasts() {
15660            final int packageCount = (appearedChildPackages != null)
15661                    ? appearedChildPackages.size() : 0;
15662            for (int i = 0; i < packageCount; i++) {
15663                PackageInstalledInfo installedInfo = appearedChildPackages.valueAt(i);
15664                for (int userId : installedInfo.newUsers) {
15665                    sendPackageAddedForUser(installedInfo.name, true,
15666                            UserHandle.getAppId(installedInfo.uid), userId);
15667                }
15668            }
15669        }
15670
15671        private void sendSystemPackageUpdatedBroadcastsInternal() {
15672            Bundle extras = new Bundle(2);
15673            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
15674            extras.putBoolean(Intent.EXTRA_REPLACING, true);
15675            sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, removedPackage,
15676                    extras, 0, null, null, null);
15677            sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, removedPackage,
15678                    extras, 0, null, null, null);
15679            sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null,
15680                    null, 0, removedPackage, null, null);
15681        }
15682
15683        private void sendPackageRemovedBroadcastInternal(boolean killApp) {
15684            Bundle extras = new Bundle(2);
15685            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0  ? removedAppId : uid);
15686            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, dataRemoved);
15687            extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, !killApp);
15688            if (isUpdate || isRemovedPackageSystemUpdate) {
15689                extras.putBoolean(Intent.EXTRA_REPLACING, true);
15690            }
15691            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
15692            if (removedPackage != null) {
15693                sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
15694                        extras, 0, null, null, removedUsers);
15695                if (dataRemoved && !isRemovedPackageSystemUpdate) {
15696                    sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED,
15697                            removedPackage, extras, 0, null, null, removedUsers);
15698                }
15699            }
15700            if (removedAppId >= 0) {
15701                sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, 0, null, null,
15702                        removedUsers);
15703            }
15704        }
15705    }
15706
15707    /*
15708     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
15709     * flag is not set, the data directory is removed as well.
15710     * make sure this flag is set for partially installed apps. If not its meaningless to
15711     * delete a partially installed application.
15712     */
15713    private void removePackageDataLIF(PackageSetting ps, int[] allUserHandles,
15714            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
15715        String packageName = ps.name;
15716        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
15717        // Retrieve object to delete permissions for shared user later on
15718        final PackageParser.Package deletedPkg;
15719        final PackageSetting deletedPs;
15720        // reader
15721        synchronized (mPackages) {
15722            deletedPkg = mPackages.get(packageName);
15723            deletedPs = mSettings.mPackages.get(packageName);
15724            if (outInfo != null) {
15725                outInfo.removedPackage = packageName;
15726                outInfo.removedUsers = deletedPs != null
15727                        ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true)
15728                        : null;
15729            }
15730        }
15731
15732        removePackageLI(ps, (flags & REMOVE_CHATTY) != 0);
15733
15734        if ((flags & PackageManager.DELETE_KEEP_DATA) == 0) {
15735            final PackageParser.Package resolvedPkg;
15736            if (deletedPkg != null) {
15737                resolvedPkg = deletedPkg;
15738            } else {
15739                // We don't have a parsed package when it lives on an ejected
15740                // adopted storage device, so fake something together
15741                resolvedPkg = new PackageParser.Package(ps.name);
15742                resolvedPkg.setVolumeUuid(ps.volumeUuid);
15743            }
15744            destroyAppDataLIF(resolvedPkg, UserHandle.USER_ALL,
15745                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
15746            destroyAppProfilesLIF(resolvedPkg, UserHandle.USER_ALL);
15747            if (outInfo != null) {
15748                outInfo.dataRemoved = true;
15749            }
15750            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
15751        }
15752
15753        // writer
15754        synchronized (mPackages) {
15755            if (deletedPs != null) {
15756                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
15757                    clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL);
15758                    clearDefaultBrowserIfNeeded(packageName);
15759                    if (outInfo != null) {
15760                        mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
15761                        outInfo.removedAppId = mSettings.removePackageLPw(packageName);
15762                    }
15763                    updatePermissionsLPw(deletedPs.name, null, 0);
15764                    if (deletedPs.sharedUser != null) {
15765                        // Remove permissions associated with package. Since runtime
15766                        // permissions are per user we have to kill the removed package
15767                        // or packages running under the shared user of the removed
15768                        // package if revoking the permissions requested only by the removed
15769                        // package is successful and this causes a change in gids.
15770                        for (int userId : UserManagerService.getInstance().getUserIds()) {
15771                            final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs,
15772                                    userId);
15773                            if (userIdToKill == UserHandle.USER_ALL
15774                                    || userIdToKill >= UserHandle.USER_SYSTEM) {
15775                                // If gids changed for this user, kill all affected packages.
15776                                mHandler.post(new Runnable() {
15777                                    @Override
15778                                    public void run() {
15779                                        // This has to happen with no lock held.
15780                                        killApplication(deletedPs.name, deletedPs.appId,
15781                                                KILL_APP_REASON_GIDS_CHANGED);
15782                                    }
15783                                });
15784                                break;
15785                            }
15786                        }
15787                    }
15788                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
15789                }
15790                // make sure to preserve per-user disabled state if this removal was just
15791                // a downgrade of a system app to the factory package
15792                if (allUserHandles != null && outInfo != null && outInfo.origUsers != null) {
15793                    if (DEBUG_REMOVE) {
15794                        Slog.d(TAG, "Propagating install state across downgrade");
15795                    }
15796                    for (int userId : allUserHandles) {
15797                        final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
15798                        if (DEBUG_REMOVE) {
15799                            Slog.d(TAG, "    user " + userId + " => " + installed);
15800                        }
15801                        ps.setInstalled(installed, userId);
15802                    }
15803                }
15804            }
15805            // can downgrade to reader
15806            if (writeSettings) {
15807                // Save settings now
15808                mSettings.writeLPr();
15809            }
15810        }
15811        if (outInfo != null) {
15812            // A user ID was deleted here. Go through all users and remove it
15813            // from KeyStore.
15814            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId);
15815        }
15816    }
15817
15818    static boolean locationIsPrivileged(File path) {
15819        try {
15820            final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
15821                    .getCanonicalPath();
15822            final String privilegedAppVendorDir = new File(Environment.getVendorDirectory(), "priv-app")
15823                    .getCanonicalPath();
15824            return (path.getCanonicalPath().startsWith(privilegedAppDir)
15825                    || path.getCanonicalPath().startsWith(privilegedAppVendorDir));
15826        } catch (IOException e) {
15827            Slog.e(TAG, "Unable to access code path " + path);
15828        }
15829        return false;
15830    }
15831
15832    /*
15833     * Tries to delete system package.
15834     */
15835    private boolean deleteSystemPackageLIF(PackageParser.Package deletedPkg,
15836            PackageSetting deletedPs, int[] allUserHandles, int flags, PackageRemovedInfo outInfo,
15837            boolean writeSettings) {
15838        if (deletedPs.parentPackageName != null) {
15839            Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName);
15840            return false;
15841        }
15842
15843        final boolean applyUserRestrictions
15844                = (allUserHandles != null) && (outInfo.origUsers != null);
15845        final PackageSetting disabledPs;
15846        // Confirm if the system package has been updated
15847        // An updated system app can be deleted. This will also have to restore
15848        // the system pkg from system partition
15849        // reader
15850        synchronized (mPackages) {
15851            disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPs.name);
15852        }
15853
15854        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName
15855                + " disabledPs=" + disabledPs);
15856
15857        if (disabledPs == null) {
15858            Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName);
15859            return false;
15860        } else if (DEBUG_REMOVE) {
15861            Slog.d(TAG, "Deleting system pkg from data partition");
15862        }
15863
15864        if (DEBUG_REMOVE) {
15865            if (applyUserRestrictions) {
15866                Slog.d(TAG, "Remembering install states:");
15867                for (int userId : allUserHandles) {
15868                    final boolean finstalled = ArrayUtils.contains(outInfo.origUsers, userId);
15869                    Slog.d(TAG, "   u=" + userId + " inst=" + finstalled);
15870                }
15871            }
15872        }
15873
15874        // Delete the updated package
15875        outInfo.isRemovedPackageSystemUpdate = true;
15876        if (outInfo.removedChildPackages != null) {
15877            final int childCount = (deletedPs.childPackageNames != null)
15878                    ? deletedPs.childPackageNames.size() : 0;
15879            for (int i = 0; i < childCount; i++) {
15880                String childPackageName = deletedPs.childPackageNames.get(i);
15881                if (disabledPs.childPackageNames != null && disabledPs.childPackageNames
15882                        .contains(childPackageName)) {
15883                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
15884                            childPackageName);
15885                    if (childInfo != null) {
15886                        childInfo.isRemovedPackageSystemUpdate = true;
15887                    }
15888                }
15889            }
15890        }
15891
15892        if (disabledPs.versionCode < deletedPs.versionCode) {
15893            // Delete data for downgrades
15894            flags &= ~PackageManager.DELETE_KEEP_DATA;
15895        } else {
15896            // Preserve data by setting flag
15897            flags |= PackageManager.DELETE_KEEP_DATA;
15898        }
15899
15900        boolean ret = deleteInstalledPackageLIF(deletedPs, true, flags, allUserHandles,
15901                outInfo, writeSettings, disabledPs.pkg);
15902        if (!ret) {
15903            return false;
15904        }
15905
15906        // writer
15907        synchronized (mPackages) {
15908            // Reinstate the old system package
15909            enableSystemPackageLPw(disabledPs.pkg);
15910            // Remove any native libraries from the upgraded package.
15911            removeNativeBinariesLI(deletedPs);
15912        }
15913
15914        // Install the system package
15915        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
15916        int parseFlags = mDefParseFlags
15917                | PackageParser.PARSE_MUST_BE_APK
15918                | PackageParser.PARSE_IS_SYSTEM
15919                | PackageParser.PARSE_IS_SYSTEM_DIR;
15920        if (locationIsPrivileged(disabledPs.codePath)) {
15921            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
15922        }
15923
15924        final PackageParser.Package newPkg;
15925        try {
15926            newPkg = scanPackageTracedLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null);
15927        } catch (PackageManagerException e) {
15928            Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": "
15929                    + e.getMessage());
15930            return false;
15931        }
15932
15933        prepareAppDataAfterInstallLIF(newPkg);
15934
15935        // writer
15936        synchronized (mPackages) {
15937            PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
15938
15939            // Propagate the permissions state as we do not want to drop on the floor
15940            // runtime permissions. The update permissions method below will take
15941            // care of removing obsolete permissions and grant install permissions.
15942            ps.getPermissionsState().copyFrom(deletedPs.getPermissionsState());
15943            updatePermissionsLPw(newPkg.packageName, newPkg,
15944                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
15945
15946            if (applyUserRestrictions) {
15947                if (DEBUG_REMOVE) {
15948                    Slog.d(TAG, "Propagating install state across reinstall");
15949                }
15950                for (int userId : allUserHandles) {
15951                    final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
15952                    if (DEBUG_REMOVE) {
15953                        Slog.d(TAG, "    user " + userId + " => " + installed);
15954                    }
15955                    ps.setInstalled(installed, userId);
15956
15957                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
15958                }
15959                // Regardless of writeSettings we need to ensure that this restriction
15960                // state propagation is persisted
15961                mSettings.writeAllUsersPackageRestrictionsLPr();
15962            }
15963            // can downgrade to reader here
15964            if (writeSettings) {
15965                mSettings.writeLPr();
15966            }
15967        }
15968        return true;
15969    }
15970
15971    private boolean deleteInstalledPackageLIF(PackageSetting ps,
15972            boolean deleteCodeAndResources, int flags, int[] allUserHandles,
15973            PackageRemovedInfo outInfo, boolean writeSettings,
15974            PackageParser.Package replacingPackage) {
15975        synchronized (mPackages) {
15976            if (outInfo != null) {
15977                outInfo.uid = ps.appId;
15978            }
15979
15980            if (outInfo != null && outInfo.removedChildPackages != null) {
15981                final int childCount = (ps.childPackageNames != null)
15982                        ? ps.childPackageNames.size() : 0;
15983                for (int i = 0; i < childCount; i++) {
15984                    String childPackageName = ps.childPackageNames.get(i);
15985                    PackageSetting childPs = mSettings.mPackages.get(childPackageName);
15986                    if (childPs == null) {
15987                        return false;
15988                    }
15989                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
15990                            childPackageName);
15991                    if (childInfo != null) {
15992                        childInfo.uid = childPs.appId;
15993                    }
15994                }
15995            }
15996        }
15997
15998        // Delete package data from internal structures and also remove data if flag is set
15999        removePackageDataLIF(ps, allUserHandles, outInfo, flags, writeSettings);
16000
16001        // Delete the child packages data
16002        final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
16003        for (int i = 0; i < childCount; i++) {
16004            PackageSetting childPs;
16005            synchronized (mPackages) {
16006                childPs = mSettings.peekPackageLPr(ps.childPackageNames.get(i));
16007            }
16008            if (childPs != null) {
16009                PackageRemovedInfo childOutInfo = (outInfo != null
16010                        && outInfo.removedChildPackages != null)
16011                        ? outInfo.removedChildPackages.get(childPs.name) : null;
16012                final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0
16013                        && (replacingPackage != null
16014                        && !replacingPackage.hasChildPackage(childPs.name))
16015                        ? flags & ~DELETE_KEEP_DATA : flags;
16016                removePackageDataLIF(childPs, allUserHandles, childOutInfo,
16017                        deleteFlags, writeSettings);
16018            }
16019        }
16020
16021        // Delete application code and resources only for parent packages
16022        if (ps.parentPackageName == null) {
16023            if (deleteCodeAndResources && (outInfo != null)) {
16024                outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
16025                        ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
16026                if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
16027            }
16028        }
16029
16030        return true;
16031    }
16032
16033    @Override
16034    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
16035            int userId) {
16036        mContext.enforceCallingOrSelfPermission(
16037                android.Manifest.permission.DELETE_PACKAGES, null);
16038        synchronized (mPackages) {
16039            PackageSetting ps = mSettings.mPackages.get(packageName);
16040            if (ps == null) {
16041                Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName);
16042                return false;
16043            }
16044            if (!ps.getInstalled(userId)) {
16045                // Can't block uninstall for an app that is not installed or enabled.
16046                Log.i(TAG, "Package not installed in set block uninstall " + packageName);
16047                return false;
16048            }
16049            ps.setBlockUninstall(blockUninstall, userId);
16050            mSettings.writePackageRestrictionsLPr(userId);
16051        }
16052        return true;
16053    }
16054
16055    @Override
16056    public boolean getBlockUninstallForUser(String packageName, int userId) {
16057        synchronized (mPackages) {
16058            PackageSetting ps = mSettings.mPackages.get(packageName);
16059            if (ps == null) {
16060                Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName);
16061                return false;
16062            }
16063            return ps.getBlockUninstall(userId);
16064        }
16065    }
16066
16067    @Override
16068    public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) {
16069        int callingUid = Binder.getCallingUid();
16070        if (callingUid != Process.SYSTEM_UID && callingUid != Process.ROOT_UID) {
16071            throw new SecurityException(
16072                    "setRequiredForSystemUser can only be run by the system or root");
16073        }
16074        synchronized (mPackages) {
16075            PackageSetting ps = mSettings.mPackages.get(packageName);
16076            if (ps == null) {
16077                Log.w(TAG, "Package doesn't exist: " + packageName);
16078                return false;
16079            }
16080            if (systemUserApp) {
16081                ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
16082            } else {
16083                ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
16084            }
16085            mSettings.writeLPr();
16086        }
16087        return true;
16088    }
16089
16090    /*
16091     * This method handles package deletion in general
16092     */
16093    private boolean deletePackageLIF(String packageName, UserHandle user,
16094            boolean deleteCodeAndResources, int[] allUserHandles, int flags,
16095            PackageRemovedInfo outInfo, boolean writeSettings,
16096            PackageParser.Package replacingPackage) {
16097        if (packageName == null) {
16098            Slog.w(TAG, "Attempt to delete null packageName.");
16099            return false;
16100        }
16101
16102        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
16103
16104        PackageSetting ps;
16105
16106        synchronized (mPackages) {
16107            ps = mSettings.mPackages.get(packageName);
16108            if (ps == null) {
16109                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
16110                return false;
16111            }
16112
16113            if (ps.parentPackageName != null && (!isSystemApp(ps)
16114                    || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) {
16115                if (DEBUG_REMOVE) {
16116                    Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:"
16117                            + ((user == null) ? UserHandle.USER_ALL : user));
16118                }
16119                final int removedUserId = (user != null) ? user.getIdentifier()
16120                        : UserHandle.USER_ALL;
16121                if (!clearPackageStateForUserLIF(ps, removedUserId, outInfo)) {
16122                    return false;
16123                }
16124                markPackageUninstalledForUserLPw(ps, user);
16125                scheduleWritePackageRestrictionsLocked(user);
16126                return true;
16127            }
16128        }
16129
16130        if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
16131                && user.getIdentifier() != UserHandle.USER_ALL)) {
16132            // The caller is asking that the package only be deleted for a single
16133            // user.  To do this, we just mark its uninstalled state and delete
16134            // its data. If this is a system app, we only allow this to happen if
16135            // they have set the special DELETE_SYSTEM_APP which requests different
16136            // semantics than normal for uninstalling system apps.
16137            markPackageUninstalledForUserLPw(ps, user);
16138
16139            if (!isSystemApp(ps)) {
16140                // Do not uninstall the APK if an app should be cached
16141                boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName);
16142                if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) {
16143                    // Other user still have this package installed, so all
16144                    // we need to do is clear this user's data and save that
16145                    // it is uninstalled.
16146                    if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
16147                    if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
16148                        return false;
16149                    }
16150                    scheduleWritePackageRestrictionsLocked(user);
16151                    return true;
16152                } else {
16153                    // We need to set it back to 'installed' so the uninstall
16154                    // broadcasts will be sent correctly.
16155                    if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
16156                    ps.setInstalled(true, user.getIdentifier());
16157                }
16158            } else {
16159                // This is a system app, so we assume that the
16160                // other users still have this package installed, so all
16161                // we need to do is clear this user's data and save that
16162                // it is uninstalled.
16163                if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
16164                if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
16165                    return false;
16166                }
16167                scheduleWritePackageRestrictionsLocked(user);
16168                return true;
16169            }
16170        }
16171
16172        // If we are deleting a composite package for all users, keep track
16173        // of result for each child.
16174        if (ps.childPackageNames != null && outInfo != null) {
16175            synchronized (mPackages) {
16176                final int childCount = ps.childPackageNames.size();
16177                outInfo.removedChildPackages = new ArrayMap<>(childCount);
16178                for (int i = 0; i < childCount; i++) {
16179                    String childPackageName = ps.childPackageNames.get(i);
16180                    PackageRemovedInfo childInfo = new PackageRemovedInfo();
16181                    childInfo.removedPackage = childPackageName;
16182                    outInfo.removedChildPackages.put(childPackageName, childInfo);
16183                    PackageSetting childPs = mSettings.peekPackageLPr(childPackageName);
16184                    if (childPs != null) {
16185                        childInfo.origUsers = childPs.queryInstalledUsers(allUserHandles, true);
16186                    }
16187                }
16188            }
16189        }
16190
16191        boolean ret = false;
16192        if (isSystemApp(ps)) {
16193            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name);
16194            // When an updated system application is deleted we delete the existing resources
16195            // as well and fall back to existing code in system partition
16196            ret = deleteSystemPackageLIF(ps.pkg, ps, allUserHandles, flags, outInfo, writeSettings);
16197        } else {
16198            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name);
16199            ret = deleteInstalledPackageLIF(ps, deleteCodeAndResources, flags, allUserHandles,
16200                    outInfo, writeSettings, replacingPackage);
16201        }
16202
16203        // Take a note whether we deleted the package for all users
16204        if (outInfo != null) {
16205            outInfo.removedForAllUsers = mPackages.get(ps.name) == null;
16206            if (outInfo.removedChildPackages != null) {
16207                synchronized (mPackages) {
16208                    final int childCount = outInfo.removedChildPackages.size();
16209                    for (int i = 0; i < childCount; i++) {
16210                        PackageRemovedInfo childInfo = outInfo.removedChildPackages.valueAt(i);
16211                        if (childInfo != null) {
16212                            childInfo.removedForAllUsers = mPackages.get(
16213                                    childInfo.removedPackage) == null;
16214                        }
16215                    }
16216                }
16217            }
16218            // If we uninstalled an update to a system app there may be some
16219            // child packages that appeared as they are declared in the system
16220            // app but were not declared in the update.
16221            if (isSystemApp(ps)) {
16222                synchronized (mPackages) {
16223                    PackageSetting updatedPs = mSettings.peekPackageLPr(ps.name);
16224                    final int childCount = (updatedPs.childPackageNames != null)
16225                            ? updatedPs.childPackageNames.size() : 0;
16226                    for (int i = 0; i < childCount; i++) {
16227                        String childPackageName = updatedPs.childPackageNames.get(i);
16228                        if (outInfo.removedChildPackages == null
16229                                || outInfo.removedChildPackages.indexOfKey(childPackageName) < 0) {
16230                            PackageSetting childPs = mSettings.peekPackageLPr(childPackageName);
16231                            if (childPs == null) {
16232                                continue;
16233                            }
16234                            PackageInstalledInfo installRes = new PackageInstalledInfo();
16235                            installRes.name = childPackageName;
16236                            installRes.newUsers = childPs.queryInstalledUsers(allUserHandles, true);
16237                            installRes.pkg = mPackages.get(childPackageName);
16238                            installRes.uid = childPs.pkg.applicationInfo.uid;
16239                            if (outInfo.appearedChildPackages == null) {
16240                                outInfo.appearedChildPackages = new ArrayMap<>();
16241                            }
16242                            outInfo.appearedChildPackages.put(childPackageName, installRes);
16243                        }
16244                    }
16245                }
16246            }
16247        }
16248
16249        return ret;
16250    }
16251
16252    private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) {
16253        final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL)
16254                ? sUserManager.getUserIds() : new int[] {user.getIdentifier()};
16255        for (int nextUserId : userIds) {
16256            if (DEBUG_REMOVE) {
16257                Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId);
16258            }
16259            ps.setUserState(nextUserId, 0, COMPONENT_ENABLED_STATE_DEFAULT,
16260                    false /*installed*/, true /*stopped*/, true /*notLaunched*/,
16261                    false /*hidden*/, false /*suspended*/, null, null, null,
16262                    false /*blockUninstall*/,
16263                    ps.readUserState(nextUserId).domainVerificationStatus, 0);
16264        }
16265    }
16266
16267    private boolean clearPackageStateForUserLIF(PackageSetting ps, int userId,
16268            PackageRemovedInfo outInfo) {
16269        final PackageParser.Package pkg;
16270        synchronized (mPackages) {
16271            pkg = mPackages.get(ps.name);
16272        }
16273
16274        final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds()
16275                : new int[] {userId};
16276        for (int nextUserId : userIds) {
16277            if (DEBUG_REMOVE) {
16278                Slog.d(TAG, "Updating package:" + ps.name + " install state for user:"
16279                        + nextUserId);
16280            }
16281
16282            destroyAppDataLIF(pkg, userId,
16283                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
16284            destroyAppProfilesLIF(pkg, userId);
16285            removeKeystoreDataIfNeeded(nextUserId, ps.appId);
16286            schedulePackageCleaning(ps.name, nextUserId, false);
16287            synchronized (mPackages) {
16288                if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) {
16289                    scheduleWritePackageRestrictionsLocked(nextUserId);
16290                }
16291                resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId);
16292            }
16293        }
16294
16295        if (outInfo != null) {
16296            outInfo.removedPackage = ps.name;
16297            outInfo.removedAppId = ps.appId;
16298            outInfo.removedUsers = userIds;
16299        }
16300
16301        return true;
16302    }
16303
16304    private final class ClearStorageConnection implements ServiceConnection {
16305        IMediaContainerService mContainerService;
16306
16307        @Override
16308        public void onServiceConnected(ComponentName name, IBinder service) {
16309            synchronized (this) {
16310                mContainerService = IMediaContainerService.Stub.asInterface(service);
16311                notifyAll();
16312            }
16313        }
16314
16315        @Override
16316        public void onServiceDisconnected(ComponentName name) {
16317        }
16318    }
16319
16320    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
16321        if (DEFAULT_CONTAINER_PACKAGE.equals(packageName)) return;
16322
16323        final boolean mounted;
16324        if (Environment.isExternalStorageEmulated()) {
16325            mounted = true;
16326        } else {
16327            final String status = Environment.getExternalStorageState();
16328
16329            mounted = status.equals(Environment.MEDIA_MOUNTED)
16330                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
16331        }
16332
16333        if (!mounted) {
16334            return;
16335        }
16336
16337        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
16338        int[] users;
16339        if (userId == UserHandle.USER_ALL) {
16340            users = sUserManager.getUserIds();
16341        } else {
16342            users = new int[] { userId };
16343        }
16344        final ClearStorageConnection conn = new ClearStorageConnection();
16345        if (mContext.bindServiceAsUser(
16346                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
16347            try {
16348                for (int curUser : users) {
16349                    long timeout = SystemClock.uptimeMillis() + 5000;
16350                    synchronized (conn) {
16351                        long now;
16352                        while (conn.mContainerService == null &&
16353                                (now = SystemClock.uptimeMillis()) < timeout) {
16354                            try {
16355                                conn.wait(timeout - now);
16356                            } catch (InterruptedException e) {
16357                            }
16358                        }
16359                    }
16360                    if (conn.mContainerService == null) {
16361                        return;
16362                    }
16363
16364                    final UserEnvironment userEnv = new UserEnvironment(curUser);
16365                    clearDirectory(conn.mContainerService,
16366                            userEnv.buildExternalStorageAppCacheDirs(packageName));
16367                    if (allData) {
16368                        clearDirectory(conn.mContainerService,
16369                                userEnv.buildExternalStorageAppDataDirs(packageName));
16370                        clearDirectory(conn.mContainerService,
16371                                userEnv.buildExternalStorageAppMediaDirs(packageName));
16372                    }
16373                }
16374            } finally {
16375                mContext.unbindService(conn);
16376            }
16377        }
16378    }
16379
16380    @Override
16381    public void clearApplicationProfileData(String packageName) {
16382        enforceSystemOrRoot("Only the system can clear all profile data");
16383
16384        final PackageParser.Package pkg;
16385        synchronized (mPackages) {
16386            pkg = mPackages.get(packageName);
16387        }
16388
16389        try (PackageFreezer freezer = freezePackage(packageName, "clearApplicationProfileData")) {
16390            synchronized (mInstallLock) {
16391                clearAppProfilesLIF(pkg, UserHandle.USER_ALL);
16392                destroyAppReferenceProfileLeafLIF(pkg, UserHandle.USER_ALL,
16393                        true /* removeBaseMarker */);
16394            }
16395        }
16396    }
16397
16398    @Override
16399    public void clearApplicationUserData(final String packageName,
16400            final IPackageDataObserver observer, final int userId) {
16401        mContext.enforceCallingOrSelfPermission(
16402                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
16403
16404        enforceCrossUserPermission(Binder.getCallingUid(), userId,
16405                true /* requireFullPermission */, false /* checkShell */, "clear application data");
16406
16407        if (mProtectedPackages.canPackageBeWiped(userId, packageName)) {
16408            throw new SecurityException("Cannot clear data for a device owner or a profile owner");
16409        }
16410        // Queue up an async operation since the package deletion may take a little while.
16411        mHandler.post(new Runnable() {
16412            public void run() {
16413                mHandler.removeCallbacks(this);
16414                final boolean succeeded;
16415                try (PackageFreezer freezer = freezePackage(packageName,
16416                        "clearApplicationUserData")) {
16417                    synchronized (mInstallLock) {
16418                        succeeded = clearApplicationUserDataLIF(packageName, userId);
16419                    }
16420                    clearExternalStorageDataSync(packageName, userId, true);
16421                }
16422                if (succeeded) {
16423                    // invoke DeviceStorageMonitor's update method to clear any notifications
16424                    DeviceStorageMonitorInternal dsm = LocalServices
16425                            .getService(DeviceStorageMonitorInternal.class);
16426                    if (dsm != null) {
16427                        dsm.checkMemory();
16428                    }
16429                }
16430                if(observer != null) {
16431                    try {
16432                        observer.onRemoveCompleted(packageName, succeeded);
16433                    } catch (RemoteException e) {
16434                        Log.i(TAG, "Observer no longer exists.");
16435                    }
16436                } //end if observer
16437            } //end run
16438        });
16439    }
16440
16441    private boolean clearApplicationUserDataLIF(String packageName, int userId) {
16442        if (packageName == null) {
16443            Slog.w(TAG, "Attempt to delete null packageName.");
16444            return false;
16445        }
16446
16447        // Try finding details about the requested package
16448        PackageParser.Package pkg;
16449        synchronized (mPackages) {
16450            pkg = mPackages.get(packageName);
16451            if (pkg == null) {
16452                final PackageSetting ps = mSettings.mPackages.get(packageName);
16453                if (ps != null) {
16454                    pkg = ps.pkg;
16455                }
16456            }
16457
16458            if (pkg == null) {
16459                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
16460                return false;
16461            }
16462
16463            PackageSetting ps = (PackageSetting) pkg.mExtras;
16464            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
16465        }
16466
16467        clearAppDataLIF(pkg, userId,
16468                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
16469
16470        final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
16471        removeKeystoreDataIfNeeded(userId, appId);
16472
16473        UserManagerInternal umInternal = getUserManagerInternal();
16474        final int flags;
16475        if (umInternal.isUserUnlockingOrUnlocked(userId)) {
16476            flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
16477        } else if (umInternal.isUserRunning(userId)) {
16478            flags = StorageManager.FLAG_STORAGE_DE;
16479        } else {
16480            flags = 0;
16481        }
16482        prepareAppDataContentsLIF(pkg, userId, flags);
16483
16484        return true;
16485    }
16486
16487    /**
16488     * Reverts user permission state changes (permissions and flags) in
16489     * all packages for a given user.
16490     *
16491     * @param userId The device user for which to do a reset.
16492     */
16493    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) {
16494        final int packageCount = mPackages.size();
16495        for (int i = 0; i < packageCount; i++) {
16496            PackageParser.Package pkg = mPackages.valueAt(i);
16497            PackageSetting ps = (PackageSetting) pkg.mExtras;
16498            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
16499        }
16500    }
16501
16502    private void resetNetworkPolicies(int userId) {
16503        LocalServices.getService(NetworkPolicyManagerInternal.class).resetUserState(userId);
16504    }
16505
16506    /**
16507     * Reverts user permission state changes (permissions and flags).
16508     *
16509     * @param ps The package for which to reset.
16510     * @param userId The device user for which to do a reset.
16511     */
16512    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(
16513            final PackageSetting ps, final int userId) {
16514        if (ps.pkg == null) {
16515            return;
16516        }
16517
16518        // These are flags that can change base on user actions.
16519        final int userSettableMask = FLAG_PERMISSION_USER_SET
16520                | FLAG_PERMISSION_USER_FIXED
16521                | FLAG_PERMISSION_REVOKE_ON_UPGRADE
16522                | FLAG_PERMISSION_REVIEW_REQUIRED;
16523
16524        final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED
16525                | FLAG_PERMISSION_POLICY_FIXED;
16526
16527        boolean writeInstallPermissions = false;
16528        boolean writeRuntimePermissions = false;
16529
16530        final int permissionCount = ps.pkg.requestedPermissions.size();
16531        for (int i = 0; i < permissionCount; i++) {
16532            String permission = ps.pkg.requestedPermissions.get(i);
16533
16534            BasePermission bp = mSettings.mPermissions.get(permission);
16535            if (bp == null) {
16536                continue;
16537            }
16538
16539            // If shared user we just reset the state to which only this app contributed.
16540            if (ps.sharedUser != null) {
16541                boolean used = false;
16542                final int packageCount = ps.sharedUser.packages.size();
16543                for (int j = 0; j < packageCount; j++) {
16544                    PackageSetting pkg = ps.sharedUser.packages.valueAt(j);
16545                    if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName)
16546                            && pkg.pkg.requestedPermissions.contains(permission)) {
16547                        used = true;
16548                        break;
16549                    }
16550                }
16551                if (used) {
16552                    continue;
16553                }
16554            }
16555
16556            PermissionsState permissionsState = ps.getPermissionsState();
16557
16558            final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId);
16559
16560            // Always clear the user settable flags.
16561            final boolean hasInstallState = permissionsState.getInstallPermissionState(
16562                    bp.name) != null;
16563            // If permission review is enabled and this is a legacy app, mark the
16564            // permission as requiring a review as this is the initial state.
16565            int flags = 0;
16566            if (Build.PERMISSIONS_REVIEW_REQUIRED
16567                    && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
16568                flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
16569            }
16570            if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) {
16571                if (hasInstallState) {
16572                    writeInstallPermissions = true;
16573                } else {
16574                    writeRuntimePermissions = true;
16575                }
16576            }
16577
16578            // Below is only runtime permission handling.
16579            if (!bp.isRuntime()) {
16580                continue;
16581            }
16582
16583            // Never clobber system or policy.
16584            if ((oldFlags & policyOrSystemFlags) != 0) {
16585                continue;
16586            }
16587
16588            // If this permission was granted by default, make sure it is.
16589            if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) {
16590                if (permissionsState.grantRuntimePermission(bp, userId)
16591                        != PERMISSION_OPERATION_FAILURE) {
16592                    writeRuntimePermissions = true;
16593                }
16594            // If permission review is enabled the permissions for a legacy apps
16595            // are represented as constantly granted runtime ones, so don't revoke.
16596            } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
16597                // Otherwise, reset the permission.
16598                final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId);
16599                switch (revokeResult) {
16600                    case PERMISSION_OPERATION_SUCCESS:
16601                    case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
16602                        writeRuntimePermissions = true;
16603                        final int appId = ps.appId;
16604                        mHandler.post(new Runnable() {
16605                            @Override
16606                            public void run() {
16607                                killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
16608                            }
16609                        });
16610                    } break;
16611                }
16612            }
16613        }
16614
16615        // Synchronously write as we are taking permissions away.
16616        if (writeRuntimePermissions) {
16617            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
16618        }
16619
16620        // Synchronously write as we are taking permissions away.
16621        if (writeInstallPermissions) {
16622            mSettings.writeLPr();
16623        }
16624    }
16625
16626    /**
16627     * Remove entries from the keystore daemon. Will only remove it if the
16628     * {@code appId} is valid.
16629     */
16630    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
16631        if (appId < 0) {
16632            return;
16633        }
16634
16635        final KeyStore keyStore = KeyStore.getInstance();
16636        if (keyStore != null) {
16637            if (userId == UserHandle.USER_ALL) {
16638                for (final int individual : sUserManager.getUserIds()) {
16639                    keyStore.clearUid(UserHandle.getUid(individual, appId));
16640                }
16641            } else {
16642                keyStore.clearUid(UserHandle.getUid(userId, appId));
16643            }
16644        } else {
16645            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
16646        }
16647    }
16648
16649    @Override
16650    public void deleteApplicationCacheFiles(final String packageName,
16651            final IPackageDataObserver observer) {
16652        final int userId = UserHandle.getCallingUserId();
16653        deleteApplicationCacheFilesAsUser(packageName, userId, observer);
16654    }
16655
16656    @Override
16657    public void deleteApplicationCacheFilesAsUser(final String packageName, final int userId,
16658            final IPackageDataObserver observer) {
16659        mContext.enforceCallingOrSelfPermission(
16660                android.Manifest.permission.DELETE_CACHE_FILES, null);
16661        enforceCrossUserPermission(Binder.getCallingUid(), userId,
16662                /* requireFullPermission= */ true, /* checkShell= */ false,
16663                "delete application cache files");
16664
16665        final PackageParser.Package pkg;
16666        synchronized (mPackages) {
16667            pkg = mPackages.get(packageName);
16668        }
16669
16670        // Queue up an async operation since the package deletion may take a little while.
16671        mHandler.post(new Runnable() {
16672            public void run() {
16673                synchronized (mInstallLock) {
16674                    final int flags = StorageManager.FLAG_STORAGE_DE
16675                            | StorageManager.FLAG_STORAGE_CE;
16676                    // We're only clearing cache files, so we don't care if the
16677                    // app is unfrozen and still able to run
16678                    clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CACHE_ONLY);
16679                    clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
16680                }
16681                clearExternalStorageDataSync(packageName, userId, false);
16682                if (observer != null) {
16683                    try {
16684                        observer.onRemoveCompleted(packageName, true);
16685                    } catch (RemoteException e) {
16686                        Log.i(TAG, "Observer no longer exists.");
16687                    }
16688                }
16689            }
16690        });
16691    }
16692
16693    @Override
16694    public void getPackageSizeInfo(final String packageName, int userHandle,
16695            final IPackageStatsObserver observer) {
16696        mContext.enforceCallingOrSelfPermission(
16697                android.Manifest.permission.GET_PACKAGE_SIZE, null);
16698        if (packageName == null) {
16699            throw new IllegalArgumentException("Attempt to get size of null packageName");
16700        }
16701
16702        PackageStats stats = new PackageStats(packageName, userHandle);
16703
16704        /*
16705         * Queue up an async operation since the package measurement may take a
16706         * little while.
16707         */
16708        Message msg = mHandler.obtainMessage(INIT_COPY);
16709        msg.obj = new MeasureParams(stats, observer);
16710        mHandler.sendMessage(msg);
16711    }
16712
16713    private boolean getPackageSizeInfoLI(String packageName, int userId, PackageStats stats) {
16714        final PackageSetting ps;
16715        synchronized (mPackages) {
16716            ps = mSettings.mPackages.get(packageName);
16717            if (ps == null) {
16718                Slog.w(TAG, "Failed to find settings for " + packageName);
16719                return false;
16720            }
16721        }
16722        try {
16723            mInstaller.getAppSize(ps.volumeUuid, packageName, userId,
16724                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE,
16725                    ps.getCeDataInode(userId), ps.codePathString, stats);
16726        } catch (InstallerException e) {
16727            Slog.w(TAG, String.valueOf(e));
16728            return false;
16729        }
16730
16731        // For now, ignore code size of packages on system partition
16732        if (isSystemApp(ps) && !isUpdatedSystemApp(ps)) {
16733            stats.codeSize = 0;
16734        }
16735
16736        return true;
16737    }
16738
16739    private int getUidTargetSdkVersionLockedLPr(int uid) {
16740        Object obj = mSettings.getUserIdLPr(uid);
16741        if (obj instanceof SharedUserSetting) {
16742            final SharedUserSetting sus = (SharedUserSetting) obj;
16743            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
16744            final Iterator<PackageSetting> it = sus.packages.iterator();
16745            while (it.hasNext()) {
16746                final PackageSetting ps = it.next();
16747                if (ps.pkg != null) {
16748                    int v = ps.pkg.applicationInfo.targetSdkVersion;
16749                    if (v < vers) vers = v;
16750                }
16751            }
16752            return vers;
16753        } else if (obj instanceof PackageSetting) {
16754            final PackageSetting ps = (PackageSetting) obj;
16755            if (ps.pkg != null) {
16756                return ps.pkg.applicationInfo.targetSdkVersion;
16757            }
16758        }
16759        return Build.VERSION_CODES.CUR_DEVELOPMENT;
16760    }
16761
16762    @Override
16763    public void addPreferredActivity(IntentFilter filter, int match,
16764            ComponentName[] set, ComponentName activity, int userId) {
16765        addPreferredActivityInternal(filter, match, set, activity, true, userId,
16766                "Adding preferred");
16767    }
16768
16769    private void addPreferredActivityInternal(IntentFilter filter, int match,
16770            ComponentName[] set, ComponentName activity, boolean always, int userId,
16771            String opname) {
16772        // writer
16773        int callingUid = Binder.getCallingUid();
16774        enforceCrossUserPermission(callingUid, userId,
16775                true /* requireFullPermission */, false /* checkShell */, "add preferred activity");
16776        if (filter.countActions() == 0) {
16777            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
16778            return;
16779        }
16780        synchronized (mPackages) {
16781            if (mContext.checkCallingOrSelfPermission(
16782                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
16783                    != PackageManager.PERMISSION_GRANTED) {
16784                if (getUidTargetSdkVersionLockedLPr(callingUid)
16785                        < Build.VERSION_CODES.FROYO) {
16786                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
16787                            + callingUid);
16788                    return;
16789                }
16790                mContext.enforceCallingOrSelfPermission(
16791                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
16792            }
16793
16794            PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
16795            Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
16796                    + userId + ":");
16797            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
16798            pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
16799            scheduleWritePackageRestrictionsLocked(userId);
16800        }
16801    }
16802
16803    @Override
16804    public void replacePreferredActivity(IntentFilter filter, int match,
16805            ComponentName[] set, ComponentName activity, int userId) {
16806        if (filter.countActions() != 1) {
16807            throw new IllegalArgumentException(
16808                    "replacePreferredActivity expects filter to have only 1 action.");
16809        }
16810        if (filter.countDataAuthorities() != 0
16811                || filter.countDataPaths() != 0
16812                || filter.countDataSchemes() > 1
16813                || filter.countDataTypes() != 0) {
16814            throw new IllegalArgumentException(
16815                    "replacePreferredActivity expects filter to have no data authorities, " +
16816                    "paths, or types; and at most one scheme.");
16817        }
16818
16819        final int callingUid = Binder.getCallingUid();
16820        enforceCrossUserPermission(callingUid, userId,
16821                true /* requireFullPermission */, false /* checkShell */,
16822                "replace preferred activity");
16823        synchronized (mPackages) {
16824            if (mContext.checkCallingOrSelfPermission(
16825                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
16826                    != PackageManager.PERMISSION_GRANTED) {
16827                if (getUidTargetSdkVersionLockedLPr(callingUid)
16828                        < Build.VERSION_CODES.FROYO) {
16829                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
16830                            + Binder.getCallingUid());
16831                    return;
16832                }
16833                mContext.enforceCallingOrSelfPermission(
16834                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
16835            }
16836
16837            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
16838            if (pir != null) {
16839                // Get all of the existing entries that exactly match this filter.
16840                ArrayList<PreferredActivity> existing = pir.findFilters(filter);
16841                if (existing != null && existing.size() == 1) {
16842                    PreferredActivity cur = existing.get(0);
16843                    if (DEBUG_PREFERRED) {
16844                        Slog.i(TAG, "Checking replace of preferred:");
16845                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
16846                        if (!cur.mPref.mAlways) {
16847                            Slog.i(TAG, "  -- CUR; not mAlways!");
16848                        } else {
16849                            Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
16850                            Slog.i(TAG, "  -- CUR: mSet="
16851                                    + Arrays.toString(cur.mPref.mSetComponents));
16852                            Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
16853                            Slog.i(TAG, "  -- NEW: mMatch="
16854                                    + (match&IntentFilter.MATCH_CATEGORY_MASK));
16855                            Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
16856                            Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
16857                        }
16858                    }
16859                    if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
16860                            && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
16861                            && cur.mPref.sameSet(set)) {
16862                        // Setting the preferred activity to what it happens to be already
16863                        if (DEBUG_PREFERRED) {
16864                            Slog.i(TAG, "Replacing with same preferred activity "
16865                                    + cur.mPref.mShortComponent + " for user "
16866                                    + userId + ":");
16867                            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
16868                        }
16869                        return;
16870                    }
16871                }
16872
16873                if (existing != null) {
16874                    if (DEBUG_PREFERRED) {
16875                        Slog.i(TAG, existing.size() + " existing preferred matches for:");
16876                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
16877                    }
16878                    for (int i = 0; i < existing.size(); i++) {
16879                        PreferredActivity pa = existing.get(i);
16880                        if (DEBUG_PREFERRED) {
16881                            Slog.i(TAG, "Removing existing preferred activity "
16882                                    + pa.mPref.mComponent + ":");
16883                            pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
16884                        }
16885                        pir.removeFilter(pa);
16886                    }
16887                }
16888            }
16889            addPreferredActivityInternal(filter, match, set, activity, true, userId,
16890                    "Replacing preferred");
16891        }
16892    }
16893
16894    @Override
16895    public void clearPackagePreferredActivities(String packageName) {
16896        final int uid = Binder.getCallingUid();
16897        // writer
16898        synchronized (mPackages) {
16899            PackageParser.Package pkg = mPackages.get(packageName);
16900            if (pkg == null || pkg.applicationInfo.uid != uid) {
16901                if (mContext.checkCallingOrSelfPermission(
16902                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
16903                        != PackageManager.PERMISSION_GRANTED) {
16904                    if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid())
16905                            < Build.VERSION_CODES.FROYO) {
16906                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
16907                                + Binder.getCallingUid());
16908                        return;
16909                    }
16910                    mContext.enforceCallingOrSelfPermission(
16911                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
16912                }
16913            }
16914
16915            int user = UserHandle.getCallingUserId();
16916            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
16917                scheduleWritePackageRestrictionsLocked(user);
16918            }
16919        }
16920    }
16921
16922    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
16923    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
16924        ArrayList<PreferredActivity> removed = null;
16925        boolean changed = false;
16926        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
16927            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
16928            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
16929            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
16930                continue;
16931            }
16932            Iterator<PreferredActivity> it = pir.filterIterator();
16933            while (it.hasNext()) {
16934                PreferredActivity pa = it.next();
16935                // Mark entry for removal only if it matches the package name
16936                // and the entry is of type "always".
16937                if (packageName == null ||
16938                        (pa.mPref.mComponent.getPackageName().equals(packageName)
16939                                && pa.mPref.mAlways)) {
16940                    if (removed == null) {
16941                        removed = new ArrayList<PreferredActivity>();
16942                    }
16943                    removed.add(pa);
16944                }
16945            }
16946            if (removed != null) {
16947                for (int j=0; j<removed.size(); j++) {
16948                    PreferredActivity pa = removed.get(j);
16949                    pir.removeFilter(pa);
16950                }
16951                changed = true;
16952            }
16953        }
16954        return changed;
16955    }
16956
16957    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
16958    private void clearIntentFilterVerificationsLPw(int userId) {
16959        final int packageCount = mPackages.size();
16960        for (int i = 0; i < packageCount; i++) {
16961            PackageParser.Package pkg = mPackages.valueAt(i);
16962            clearIntentFilterVerificationsLPw(pkg.packageName, userId);
16963        }
16964    }
16965
16966    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
16967    void clearIntentFilterVerificationsLPw(String packageName, int userId) {
16968        if (userId == UserHandle.USER_ALL) {
16969            if (mSettings.removeIntentFilterVerificationLPw(packageName,
16970                    sUserManager.getUserIds())) {
16971                for (int oneUserId : sUserManager.getUserIds()) {
16972                    scheduleWritePackageRestrictionsLocked(oneUserId);
16973                }
16974            }
16975        } else {
16976            if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) {
16977                scheduleWritePackageRestrictionsLocked(userId);
16978            }
16979        }
16980    }
16981
16982    void clearDefaultBrowserIfNeeded(String packageName) {
16983        for (int oneUserId : sUserManager.getUserIds()) {
16984            String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId);
16985            if (TextUtils.isEmpty(defaultBrowserPackageName)) continue;
16986            if (packageName.equals(defaultBrowserPackageName)) {
16987                setDefaultBrowserPackageName(null, oneUserId);
16988            }
16989        }
16990    }
16991
16992    @Override
16993    public void resetApplicationPreferences(int userId) {
16994        mContext.enforceCallingOrSelfPermission(
16995                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
16996        final long identity = Binder.clearCallingIdentity();
16997        // writer
16998        try {
16999            synchronized (mPackages) {
17000                clearPackagePreferredActivitiesLPw(null, userId);
17001                mSettings.applyDefaultPreferredAppsLPw(this, userId);
17002                // TODO: We have to reset the default SMS and Phone. This requires
17003                // significant refactoring to keep all default apps in the package
17004                // manager (cleaner but more work) or have the services provide
17005                // callbacks to the package manager to request a default app reset.
17006                applyFactoryDefaultBrowserLPw(userId);
17007                clearIntentFilterVerificationsLPw(userId);
17008                primeDomainVerificationsLPw(userId);
17009                resetUserChangesToRuntimePermissionsAndFlagsLPw(userId);
17010                scheduleWritePackageRestrictionsLocked(userId);
17011            }
17012            resetNetworkPolicies(userId);
17013        } finally {
17014            Binder.restoreCallingIdentity(identity);
17015        }
17016    }
17017
17018    @Override
17019    public int getPreferredActivities(List<IntentFilter> outFilters,
17020            List<ComponentName> outActivities, String packageName) {
17021
17022        int num = 0;
17023        final int userId = UserHandle.getCallingUserId();
17024        // reader
17025        synchronized (mPackages) {
17026            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
17027            if (pir != null) {
17028                final Iterator<PreferredActivity> it = pir.filterIterator();
17029                while (it.hasNext()) {
17030                    final PreferredActivity pa = it.next();
17031                    if (packageName == null
17032                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
17033                                    && pa.mPref.mAlways)) {
17034                        if (outFilters != null) {
17035                            outFilters.add(new IntentFilter(pa));
17036                        }
17037                        if (outActivities != null) {
17038                            outActivities.add(pa.mPref.mComponent);
17039                        }
17040                    }
17041                }
17042            }
17043        }
17044
17045        return num;
17046    }
17047
17048    @Override
17049    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
17050            int userId) {
17051        int callingUid = Binder.getCallingUid();
17052        if (callingUid != Process.SYSTEM_UID) {
17053            throw new SecurityException(
17054                    "addPersistentPreferredActivity can only be run by the system");
17055        }
17056        if (filter.countActions() == 0) {
17057            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
17058            return;
17059        }
17060        synchronized (mPackages) {
17061            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
17062                    ":");
17063            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
17064            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
17065                    new PersistentPreferredActivity(filter, activity));
17066            scheduleWritePackageRestrictionsLocked(userId);
17067        }
17068    }
17069
17070    @Override
17071    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
17072        int callingUid = Binder.getCallingUid();
17073        if (callingUid != Process.SYSTEM_UID) {
17074            throw new SecurityException(
17075                    "clearPackagePersistentPreferredActivities can only be run by the system");
17076        }
17077        ArrayList<PersistentPreferredActivity> removed = null;
17078        boolean changed = false;
17079        synchronized (mPackages) {
17080            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
17081                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
17082                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
17083                        .valueAt(i);
17084                if (userId != thisUserId) {
17085                    continue;
17086                }
17087                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
17088                while (it.hasNext()) {
17089                    PersistentPreferredActivity ppa = it.next();
17090                    // Mark entry for removal only if it matches the package name.
17091                    if (ppa.mComponent.getPackageName().equals(packageName)) {
17092                        if (removed == null) {
17093                            removed = new ArrayList<PersistentPreferredActivity>();
17094                        }
17095                        removed.add(ppa);
17096                    }
17097                }
17098                if (removed != null) {
17099                    for (int j=0; j<removed.size(); j++) {
17100                        PersistentPreferredActivity ppa = removed.get(j);
17101                        ppir.removeFilter(ppa);
17102                    }
17103                    changed = true;
17104                }
17105            }
17106
17107            if (changed) {
17108                scheduleWritePackageRestrictionsLocked(userId);
17109            }
17110        }
17111    }
17112
17113    /**
17114     * Common machinery for picking apart a restored XML blob and passing
17115     * it to a caller-supplied functor to be applied to the running system.
17116     */
17117    private void restoreFromXml(XmlPullParser parser, int userId,
17118            String expectedStartTag, BlobXmlRestorer functor)
17119            throws IOException, XmlPullParserException {
17120        int type;
17121        while ((type = parser.next()) != XmlPullParser.START_TAG
17122                && type != XmlPullParser.END_DOCUMENT) {
17123        }
17124        if (type != XmlPullParser.START_TAG) {
17125            // oops didn't find a start tag?!
17126            if (DEBUG_BACKUP) {
17127                Slog.e(TAG, "Didn't find start tag during restore");
17128            }
17129            return;
17130        }
17131Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName());
17132        // this is supposed to be TAG_PREFERRED_BACKUP
17133        if (!expectedStartTag.equals(parser.getName())) {
17134            if (DEBUG_BACKUP) {
17135                Slog.e(TAG, "Found unexpected tag " + parser.getName());
17136            }
17137            return;
17138        }
17139
17140        // skip interfering stuff, then we're aligned with the backing implementation
17141        while ((type = parser.next()) == XmlPullParser.TEXT) { }
17142Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName());
17143        functor.apply(parser, userId);
17144    }
17145
17146    private interface BlobXmlRestorer {
17147        public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException;
17148    }
17149
17150    /**
17151     * Non-Binder method, support for the backup/restore mechanism: write the
17152     * full set of preferred activities in its canonical XML format.  Returns the
17153     * XML output as a byte array, or null if there is none.
17154     */
17155    @Override
17156    public byte[] getPreferredActivityBackup(int userId) {
17157        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17158            throw new SecurityException("Only the system may call getPreferredActivityBackup()");
17159        }
17160
17161        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
17162        try {
17163            final XmlSerializer serializer = new FastXmlSerializer();
17164            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
17165            serializer.startDocument(null, true);
17166            serializer.startTag(null, TAG_PREFERRED_BACKUP);
17167
17168            synchronized (mPackages) {
17169                mSettings.writePreferredActivitiesLPr(serializer, userId, true);
17170            }
17171
17172            serializer.endTag(null, TAG_PREFERRED_BACKUP);
17173            serializer.endDocument();
17174            serializer.flush();
17175        } catch (Exception e) {
17176            if (DEBUG_BACKUP) {
17177                Slog.e(TAG, "Unable to write preferred activities for backup", e);
17178            }
17179            return null;
17180        }
17181
17182        return dataStream.toByteArray();
17183    }
17184
17185    @Override
17186    public void restorePreferredActivities(byte[] backup, int userId) {
17187        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17188            throw new SecurityException("Only the system may call restorePreferredActivities()");
17189        }
17190
17191        try {
17192            final XmlPullParser parser = Xml.newPullParser();
17193            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
17194            restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP,
17195                    new BlobXmlRestorer() {
17196                        @Override
17197                        public void apply(XmlPullParser parser, int userId)
17198                                throws XmlPullParserException, IOException {
17199                            synchronized (mPackages) {
17200                                mSettings.readPreferredActivitiesLPw(parser, userId);
17201                            }
17202                        }
17203                    } );
17204        } catch (Exception e) {
17205            if (DEBUG_BACKUP) {
17206                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
17207            }
17208        }
17209    }
17210
17211    /**
17212     * Non-Binder method, support for the backup/restore mechanism: write the
17213     * default browser (etc) settings in its canonical XML format.  Returns the default
17214     * browser XML representation as a byte array, or null if there is none.
17215     */
17216    @Override
17217    public byte[] getDefaultAppsBackup(int userId) {
17218        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17219            throw new SecurityException("Only the system may call getDefaultAppsBackup()");
17220        }
17221
17222        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
17223        try {
17224            final XmlSerializer serializer = new FastXmlSerializer();
17225            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
17226            serializer.startDocument(null, true);
17227            serializer.startTag(null, TAG_DEFAULT_APPS);
17228
17229            synchronized (mPackages) {
17230                mSettings.writeDefaultAppsLPr(serializer, userId);
17231            }
17232
17233            serializer.endTag(null, TAG_DEFAULT_APPS);
17234            serializer.endDocument();
17235            serializer.flush();
17236        } catch (Exception e) {
17237            if (DEBUG_BACKUP) {
17238                Slog.e(TAG, "Unable to write default apps for backup", e);
17239            }
17240            return null;
17241        }
17242
17243        return dataStream.toByteArray();
17244    }
17245
17246    @Override
17247    public void restoreDefaultApps(byte[] backup, int userId) {
17248        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17249            throw new SecurityException("Only the system may call restoreDefaultApps()");
17250        }
17251
17252        try {
17253            final XmlPullParser parser = Xml.newPullParser();
17254            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
17255            restoreFromXml(parser, userId, TAG_DEFAULT_APPS,
17256                    new BlobXmlRestorer() {
17257                        @Override
17258                        public void apply(XmlPullParser parser, int userId)
17259                                throws XmlPullParserException, IOException {
17260                            synchronized (mPackages) {
17261                                mSettings.readDefaultAppsLPw(parser, userId);
17262                            }
17263                        }
17264                    } );
17265        } catch (Exception e) {
17266            if (DEBUG_BACKUP) {
17267                Slog.e(TAG, "Exception restoring default apps: " + e.getMessage());
17268            }
17269        }
17270    }
17271
17272    @Override
17273    public byte[] getIntentFilterVerificationBackup(int userId) {
17274        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17275            throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()");
17276        }
17277
17278        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
17279        try {
17280            final XmlSerializer serializer = new FastXmlSerializer();
17281            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
17282            serializer.startDocument(null, true);
17283            serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION);
17284
17285            synchronized (mPackages) {
17286                mSettings.writeAllDomainVerificationsLPr(serializer, userId);
17287            }
17288
17289            serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION);
17290            serializer.endDocument();
17291            serializer.flush();
17292        } catch (Exception e) {
17293            if (DEBUG_BACKUP) {
17294                Slog.e(TAG, "Unable to write default apps for backup", e);
17295            }
17296            return null;
17297        }
17298
17299        return dataStream.toByteArray();
17300    }
17301
17302    @Override
17303    public void restoreIntentFilterVerification(byte[] backup, int userId) {
17304        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17305            throw new SecurityException("Only the system may call restorePreferredActivities()");
17306        }
17307
17308        try {
17309            final XmlPullParser parser = Xml.newPullParser();
17310            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
17311            restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION,
17312                    new BlobXmlRestorer() {
17313                        @Override
17314                        public void apply(XmlPullParser parser, int userId)
17315                                throws XmlPullParserException, IOException {
17316                            synchronized (mPackages) {
17317                                mSettings.readAllDomainVerificationsLPr(parser, userId);
17318                                mSettings.writeLPr();
17319                            }
17320                        }
17321                    } );
17322        } catch (Exception e) {
17323            if (DEBUG_BACKUP) {
17324                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
17325            }
17326        }
17327    }
17328
17329    @Override
17330    public byte[] getPermissionGrantBackup(int userId) {
17331        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17332            throw new SecurityException("Only the system may call getPermissionGrantBackup()");
17333        }
17334
17335        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
17336        try {
17337            final XmlSerializer serializer = new FastXmlSerializer();
17338            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
17339            serializer.startDocument(null, true);
17340            serializer.startTag(null, TAG_PERMISSION_BACKUP);
17341
17342            synchronized (mPackages) {
17343                serializeRuntimePermissionGrantsLPr(serializer, userId);
17344            }
17345
17346            serializer.endTag(null, TAG_PERMISSION_BACKUP);
17347            serializer.endDocument();
17348            serializer.flush();
17349        } catch (Exception e) {
17350            if (DEBUG_BACKUP) {
17351                Slog.e(TAG, "Unable to write default apps for backup", e);
17352            }
17353            return null;
17354        }
17355
17356        return dataStream.toByteArray();
17357    }
17358
17359    @Override
17360    public void restorePermissionGrants(byte[] backup, int userId) {
17361        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17362            throw new SecurityException("Only the system may call restorePermissionGrants()");
17363        }
17364
17365        try {
17366            final XmlPullParser parser = Xml.newPullParser();
17367            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
17368            restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP,
17369                    new BlobXmlRestorer() {
17370                        @Override
17371                        public void apply(XmlPullParser parser, int userId)
17372                                throws XmlPullParserException, IOException {
17373                            synchronized (mPackages) {
17374                                processRestoredPermissionGrantsLPr(parser, userId);
17375                            }
17376                        }
17377                    } );
17378        } catch (Exception e) {
17379            if (DEBUG_BACKUP) {
17380                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
17381            }
17382        }
17383    }
17384
17385    private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId)
17386            throws IOException {
17387        serializer.startTag(null, TAG_ALL_GRANTS);
17388
17389        final int N = mSettings.mPackages.size();
17390        for (int i = 0; i < N; i++) {
17391            final PackageSetting ps = mSettings.mPackages.valueAt(i);
17392            boolean pkgGrantsKnown = false;
17393
17394            PermissionsState packagePerms = ps.getPermissionsState();
17395
17396            for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) {
17397                final int grantFlags = state.getFlags();
17398                // only look at grants that are not system/policy fixed
17399                if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) {
17400                    final boolean isGranted = state.isGranted();
17401                    // And only back up the user-twiddled state bits
17402                    if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) {
17403                        final String packageName = mSettings.mPackages.keyAt(i);
17404                        if (!pkgGrantsKnown) {
17405                            serializer.startTag(null, TAG_GRANT);
17406                            serializer.attribute(null, ATTR_PACKAGE_NAME, packageName);
17407                            pkgGrantsKnown = true;
17408                        }
17409
17410                        final boolean userSet =
17411                                (grantFlags & FLAG_PERMISSION_USER_SET) != 0;
17412                        final boolean userFixed =
17413                                (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0;
17414                        final boolean revoke =
17415                                (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0;
17416
17417                        serializer.startTag(null, TAG_PERMISSION);
17418                        serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName());
17419                        if (isGranted) {
17420                            serializer.attribute(null, ATTR_IS_GRANTED, "true");
17421                        }
17422                        if (userSet) {
17423                            serializer.attribute(null, ATTR_USER_SET, "true");
17424                        }
17425                        if (userFixed) {
17426                            serializer.attribute(null, ATTR_USER_FIXED, "true");
17427                        }
17428                        if (revoke) {
17429                            serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true");
17430                        }
17431                        serializer.endTag(null, TAG_PERMISSION);
17432                    }
17433                }
17434            }
17435
17436            if (pkgGrantsKnown) {
17437                serializer.endTag(null, TAG_GRANT);
17438            }
17439        }
17440
17441        serializer.endTag(null, TAG_ALL_GRANTS);
17442    }
17443
17444    private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId)
17445            throws XmlPullParserException, IOException {
17446        String pkgName = null;
17447        int outerDepth = parser.getDepth();
17448        int type;
17449        while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
17450                && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
17451            if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
17452                continue;
17453            }
17454
17455            final String tagName = parser.getName();
17456            if (tagName.equals(TAG_GRANT)) {
17457                pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME);
17458                if (DEBUG_BACKUP) {
17459                    Slog.v(TAG, "+++ Restoring grants for package " + pkgName);
17460                }
17461            } else if (tagName.equals(TAG_PERMISSION)) {
17462
17463                final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED));
17464                final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME);
17465
17466                int newFlagSet = 0;
17467                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) {
17468                    newFlagSet |= FLAG_PERMISSION_USER_SET;
17469                }
17470                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) {
17471                    newFlagSet |= FLAG_PERMISSION_USER_FIXED;
17472                }
17473                if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) {
17474                    newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE;
17475                }
17476                if (DEBUG_BACKUP) {
17477                    Slog.v(TAG, "  + Restoring grant: pkg=" + pkgName + " perm=" + permName
17478                            + " granted=" + isGranted + " bits=0x" + Integer.toHexString(newFlagSet));
17479                }
17480                final PackageSetting ps = mSettings.mPackages.get(pkgName);
17481                if (ps != null) {
17482                    // Already installed so we apply the grant immediately
17483                    if (DEBUG_BACKUP) {
17484                        Slog.v(TAG, "        + already installed; applying");
17485                    }
17486                    PermissionsState perms = ps.getPermissionsState();
17487                    BasePermission bp = mSettings.mPermissions.get(permName);
17488                    if (bp != null) {
17489                        if (isGranted) {
17490                            perms.grantRuntimePermission(bp, userId);
17491                        }
17492                        if (newFlagSet != 0) {
17493                            perms.updatePermissionFlags(bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet);
17494                        }
17495                    }
17496                } else {
17497                    // Need to wait for post-restore install to apply the grant
17498                    if (DEBUG_BACKUP) {
17499                        Slog.v(TAG, "        - not yet installed; saving for later");
17500                    }
17501                    mSettings.processRestoredPermissionGrantLPr(pkgName, permName,
17502                            isGranted, newFlagSet, userId);
17503                }
17504            } else {
17505                PackageManagerService.reportSettingsProblem(Log.WARN,
17506                        "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName);
17507                XmlUtils.skipCurrentTag(parser);
17508            }
17509        }
17510
17511        scheduleWriteSettingsLocked();
17512        mSettings.writeRuntimePermissionsForUserLPr(userId, false);
17513    }
17514
17515    @Override
17516    public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
17517            int sourceUserId, int targetUserId, int flags) {
17518        mContext.enforceCallingOrSelfPermission(
17519                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
17520        int callingUid = Binder.getCallingUid();
17521        enforceOwnerRights(ownerPackage, callingUid);
17522        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
17523        if (intentFilter.countActions() == 0) {
17524            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
17525            return;
17526        }
17527        synchronized (mPackages) {
17528            CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter,
17529                    ownerPackage, targetUserId, flags);
17530            CrossProfileIntentResolver resolver =
17531                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
17532            ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter);
17533            // We have all those whose filter is equal. Now checking if the rest is equal as well.
17534            if (existing != null) {
17535                int size = existing.size();
17536                for (int i = 0; i < size; i++) {
17537                    if (newFilter.equalsIgnoreFilter(existing.get(i))) {
17538                        return;
17539                    }
17540                }
17541            }
17542            resolver.addFilter(newFilter);
17543            scheduleWritePackageRestrictionsLocked(sourceUserId);
17544        }
17545    }
17546
17547    @Override
17548    public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) {
17549        mContext.enforceCallingOrSelfPermission(
17550                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
17551        int callingUid = Binder.getCallingUid();
17552        enforceOwnerRights(ownerPackage, callingUid);
17553        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
17554        synchronized (mPackages) {
17555            CrossProfileIntentResolver resolver =
17556                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
17557            ArraySet<CrossProfileIntentFilter> set =
17558                    new ArraySet<CrossProfileIntentFilter>(resolver.filterSet());
17559            for (CrossProfileIntentFilter filter : set) {
17560                if (filter.getOwnerPackage().equals(ownerPackage)) {
17561                    resolver.removeFilter(filter);
17562                }
17563            }
17564            scheduleWritePackageRestrictionsLocked(sourceUserId);
17565        }
17566    }
17567
17568    // Enforcing that callingUid is owning pkg on userId
17569    private void enforceOwnerRights(String pkg, int callingUid) {
17570        // The system owns everything.
17571        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
17572            return;
17573        }
17574        int callingUserId = UserHandle.getUserId(callingUid);
17575        PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
17576        if (pi == null) {
17577            throw new IllegalArgumentException("Unknown package " + pkg + " on user "
17578                    + callingUserId);
17579        }
17580        if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
17581            throw new SecurityException("Calling uid " + callingUid
17582                    + " does not own package " + pkg);
17583        }
17584    }
17585
17586    @Override
17587    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
17588        return getHomeActivitiesAsUser(allHomeCandidates, UserHandle.getCallingUserId());
17589    }
17590
17591    private Intent getHomeIntent() {
17592        Intent intent = new Intent(Intent.ACTION_MAIN);
17593        intent.addCategory(Intent.CATEGORY_HOME);
17594        return intent;
17595    }
17596
17597    private IntentFilter getHomeFilter() {
17598        IntentFilter filter = new IntentFilter(Intent.ACTION_MAIN);
17599        filter.addCategory(Intent.CATEGORY_HOME);
17600        filter.addCategory(Intent.CATEGORY_DEFAULT);
17601        return filter;
17602    }
17603
17604    ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
17605            int userId) {
17606        Intent intent  = getHomeIntent();
17607        List<ResolveInfo> list = queryIntentActivitiesInternal(intent, null,
17608                PackageManager.GET_META_DATA, userId);
17609        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
17610                true, false, false, userId);
17611
17612        allHomeCandidates.clear();
17613        if (list != null) {
17614            for (ResolveInfo ri : list) {
17615                allHomeCandidates.add(ri);
17616            }
17617        }
17618        return (preferred == null || preferred.activityInfo == null)
17619                ? null
17620                : new ComponentName(preferred.activityInfo.packageName,
17621                        preferred.activityInfo.name);
17622    }
17623
17624    @Override
17625    public void setHomeActivity(ComponentName comp, int userId) {
17626        ArrayList<ResolveInfo> homeActivities = new ArrayList<>();
17627        getHomeActivitiesAsUser(homeActivities, userId);
17628
17629        boolean found = false;
17630
17631        final int size = homeActivities.size();
17632        final ComponentName[] set = new ComponentName[size];
17633        for (int i = 0; i < size; i++) {
17634            final ResolveInfo candidate = homeActivities.get(i);
17635            final ActivityInfo info = candidate.activityInfo;
17636            final ComponentName activityName = new ComponentName(info.packageName, info.name);
17637            set[i] = activityName;
17638            if (!found && activityName.equals(comp)) {
17639                found = true;
17640            }
17641        }
17642        if (!found) {
17643            throw new IllegalArgumentException("Component " + comp + " cannot be home on user "
17644                    + userId);
17645        }
17646        replacePreferredActivity(getHomeFilter(), IntentFilter.MATCH_CATEGORY_EMPTY,
17647                set, comp, userId);
17648    }
17649
17650    private @Nullable String getSetupWizardPackageName() {
17651        final Intent intent = new Intent(Intent.ACTION_MAIN);
17652        intent.addCategory(Intent.CATEGORY_SETUP_WIZARD);
17653
17654        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
17655                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
17656                        | MATCH_DISABLED_COMPONENTS,
17657                UserHandle.myUserId());
17658        if (matches.size() == 1) {
17659            return matches.get(0).getComponentInfo().packageName;
17660        } else {
17661            Slog.e(TAG, "There should probably be exactly one setup wizard; found " + matches.size()
17662                    + ": matches=" + matches);
17663            return null;
17664        }
17665    }
17666
17667    @Override
17668    public void setApplicationEnabledSetting(String appPackageName,
17669            int newState, int flags, int userId, String callingPackage) {
17670        if (!sUserManager.exists(userId)) return;
17671        if (callingPackage == null) {
17672            callingPackage = Integer.toString(Binder.getCallingUid());
17673        }
17674        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
17675    }
17676
17677    @Override
17678    public void setComponentEnabledSetting(ComponentName componentName,
17679            int newState, int flags, int userId) {
17680        if (!sUserManager.exists(userId)) return;
17681        setEnabledSetting(componentName.getPackageName(),
17682                componentName.getClassName(), newState, flags, userId, null);
17683    }
17684
17685    private void setEnabledSetting(final String packageName, String className, int newState,
17686            final int flags, int userId, String callingPackage) {
17687        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
17688              || newState == COMPONENT_ENABLED_STATE_ENABLED
17689              || newState == COMPONENT_ENABLED_STATE_DISABLED
17690              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
17691              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
17692            throw new IllegalArgumentException("Invalid new component state: "
17693                    + newState);
17694        }
17695        PackageSetting pkgSetting;
17696        final int uid = Binder.getCallingUid();
17697        final int permission;
17698        if (uid == Process.SYSTEM_UID) {
17699            permission = PackageManager.PERMISSION_GRANTED;
17700        } else {
17701            permission = mContext.checkCallingOrSelfPermission(
17702                    android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
17703        }
17704        enforceCrossUserPermission(uid, userId,
17705                false /* requireFullPermission */, true /* checkShell */, "set enabled");
17706        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
17707        boolean sendNow = false;
17708        boolean isApp = (className == null);
17709        String componentName = isApp ? packageName : className;
17710        int packageUid = -1;
17711        ArrayList<String> components;
17712
17713        // writer
17714        synchronized (mPackages) {
17715            pkgSetting = mSettings.mPackages.get(packageName);
17716            if (pkgSetting == null) {
17717                if (className == null) {
17718                    throw new IllegalArgumentException("Unknown package: " + packageName);
17719                }
17720                throw new IllegalArgumentException(
17721                        "Unknown component: " + packageName + "/" + className);
17722            }
17723        }
17724
17725        // Limit who can change which apps
17726        if (!UserHandle.isSameApp(uid, pkgSetting.appId)) {
17727            // Don't allow apps that don't have permission to modify other apps
17728            if (!allowedByPermission) {
17729                throw new SecurityException(
17730                        "Permission Denial: attempt to change component state from pid="
17731                        + Binder.getCallingPid()
17732                        + ", uid=" + uid + ", package uid=" + pkgSetting.appId);
17733            }
17734            // Don't allow changing profile and device owners.
17735            if (mProtectedPackages.canPackageStateBeChanged(userId, packageName)) {
17736                throw new SecurityException("Cannot disable a device owner or a profile owner");
17737            }
17738        }
17739
17740        synchronized (mPackages) {
17741            if (uid == Process.SHELL_UID) {
17742                // Shell can only change whole packages between ENABLED and DISABLED_USER states
17743                int oldState = pkgSetting.getEnabled(userId);
17744                if (className == null
17745                    &&
17746                    (oldState == COMPONENT_ENABLED_STATE_DISABLED_USER
17747                     || oldState == COMPONENT_ENABLED_STATE_DEFAULT
17748                     || oldState == COMPONENT_ENABLED_STATE_ENABLED)
17749                    &&
17750                    (newState == COMPONENT_ENABLED_STATE_DISABLED_USER
17751                     || newState == COMPONENT_ENABLED_STATE_DEFAULT
17752                     || newState == COMPONENT_ENABLED_STATE_ENABLED)) {
17753                    // ok
17754                } else {
17755                    throw new SecurityException(
17756                            "Shell cannot change component state for " + packageName + "/"
17757                            + className + " to " + newState);
17758                }
17759            }
17760            if (className == null) {
17761                // We're dealing with an application/package level state change
17762                if (pkgSetting.getEnabled(userId) == newState) {
17763                    // Nothing to do
17764                    return;
17765                }
17766                if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
17767                    || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
17768                    // Don't care about who enables an app.
17769                    callingPackage = null;
17770                }
17771                pkgSetting.setEnabled(newState, userId, callingPackage);
17772                // pkgSetting.pkg.mSetEnabled = newState;
17773            } else {
17774                // We're dealing with a component level state change
17775                // First, verify that this is a valid class name.
17776                PackageParser.Package pkg = pkgSetting.pkg;
17777                if (pkg == null || !pkg.hasComponentClassName(className)) {
17778                    if (pkg != null &&
17779                            pkg.applicationInfo.targetSdkVersion >=
17780                                    Build.VERSION_CODES.JELLY_BEAN) {
17781                        throw new IllegalArgumentException("Component class " + className
17782                                + " does not exist in " + packageName);
17783                    } else {
17784                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
17785                                + className + " does not exist in " + packageName);
17786                    }
17787                }
17788                switch (newState) {
17789                case COMPONENT_ENABLED_STATE_ENABLED:
17790                    if (!pkgSetting.enableComponentLPw(className, userId)) {
17791                        return;
17792                    }
17793                    break;
17794                case COMPONENT_ENABLED_STATE_DISABLED:
17795                    if (!pkgSetting.disableComponentLPw(className, userId)) {
17796                        return;
17797                    }
17798                    break;
17799                case COMPONENT_ENABLED_STATE_DEFAULT:
17800                    if (!pkgSetting.restoreComponentLPw(className, userId)) {
17801                        return;
17802                    }
17803                    break;
17804                default:
17805                    Slog.e(TAG, "Invalid new component state: " + newState);
17806                    return;
17807                }
17808            }
17809            scheduleWritePackageRestrictionsLocked(userId);
17810            components = mPendingBroadcasts.get(userId, packageName);
17811            final boolean newPackage = components == null;
17812            if (newPackage) {
17813                components = new ArrayList<String>();
17814            }
17815            if (!components.contains(componentName)) {
17816                components.add(componentName);
17817            }
17818            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
17819                sendNow = true;
17820                // Purge entry from pending broadcast list if another one exists already
17821                // since we are sending one right away.
17822                mPendingBroadcasts.remove(userId, packageName);
17823            } else {
17824                if (newPackage) {
17825                    mPendingBroadcasts.put(userId, packageName, components);
17826                }
17827                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
17828                    // Schedule a message
17829                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
17830                }
17831            }
17832        }
17833
17834        long callingId = Binder.clearCallingIdentity();
17835        try {
17836            if (sendNow) {
17837                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
17838                sendPackageChangedBroadcast(packageName,
17839                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
17840            }
17841        } finally {
17842            Binder.restoreCallingIdentity(callingId);
17843        }
17844    }
17845
17846    @Override
17847    public void flushPackageRestrictionsAsUser(int userId) {
17848        if (!sUserManager.exists(userId)) {
17849            return;
17850        }
17851        enforceCrossUserPermission(Binder.getCallingUid(), userId, false /* requireFullPermission*/,
17852                false /* checkShell */, "flushPackageRestrictions");
17853        synchronized (mPackages) {
17854            mSettings.writePackageRestrictionsLPr(userId);
17855            mDirtyUsers.remove(userId);
17856            if (mDirtyUsers.isEmpty()) {
17857                mHandler.removeMessages(WRITE_PACKAGE_RESTRICTIONS);
17858            }
17859        }
17860    }
17861
17862    private void sendPackageChangedBroadcast(String packageName,
17863            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
17864        if (DEBUG_INSTALL)
17865            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
17866                    + componentNames);
17867        Bundle extras = new Bundle(4);
17868        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
17869        String nameList[] = new String[componentNames.size()];
17870        componentNames.toArray(nameList);
17871        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
17872        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
17873        extras.putInt(Intent.EXTRA_UID, packageUid);
17874        // If this is not reporting a change of the overall package, then only send it
17875        // to registered receivers.  We don't want to launch a swath of apps for every
17876        // little component state change.
17877        final int flags = !componentNames.contains(packageName)
17878                ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0;
17879        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, flags, null, null,
17880                new int[] {UserHandle.getUserId(packageUid)});
17881    }
17882
17883    @Override
17884    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
17885        if (!sUserManager.exists(userId)) return;
17886        final int uid = Binder.getCallingUid();
17887        final int permission = mContext.checkCallingOrSelfPermission(
17888                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
17889        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
17890        enforceCrossUserPermission(uid, userId,
17891                true /* requireFullPermission */, true /* checkShell */, "stop package");
17892        // writer
17893        synchronized (mPackages) {
17894            if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped,
17895                    allowedByPermission, uid, userId)) {
17896                scheduleWritePackageRestrictionsLocked(userId);
17897            }
17898        }
17899    }
17900
17901    @Override
17902    public String getInstallerPackageName(String packageName) {
17903        // reader
17904        synchronized (mPackages) {
17905            return mSettings.getInstallerPackageNameLPr(packageName);
17906        }
17907    }
17908
17909    public boolean isOrphaned(String packageName) {
17910        // reader
17911        synchronized (mPackages) {
17912            return mSettings.isOrphaned(packageName);
17913        }
17914    }
17915
17916    @Override
17917    public int getApplicationEnabledSetting(String packageName, int userId) {
17918        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
17919        int uid = Binder.getCallingUid();
17920        enforceCrossUserPermission(uid, userId,
17921                false /* requireFullPermission */, false /* checkShell */, "get enabled");
17922        // reader
17923        synchronized (mPackages) {
17924            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
17925        }
17926    }
17927
17928    @Override
17929    public int getComponentEnabledSetting(ComponentName componentName, int userId) {
17930        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
17931        int uid = Binder.getCallingUid();
17932        enforceCrossUserPermission(uid, userId,
17933                false /* requireFullPermission */, false /* checkShell */, "get component enabled");
17934        // reader
17935        synchronized (mPackages) {
17936            return mSettings.getComponentEnabledSettingLPr(componentName, userId);
17937        }
17938    }
17939
17940    @Override
17941    public void enterSafeMode() {
17942        enforceSystemOrRoot("Only the system can request entering safe mode");
17943
17944        if (!mSystemReady) {
17945            mSafeMode = true;
17946        }
17947    }
17948
17949    @Override
17950    public void systemReady() {
17951        mSystemReady = true;
17952
17953        // Read the compatibilty setting when the system is ready.
17954        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
17955                mContext.getContentResolver(),
17956                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
17957        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
17958        if (DEBUG_SETTINGS) {
17959            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
17960        }
17961
17962        int[] grantPermissionsUserIds = EMPTY_INT_ARRAY;
17963
17964        synchronized (mPackages) {
17965            // Verify that all of the preferred activity components actually
17966            // exist.  It is possible for applications to be updated and at
17967            // that point remove a previously declared activity component that
17968            // had been set as a preferred activity.  We try to clean this up
17969            // the next time we encounter that preferred activity, but it is
17970            // possible for the user flow to never be able to return to that
17971            // situation so here we do a sanity check to make sure we haven't
17972            // left any junk around.
17973            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
17974            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
17975                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
17976                removed.clear();
17977                for (PreferredActivity pa : pir.filterSet()) {
17978                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
17979                        removed.add(pa);
17980                    }
17981                }
17982                if (removed.size() > 0) {
17983                    for (int r=0; r<removed.size(); r++) {
17984                        PreferredActivity pa = removed.get(r);
17985                        Slog.w(TAG, "Removing dangling preferred activity: "
17986                                + pa.mPref.mComponent);
17987                        pir.removeFilter(pa);
17988                    }
17989                    mSettings.writePackageRestrictionsLPr(
17990                            mSettings.mPreferredActivities.keyAt(i));
17991                }
17992            }
17993
17994            for (int userId : UserManagerService.getInstance().getUserIds()) {
17995                if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) {
17996                    grantPermissionsUserIds = ArrayUtils.appendInt(
17997                            grantPermissionsUserIds, userId);
17998                }
17999            }
18000        }
18001        sUserManager.systemReady();
18002
18003        // If we upgraded grant all default permissions before kicking off.
18004        for (int userId : grantPermissionsUserIds) {
18005            mDefaultPermissionPolicy.grantDefaultPermissions(userId);
18006        }
18007
18008        // Kick off any messages waiting for system ready
18009        if (mPostSystemReadyMessages != null) {
18010            for (Message msg : mPostSystemReadyMessages) {
18011                msg.sendToTarget();
18012            }
18013            mPostSystemReadyMessages = null;
18014        }
18015
18016        // Watch for external volumes that come and go over time
18017        final StorageManager storage = mContext.getSystemService(StorageManager.class);
18018        storage.registerListener(mStorageListener);
18019
18020        mInstallerService.systemReady();
18021        mPackageDexOptimizer.systemReady();
18022
18023        MountServiceInternal mountServiceInternal = LocalServices.getService(
18024                MountServiceInternal.class);
18025        mountServiceInternal.addExternalStoragePolicy(
18026                new MountServiceInternal.ExternalStorageMountPolicy() {
18027            @Override
18028            public int getMountMode(int uid, String packageName) {
18029                if (Process.isIsolated(uid)) {
18030                    return Zygote.MOUNT_EXTERNAL_NONE;
18031                }
18032                if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) {
18033                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
18034                }
18035                if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
18036                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
18037                }
18038                if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
18039                    return Zygote.MOUNT_EXTERNAL_READ;
18040                }
18041                return Zygote.MOUNT_EXTERNAL_WRITE;
18042            }
18043
18044            @Override
18045            public boolean hasExternalStorage(int uid, String packageName) {
18046                return true;
18047            }
18048        });
18049
18050        // Now that we're mostly running, clean up stale users and apps
18051        reconcileUsers(StorageManager.UUID_PRIVATE_INTERNAL);
18052        reconcileApps(StorageManager.UUID_PRIVATE_INTERNAL);
18053    }
18054
18055    @Override
18056    public boolean isSafeMode() {
18057        return mSafeMode;
18058    }
18059
18060    @Override
18061    public boolean hasSystemUidErrors() {
18062        return mHasSystemUidErrors;
18063    }
18064
18065    static String arrayToString(int[] array) {
18066        StringBuffer buf = new StringBuffer(128);
18067        buf.append('[');
18068        if (array != null) {
18069            for (int i=0; i<array.length; i++) {
18070                if (i > 0) buf.append(", ");
18071                buf.append(array[i]);
18072            }
18073        }
18074        buf.append(']');
18075        return buf.toString();
18076    }
18077
18078    static class DumpState {
18079        public static final int DUMP_LIBS = 1 << 0;
18080        public static final int DUMP_FEATURES = 1 << 1;
18081        public static final int DUMP_ACTIVITY_RESOLVERS = 1 << 2;
18082        public static final int DUMP_SERVICE_RESOLVERS = 1 << 3;
18083        public static final int DUMP_RECEIVER_RESOLVERS = 1 << 4;
18084        public static final int DUMP_CONTENT_RESOLVERS = 1 << 5;
18085        public static final int DUMP_PERMISSIONS = 1 << 6;
18086        public static final int DUMP_PACKAGES = 1 << 7;
18087        public static final int DUMP_SHARED_USERS = 1 << 8;
18088        public static final int DUMP_MESSAGES = 1 << 9;
18089        public static final int DUMP_PROVIDERS = 1 << 10;
18090        public static final int DUMP_VERIFIERS = 1 << 11;
18091        public static final int DUMP_PREFERRED = 1 << 12;
18092        public static final int DUMP_PREFERRED_XML = 1 << 13;
18093        public static final int DUMP_KEYSETS = 1 << 14;
18094        public static final int DUMP_VERSION = 1 << 15;
18095        public static final int DUMP_INSTALLS = 1 << 16;
18096        public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 17;
18097        public static final int DUMP_DOMAIN_PREFERRED = 1 << 18;
18098        public static final int DUMP_FROZEN = 1 << 19;
18099        public static final int DUMP_DEXOPT = 1 << 20;
18100
18101        public static final int OPTION_SHOW_FILTERS = 1 << 0;
18102
18103        private int mTypes;
18104
18105        private int mOptions;
18106
18107        private boolean mTitlePrinted;
18108
18109        private SharedUserSetting mSharedUser;
18110
18111        public boolean isDumping(int type) {
18112            if (mTypes == 0 && type != DUMP_PREFERRED_XML) {
18113                return true;
18114            }
18115
18116            return (mTypes & type) != 0;
18117        }
18118
18119        public void setDump(int type) {
18120            mTypes |= type;
18121        }
18122
18123        public boolean isOptionEnabled(int option) {
18124            return (mOptions & option) != 0;
18125        }
18126
18127        public void setOptionEnabled(int option) {
18128            mOptions |= option;
18129        }
18130
18131        public boolean onTitlePrinted() {
18132            final boolean printed = mTitlePrinted;
18133            mTitlePrinted = true;
18134            return printed;
18135        }
18136
18137        public boolean getTitlePrinted() {
18138            return mTitlePrinted;
18139        }
18140
18141        public void setTitlePrinted(boolean enabled) {
18142            mTitlePrinted = enabled;
18143        }
18144
18145        public SharedUserSetting getSharedUser() {
18146            return mSharedUser;
18147        }
18148
18149        public void setSharedUser(SharedUserSetting user) {
18150            mSharedUser = user;
18151        }
18152    }
18153
18154    @Override
18155    public void onShellCommand(FileDescriptor in, FileDescriptor out,
18156            FileDescriptor err, String[] args, ResultReceiver resultReceiver) {
18157        (new PackageManagerShellCommand(this)).exec(
18158                this, in, out, err, args, resultReceiver);
18159    }
18160
18161    @Override
18162    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
18163        if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
18164                != PackageManager.PERMISSION_GRANTED) {
18165            pw.println("Permission Denial: can't dump ActivityManager from from pid="
18166                    + Binder.getCallingPid()
18167                    + ", uid=" + Binder.getCallingUid()
18168                    + " without permission "
18169                    + android.Manifest.permission.DUMP);
18170            return;
18171        }
18172
18173        DumpState dumpState = new DumpState();
18174        boolean fullPreferred = false;
18175        boolean checkin = false;
18176
18177        String packageName = null;
18178        ArraySet<String> permissionNames = null;
18179
18180        int opti = 0;
18181        while (opti < args.length) {
18182            String opt = args[opti];
18183            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
18184                break;
18185            }
18186            opti++;
18187
18188            if ("-a".equals(opt)) {
18189                // Right now we only know how to print all.
18190            } else if ("-h".equals(opt)) {
18191                pw.println("Package manager dump options:");
18192                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
18193                pw.println("    --checkin: dump for a checkin");
18194                pw.println("    -f: print details of intent filters");
18195                pw.println("    -h: print this help");
18196                pw.println("  cmd may be one of:");
18197                pw.println("    l[ibraries]: list known shared libraries");
18198                pw.println("    f[eatures]: list device features");
18199                pw.println("    k[eysets]: print known keysets");
18200                pw.println("    r[esolvers] [activity|service|receiver|content]: dump intent resolvers");
18201                pw.println("    perm[issions]: dump permissions");
18202                pw.println("    permission [name ...]: dump declaration and use of given permission");
18203                pw.println("    pref[erred]: print preferred package settings");
18204                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
18205                pw.println("    prov[iders]: dump content providers");
18206                pw.println("    p[ackages]: dump installed packages");
18207                pw.println("    s[hared-users]: dump shared user IDs");
18208                pw.println("    m[essages]: print collected runtime messages");
18209                pw.println("    v[erifiers]: print package verifier info");
18210                pw.println("    d[omain-preferred-apps]: print domains preferred apps");
18211                pw.println("    i[ntent-filter-verifiers]|ifv: print intent filter verifier info");
18212                pw.println("    version: print database version info");
18213                pw.println("    write: write current settings now");
18214                pw.println("    installs: details about install sessions");
18215                pw.println("    check-permission <permission> <package> [<user>]: does pkg hold perm?");
18216                pw.println("    dexopt: dump dexopt state");
18217                pw.println("    <package.name>: info about given package");
18218                return;
18219            } else if ("--checkin".equals(opt)) {
18220                checkin = true;
18221            } else if ("-f".equals(opt)) {
18222                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
18223            } else {
18224                pw.println("Unknown argument: " + opt + "; use -h for help");
18225            }
18226        }
18227
18228        // Is the caller requesting to dump a particular piece of data?
18229        if (opti < args.length) {
18230            String cmd = args[opti];
18231            opti++;
18232            // Is this a package name?
18233            if ("android".equals(cmd) || cmd.contains(".")) {
18234                packageName = cmd;
18235                // When dumping a single package, we always dump all of its
18236                // filter information since the amount of data will be reasonable.
18237                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
18238            } else if ("check-permission".equals(cmd)) {
18239                if (opti >= args.length) {
18240                    pw.println("Error: check-permission missing permission argument");
18241                    return;
18242                }
18243                String perm = args[opti];
18244                opti++;
18245                if (opti >= args.length) {
18246                    pw.println("Error: check-permission missing package argument");
18247                    return;
18248                }
18249                String pkg = args[opti];
18250                opti++;
18251                int user = UserHandle.getUserId(Binder.getCallingUid());
18252                if (opti < args.length) {
18253                    try {
18254                        user = Integer.parseInt(args[opti]);
18255                    } catch (NumberFormatException e) {
18256                        pw.println("Error: check-permission user argument is not a number: "
18257                                + args[opti]);
18258                        return;
18259                    }
18260                }
18261                pw.println(checkPermission(perm, pkg, user));
18262                return;
18263            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
18264                dumpState.setDump(DumpState.DUMP_LIBS);
18265            } else if ("f".equals(cmd) || "features".equals(cmd)) {
18266                dumpState.setDump(DumpState.DUMP_FEATURES);
18267            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
18268                if (opti >= args.length) {
18269                    dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS
18270                            | DumpState.DUMP_SERVICE_RESOLVERS
18271                            | DumpState.DUMP_RECEIVER_RESOLVERS
18272                            | DumpState.DUMP_CONTENT_RESOLVERS);
18273                } else {
18274                    while (opti < args.length) {
18275                        String name = args[opti];
18276                        if ("a".equals(name) || "activity".equals(name)) {
18277                            dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS);
18278                        } else if ("s".equals(name) || "service".equals(name)) {
18279                            dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS);
18280                        } else if ("r".equals(name) || "receiver".equals(name)) {
18281                            dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS);
18282                        } else if ("c".equals(name) || "content".equals(name)) {
18283                            dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS);
18284                        } else {
18285                            pw.println("Error: unknown resolver table type: " + name);
18286                            return;
18287                        }
18288                        opti++;
18289                    }
18290                }
18291            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
18292                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
18293            } else if ("permission".equals(cmd)) {
18294                if (opti >= args.length) {
18295                    pw.println("Error: permission requires permission name");
18296                    return;
18297                }
18298                permissionNames = new ArraySet<>();
18299                while (opti < args.length) {
18300                    permissionNames.add(args[opti]);
18301                    opti++;
18302                }
18303                dumpState.setDump(DumpState.DUMP_PERMISSIONS
18304                        | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS);
18305            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
18306                dumpState.setDump(DumpState.DUMP_PREFERRED);
18307            } else if ("preferred-xml".equals(cmd)) {
18308                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
18309                if (opti < args.length && "--full".equals(args[opti])) {
18310                    fullPreferred = true;
18311                    opti++;
18312                }
18313            } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) {
18314                dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED);
18315            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
18316                dumpState.setDump(DumpState.DUMP_PACKAGES);
18317            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
18318                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
18319            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
18320                dumpState.setDump(DumpState.DUMP_PROVIDERS);
18321            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
18322                dumpState.setDump(DumpState.DUMP_MESSAGES);
18323            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
18324                dumpState.setDump(DumpState.DUMP_VERIFIERS);
18325            } else if ("i".equals(cmd) || "ifv".equals(cmd)
18326                    || "intent-filter-verifiers".equals(cmd)) {
18327                dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS);
18328            } else if ("version".equals(cmd)) {
18329                dumpState.setDump(DumpState.DUMP_VERSION);
18330            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
18331                dumpState.setDump(DumpState.DUMP_KEYSETS);
18332            } else if ("installs".equals(cmd)) {
18333                dumpState.setDump(DumpState.DUMP_INSTALLS);
18334            } else if ("frozen".equals(cmd)) {
18335                dumpState.setDump(DumpState.DUMP_FROZEN);
18336            } else if ("dexopt".equals(cmd)) {
18337                dumpState.setDump(DumpState.DUMP_DEXOPT);
18338            } else if ("write".equals(cmd)) {
18339                synchronized (mPackages) {
18340                    mSettings.writeLPr();
18341                    pw.println("Settings written.");
18342                    return;
18343                }
18344            }
18345        }
18346
18347        if (checkin) {
18348            pw.println("vers,1");
18349        }
18350
18351        // reader
18352        synchronized (mPackages) {
18353            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
18354                if (!checkin) {
18355                    if (dumpState.onTitlePrinted())
18356                        pw.println();
18357                    pw.println("Database versions:");
18358                    mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, "  "));
18359                }
18360            }
18361
18362            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
18363                if (!checkin) {
18364                    if (dumpState.onTitlePrinted())
18365                        pw.println();
18366                    pw.println("Verifiers:");
18367                    pw.print("  Required: ");
18368                    pw.print(mRequiredVerifierPackage);
18369                    pw.print(" (uid=");
18370                    pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
18371                            UserHandle.USER_SYSTEM));
18372                    pw.println(")");
18373                } else if (mRequiredVerifierPackage != null) {
18374                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
18375                    pw.print(",");
18376                    pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
18377                            UserHandle.USER_SYSTEM));
18378                }
18379            }
18380
18381            if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) &&
18382                    packageName == null) {
18383                if (mIntentFilterVerifierComponent != null) {
18384                    String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
18385                    if (!checkin) {
18386                        if (dumpState.onTitlePrinted())
18387                            pw.println();
18388                        pw.println("Intent Filter Verifier:");
18389                        pw.print("  Using: ");
18390                        pw.print(verifierPackageName);
18391                        pw.print(" (uid=");
18392                        pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
18393                                UserHandle.USER_SYSTEM));
18394                        pw.println(")");
18395                    } else if (verifierPackageName != null) {
18396                        pw.print("ifv,"); pw.print(verifierPackageName);
18397                        pw.print(",");
18398                        pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
18399                                UserHandle.USER_SYSTEM));
18400                    }
18401                } else {
18402                    pw.println();
18403                    pw.println("No Intent Filter Verifier available!");
18404                }
18405            }
18406
18407            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
18408                boolean printedHeader = false;
18409                final Iterator<String> it = mSharedLibraries.keySet().iterator();
18410                while (it.hasNext()) {
18411                    String name = it.next();
18412                    SharedLibraryEntry ent = mSharedLibraries.get(name);
18413                    if (!checkin) {
18414                        if (!printedHeader) {
18415                            if (dumpState.onTitlePrinted())
18416                                pw.println();
18417                            pw.println("Libraries:");
18418                            printedHeader = true;
18419                        }
18420                        pw.print("  ");
18421                    } else {
18422                        pw.print("lib,");
18423                    }
18424                    pw.print(name);
18425                    if (!checkin) {
18426                        pw.print(" -> ");
18427                    }
18428                    if (ent.path != null) {
18429                        if (!checkin) {
18430                            pw.print("(jar) ");
18431                            pw.print(ent.path);
18432                        } else {
18433                            pw.print(",jar,");
18434                            pw.print(ent.path);
18435                        }
18436                    } else {
18437                        if (!checkin) {
18438                            pw.print("(apk) ");
18439                            pw.print(ent.apk);
18440                        } else {
18441                            pw.print(",apk,");
18442                            pw.print(ent.apk);
18443                        }
18444                    }
18445                    pw.println();
18446                }
18447            }
18448
18449            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
18450                if (dumpState.onTitlePrinted())
18451                    pw.println();
18452                if (!checkin) {
18453                    pw.println("Features:");
18454                }
18455
18456                for (FeatureInfo feat : mAvailableFeatures.values()) {
18457                    if (checkin) {
18458                        pw.print("feat,");
18459                        pw.print(feat.name);
18460                        pw.print(",");
18461                        pw.println(feat.version);
18462                    } else {
18463                        pw.print("  ");
18464                        pw.print(feat.name);
18465                        if (feat.version > 0) {
18466                            pw.print(" version=");
18467                            pw.print(feat.version);
18468                        }
18469                        pw.println();
18470                    }
18471                }
18472            }
18473
18474            if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) {
18475                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
18476                        : "Activity Resolver Table:", "  ", packageName,
18477                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
18478                    dumpState.setTitlePrinted(true);
18479                }
18480            }
18481            if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) {
18482                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
18483                        : "Receiver Resolver Table:", "  ", packageName,
18484                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
18485                    dumpState.setTitlePrinted(true);
18486                }
18487            }
18488            if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) {
18489                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
18490                        : "Service Resolver Table:", "  ", packageName,
18491                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
18492                    dumpState.setTitlePrinted(true);
18493                }
18494            }
18495            if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) {
18496                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
18497                        : "Provider Resolver Table:", "  ", packageName,
18498                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
18499                    dumpState.setTitlePrinted(true);
18500                }
18501            }
18502
18503            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
18504                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
18505                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
18506                    int user = mSettings.mPreferredActivities.keyAt(i);
18507                    if (pir.dump(pw,
18508                            dumpState.getTitlePrinted()
18509                                ? "\nPreferred Activities User " + user + ":"
18510                                : "Preferred Activities User " + user + ":", "  ",
18511                            packageName, true, false)) {
18512                        dumpState.setTitlePrinted(true);
18513                    }
18514                }
18515            }
18516
18517            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
18518                pw.flush();
18519                FileOutputStream fout = new FileOutputStream(fd);
18520                BufferedOutputStream str = new BufferedOutputStream(fout);
18521                XmlSerializer serializer = new FastXmlSerializer();
18522                try {
18523                    serializer.setOutput(str, StandardCharsets.UTF_8.name());
18524                    serializer.startDocument(null, true);
18525                    serializer.setFeature(
18526                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
18527                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
18528                    serializer.endDocument();
18529                    serializer.flush();
18530                } catch (IllegalArgumentException e) {
18531                    pw.println("Failed writing: " + e);
18532                } catch (IllegalStateException e) {
18533                    pw.println("Failed writing: " + e);
18534                } catch (IOException e) {
18535                    pw.println("Failed writing: " + e);
18536                }
18537            }
18538
18539            if (!checkin
18540                    && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)
18541                    && packageName == null) {
18542                pw.println();
18543                int count = mSettings.mPackages.size();
18544                if (count == 0) {
18545                    pw.println("No applications!");
18546                    pw.println();
18547                } else {
18548                    final String prefix = "  ";
18549                    Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values();
18550                    if (allPackageSettings.size() == 0) {
18551                        pw.println("No domain preferred apps!");
18552                        pw.println();
18553                    } else {
18554                        pw.println("App verification status:");
18555                        pw.println();
18556                        count = 0;
18557                        for (PackageSetting ps : allPackageSettings) {
18558                            IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
18559                            if (ivi == null || ivi.getPackageName() == null) continue;
18560                            pw.println(prefix + "Package: " + ivi.getPackageName());
18561                            pw.println(prefix + "Domains: " + ivi.getDomainsString());
18562                            pw.println(prefix + "Status:  " + ivi.getStatusString());
18563                            pw.println();
18564                            count++;
18565                        }
18566                        if (count == 0) {
18567                            pw.println(prefix + "No app verification established.");
18568                            pw.println();
18569                        }
18570                        for (int userId : sUserManager.getUserIds()) {
18571                            pw.println("App linkages for user " + userId + ":");
18572                            pw.println();
18573                            count = 0;
18574                            for (PackageSetting ps : allPackageSettings) {
18575                                final long status = ps.getDomainVerificationStatusForUser(userId);
18576                                if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
18577                                    continue;
18578                                }
18579                                pw.println(prefix + "Package: " + ps.name);
18580                                pw.println(prefix + "Domains: " + dumpDomainString(ps.name));
18581                                String statusStr = IntentFilterVerificationInfo.
18582                                        getStatusStringFromValue(status);
18583                                pw.println(prefix + "Status:  " + statusStr);
18584                                pw.println();
18585                                count++;
18586                            }
18587                            if (count == 0) {
18588                                pw.println(prefix + "No configured app linkages.");
18589                                pw.println();
18590                            }
18591                        }
18592                    }
18593                }
18594            }
18595
18596            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
18597                mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState);
18598                if (packageName == null && permissionNames == null) {
18599                    for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) {
18600                        if (iperm == 0) {
18601                            if (dumpState.onTitlePrinted())
18602                                pw.println();
18603                            pw.println("AppOp Permissions:");
18604                        }
18605                        pw.print("  AppOp Permission ");
18606                        pw.print(mAppOpPermissionPackages.keyAt(iperm));
18607                        pw.println(":");
18608                        ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm);
18609                        for (int ipkg=0; ipkg<pkgs.size(); ipkg++) {
18610                            pw.print("    "); pw.println(pkgs.valueAt(ipkg));
18611                        }
18612                    }
18613                }
18614            }
18615
18616            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
18617                boolean printedSomething = false;
18618                for (PackageParser.Provider p : mProviders.mProviders.values()) {
18619                    if (packageName != null && !packageName.equals(p.info.packageName)) {
18620                        continue;
18621                    }
18622                    if (!printedSomething) {
18623                        if (dumpState.onTitlePrinted())
18624                            pw.println();
18625                        pw.println("Registered ContentProviders:");
18626                        printedSomething = true;
18627                    }
18628                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
18629                    pw.print("    "); pw.println(p.toString());
18630                }
18631                printedSomething = false;
18632                for (Map.Entry<String, PackageParser.Provider> entry :
18633                        mProvidersByAuthority.entrySet()) {
18634                    PackageParser.Provider p = entry.getValue();
18635                    if (packageName != null && !packageName.equals(p.info.packageName)) {
18636                        continue;
18637                    }
18638                    if (!printedSomething) {
18639                        if (dumpState.onTitlePrinted())
18640                            pw.println();
18641                        pw.println("ContentProvider Authorities:");
18642                        printedSomething = true;
18643                    }
18644                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
18645                    pw.print("    "); pw.println(p.toString());
18646                    if (p.info != null && p.info.applicationInfo != null) {
18647                        final String appInfo = p.info.applicationInfo.toString();
18648                        pw.print("      applicationInfo="); pw.println(appInfo);
18649                    }
18650                }
18651            }
18652
18653            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
18654                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
18655            }
18656
18657            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
18658                mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin);
18659            }
18660
18661            if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
18662                mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin);
18663            }
18664
18665            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) {
18666                mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState);
18667            }
18668
18669            if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
18670                // XXX should handle packageName != null by dumping only install data that
18671                // the given package is involved with.
18672                if (dumpState.onTitlePrinted()) pw.println();
18673                mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
18674            }
18675
18676            if (!checkin && dumpState.isDumping(DumpState.DUMP_FROZEN) && packageName == null) {
18677                // XXX should handle packageName != null by dumping only install data that
18678                // the given package is involved with.
18679                if (dumpState.onTitlePrinted()) pw.println();
18680
18681                final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
18682                ipw.println();
18683                ipw.println("Frozen packages:");
18684                ipw.increaseIndent();
18685                if (mFrozenPackages.size() == 0) {
18686                    ipw.println("(none)");
18687                } else {
18688                    for (int i = 0; i < mFrozenPackages.size(); i++) {
18689                        ipw.println(mFrozenPackages.valueAt(i));
18690                    }
18691                }
18692                ipw.decreaseIndent();
18693            }
18694
18695            if (!checkin && dumpState.isDumping(DumpState.DUMP_DEXOPT)) {
18696                if (dumpState.onTitlePrinted()) pw.println();
18697                dumpDexoptStateLPr(pw, packageName);
18698            }
18699
18700            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
18701                if (dumpState.onTitlePrinted()) pw.println();
18702                mSettings.dumpReadMessagesLPr(pw, dumpState);
18703
18704                pw.println();
18705                pw.println("Package warning messages:");
18706                BufferedReader in = null;
18707                String line = null;
18708                try {
18709                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
18710                    while ((line = in.readLine()) != null) {
18711                        if (line.contains("ignored: updated version")) continue;
18712                        pw.println(line);
18713                    }
18714                } catch (IOException ignored) {
18715                } finally {
18716                    IoUtils.closeQuietly(in);
18717                }
18718            }
18719
18720            if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) {
18721                BufferedReader in = null;
18722                String line = null;
18723                try {
18724                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
18725                    while ((line = in.readLine()) != null) {
18726                        if (line.contains("ignored: updated version")) continue;
18727                        pw.print("msg,");
18728                        pw.println(line);
18729                    }
18730                } catch (IOException ignored) {
18731                } finally {
18732                    IoUtils.closeQuietly(in);
18733                }
18734            }
18735        }
18736    }
18737
18738    private void dumpDexoptStateLPr(PrintWriter pw, String packageName) {
18739        final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
18740        ipw.println();
18741        ipw.println("Dexopt state:");
18742        ipw.increaseIndent();
18743        Collection<PackageParser.Package> packages = null;
18744        if (packageName != null) {
18745            PackageParser.Package targetPackage = mPackages.get(packageName);
18746            if (targetPackage != null) {
18747                packages = Collections.singletonList(targetPackage);
18748            } else {
18749                ipw.println("Unable to find package: " + packageName);
18750                return;
18751            }
18752        } else {
18753            packages = mPackages.values();
18754        }
18755
18756        for (PackageParser.Package pkg : packages) {
18757            ipw.println("[" + pkg.packageName + "]");
18758            ipw.increaseIndent();
18759            mPackageDexOptimizer.dumpDexoptState(ipw, pkg);
18760            ipw.decreaseIndent();
18761        }
18762    }
18763
18764    private String dumpDomainString(String packageName) {
18765        List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName)
18766                .getList();
18767        List<IntentFilter> filters = getAllIntentFilters(packageName).getList();
18768
18769        ArraySet<String> result = new ArraySet<>();
18770        if (iviList.size() > 0) {
18771            for (IntentFilterVerificationInfo ivi : iviList) {
18772                for (String host : ivi.getDomains()) {
18773                    result.add(host);
18774                }
18775            }
18776        }
18777        if (filters != null && filters.size() > 0) {
18778            for (IntentFilter filter : filters) {
18779                if (filter.hasCategory(Intent.CATEGORY_BROWSABLE)
18780                        && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
18781                                filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) {
18782                    result.addAll(filter.getHostsList());
18783                }
18784            }
18785        }
18786
18787        StringBuilder sb = new StringBuilder(result.size() * 16);
18788        for (String domain : result) {
18789            if (sb.length() > 0) sb.append(" ");
18790            sb.append(domain);
18791        }
18792        return sb.toString();
18793    }
18794
18795    // ------- apps on sdcard specific code -------
18796    static final boolean DEBUG_SD_INSTALL = false;
18797
18798    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
18799
18800    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
18801
18802    private boolean mMediaMounted = false;
18803
18804    static String getEncryptKey() {
18805        try {
18806            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
18807                    SD_ENCRYPTION_KEYSTORE_NAME);
18808            if (sdEncKey == null) {
18809                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
18810                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
18811                if (sdEncKey == null) {
18812                    Slog.e(TAG, "Failed to create encryption keys");
18813                    return null;
18814                }
18815            }
18816            return sdEncKey;
18817        } catch (NoSuchAlgorithmException nsae) {
18818            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
18819            return null;
18820        } catch (IOException ioe) {
18821            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
18822            return null;
18823        }
18824    }
18825
18826    /*
18827     * Update media status on PackageManager.
18828     */
18829    @Override
18830    public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
18831        int callingUid = Binder.getCallingUid();
18832        if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
18833            throw new SecurityException("Media status can only be updated by the system");
18834        }
18835        // reader; this apparently protects mMediaMounted, but should probably
18836        // be a different lock in that case.
18837        synchronized (mPackages) {
18838            Log.i(TAG, "Updating external media status from "
18839                    + (mMediaMounted ? "mounted" : "unmounted") + " to "
18840                    + (mediaStatus ? "mounted" : "unmounted"));
18841            if (DEBUG_SD_INSTALL)
18842                Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
18843                        + ", mMediaMounted=" + mMediaMounted);
18844            if (mediaStatus == mMediaMounted) {
18845                final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
18846                        : 0, -1);
18847                mHandler.sendMessage(msg);
18848                return;
18849            }
18850            mMediaMounted = mediaStatus;
18851        }
18852        // Queue up an async operation since the package installation may take a
18853        // little while.
18854        mHandler.post(new Runnable() {
18855            public void run() {
18856                updateExternalMediaStatusInner(mediaStatus, reportStatus, true);
18857            }
18858        });
18859    }
18860
18861    /**
18862     * Called by MountService when the initial ASECs to scan are available.
18863     * Should block until all the ASEC containers are finished being scanned.
18864     */
18865    public void scanAvailableAsecs() {
18866        updateExternalMediaStatusInner(true, false, false);
18867    }
18868
18869    /*
18870     * Collect information of applications on external media, map them against
18871     * existing containers and update information based on current mount status.
18872     * Please note that we always have to report status if reportStatus has been
18873     * set to true especially when unloading packages.
18874     */
18875    private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus,
18876            boolean externalStorage) {
18877        ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>();
18878        int[] uidArr = EmptyArray.INT;
18879
18880        final String[] list = PackageHelper.getSecureContainerList();
18881        if (ArrayUtils.isEmpty(list)) {
18882            Log.i(TAG, "No secure containers found");
18883        } else {
18884            // Process list of secure containers and categorize them
18885            // as active or stale based on their package internal state.
18886
18887            // reader
18888            synchronized (mPackages) {
18889                for (String cid : list) {
18890                    // Leave stages untouched for now; installer service owns them
18891                    if (PackageInstallerService.isStageName(cid)) continue;
18892
18893                    if (DEBUG_SD_INSTALL)
18894                        Log.i(TAG, "Processing container " + cid);
18895                    String pkgName = getAsecPackageName(cid);
18896                    if (pkgName == null) {
18897                        Slog.i(TAG, "Found stale container " + cid + " with no package name");
18898                        continue;
18899                    }
18900                    if (DEBUG_SD_INSTALL)
18901                        Log.i(TAG, "Looking for pkg : " + pkgName);
18902
18903                    final PackageSetting ps = mSettings.mPackages.get(pkgName);
18904                    if (ps == null) {
18905                        Slog.i(TAG, "Found stale container " + cid + " with no matching settings");
18906                        continue;
18907                    }
18908
18909                    /*
18910                     * Skip packages that are not external if we're unmounting
18911                     * external storage.
18912                     */
18913                    if (externalStorage && !isMounted && !isExternal(ps)) {
18914                        continue;
18915                    }
18916
18917                    final AsecInstallArgs args = new AsecInstallArgs(cid,
18918                            getAppDexInstructionSets(ps), ps.isForwardLocked());
18919                    // The package status is changed only if the code path
18920                    // matches between settings and the container id.
18921                    if (ps.codePathString != null
18922                            && ps.codePathString.startsWith(args.getCodePath())) {
18923                        if (DEBUG_SD_INSTALL) {
18924                            Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
18925                                    + " at code path: " + ps.codePathString);
18926                        }
18927
18928                        // We do have a valid package installed on sdcard
18929                        processCids.put(args, ps.codePathString);
18930                        final int uid = ps.appId;
18931                        if (uid != -1) {
18932                            uidArr = ArrayUtils.appendInt(uidArr, uid);
18933                        }
18934                    } else {
18935                        Slog.i(TAG, "Found stale container " + cid + ": expected codePath="
18936                                + ps.codePathString);
18937                    }
18938                }
18939            }
18940
18941            Arrays.sort(uidArr);
18942        }
18943
18944        // Process packages with valid entries.
18945        if (isMounted) {
18946            if (DEBUG_SD_INSTALL)
18947                Log.i(TAG, "Loading packages");
18948            loadMediaPackages(processCids, uidArr, externalStorage);
18949            startCleaningPackages();
18950            mInstallerService.onSecureContainersAvailable();
18951        } else {
18952            if (DEBUG_SD_INSTALL)
18953                Log.i(TAG, "Unloading packages");
18954            unloadMediaPackages(processCids, uidArr, reportStatus);
18955        }
18956    }
18957
18958    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
18959            ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) {
18960        final int size = infos.size();
18961        final String[] packageNames = new String[size];
18962        final int[] packageUids = new int[size];
18963        for (int i = 0; i < size; i++) {
18964            final ApplicationInfo info = infos.get(i);
18965            packageNames[i] = info.packageName;
18966            packageUids[i] = info.uid;
18967        }
18968        sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids,
18969                finishedReceiver);
18970    }
18971
18972    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
18973            ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
18974        sendResourcesChangedBroadcast(mediaStatus, replacing,
18975                pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver);
18976    }
18977
18978    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
18979            String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
18980        int size = pkgList.length;
18981        if (size > 0) {
18982            // Send broadcasts here
18983            Bundle extras = new Bundle();
18984            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
18985            if (uidArr != null) {
18986                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
18987            }
18988            if (replacing) {
18989                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
18990            }
18991            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
18992                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
18993            sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null);
18994        }
18995    }
18996
18997   /*
18998     * Look at potentially valid container ids from processCids If package
18999     * information doesn't match the one on record or package scanning fails,
19000     * the cid is added to list of removeCids. We currently don't delete stale
19001     * containers.
19002     */
19003    private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr,
19004            boolean externalStorage) {
19005        ArrayList<String> pkgList = new ArrayList<String>();
19006        Set<AsecInstallArgs> keys = processCids.keySet();
19007
19008        for (AsecInstallArgs args : keys) {
19009            String codePath = processCids.get(args);
19010            if (DEBUG_SD_INSTALL)
19011                Log.i(TAG, "Loading container : " + args.cid);
19012            int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
19013            try {
19014                // Make sure there are no container errors first.
19015                if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
19016                    Slog.e(TAG, "Failed to mount cid : " + args.cid
19017                            + " when installing from sdcard");
19018                    continue;
19019                }
19020                // Check code path here.
19021                if (codePath == null || !codePath.startsWith(args.getCodePath())) {
19022                    Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
19023                            + " does not match one in settings " + codePath);
19024                    continue;
19025                }
19026                // Parse package
19027                int parseFlags = mDefParseFlags;
19028                if (args.isExternalAsec()) {
19029                    parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE;
19030                }
19031                if (args.isFwdLocked()) {
19032                    parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
19033                }
19034
19035                synchronized (mInstallLock) {
19036                    PackageParser.Package pkg = null;
19037                    try {
19038                        // Sadly we don't know the package name yet to freeze it
19039                        pkg = scanPackageTracedLI(new File(codePath), parseFlags,
19040                                SCAN_IGNORE_FROZEN, 0, null);
19041                    } catch (PackageManagerException e) {
19042                        Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage());
19043                    }
19044                    // Scan the package
19045                    if (pkg != null) {
19046                        /*
19047                         * TODO why is the lock being held? doPostInstall is
19048                         * called in other places without the lock. This needs
19049                         * to be straightened out.
19050                         */
19051                        // writer
19052                        synchronized (mPackages) {
19053                            retCode = PackageManager.INSTALL_SUCCEEDED;
19054                            pkgList.add(pkg.packageName);
19055                            // Post process args
19056                            args.doPostInstall(PackageManager.INSTALL_SUCCEEDED,
19057                                    pkg.applicationInfo.uid);
19058                        }
19059                    } else {
19060                        Slog.i(TAG, "Failed to install pkg from  " + codePath + " from sdcard");
19061                    }
19062                }
19063
19064            } finally {
19065                if (retCode != PackageManager.INSTALL_SUCCEEDED) {
19066                    Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode);
19067                }
19068            }
19069        }
19070        // writer
19071        synchronized (mPackages) {
19072            // If the platform SDK has changed since the last time we booted,
19073            // we need to re-grant app permission to catch any new ones that
19074            // appear. This is really a hack, and means that apps can in some
19075            // cases get permissions that the user didn't initially explicitly
19076            // allow... it would be nice to have some better way to handle
19077            // this situation.
19078            final VersionInfo ver = externalStorage ? mSettings.getExternalVersion()
19079                    : mSettings.getInternalVersion();
19080            final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL
19081                    : StorageManager.UUID_PRIVATE_INTERNAL;
19082
19083            int updateFlags = UPDATE_PERMISSIONS_ALL;
19084            if (ver.sdkVersion != mSdkVersion) {
19085                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
19086                        + mSdkVersion + "; regranting permissions for external");
19087                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
19088            }
19089            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
19090
19091            // Yay, everything is now upgraded
19092            ver.forceCurrent();
19093
19094            // can downgrade to reader
19095            // Persist settings
19096            mSettings.writeLPr();
19097        }
19098        // Send a broadcast to let everyone know we are done processing
19099        if (pkgList.size() > 0) {
19100            sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
19101        }
19102    }
19103
19104   /*
19105     * Utility method to unload a list of specified containers
19106     */
19107    private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) {
19108        // Just unmount all valid containers.
19109        for (AsecInstallArgs arg : cidArgs) {
19110            synchronized (mInstallLock) {
19111                arg.doPostDeleteLI(false);
19112           }
19113       }
19114   }
19115
19116    /*
19117     * Unload packages mounted on external media. This involves deleting package
19118     * data from internal structures, sending broadcasts about disabled packages,
19119     * gc'ing to free up references, unmounting all secure containers
19120     * corresponding to packages on external media, and posting a
19121     * UPDATED_MEDIA_STATUS message if status has been requested. Please note
19122     * that we always have to post this message if status has been requested no
19123     * matter what.
19124     */
19125    private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[],
19126            final boolean reportStatus) {
19127        if (DEBUG_SD_INSTALL)
19128            Log.i(TAG, "unloading media packages");
19129        ArrayList<String> pkgList = new ArrayList<String>();
19130        ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>();
19131        final Set<AsecInstallArgs> keys = processCids.keySet();
19132        for (AsecInstallArgs args : keys) {
19133            String pkgName = args.getPackageName();
19134            if (DEBUG_SD_INSTALL)
19135                Log.i(TAG, "Trying to unload pkg : " + pkgName);
19136            // Delete package internally
19137            PackageRemovedInfo outInfo = new PackageRemovedInfo();
19138            synchronized (mInstallLock) {
19139                final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
19140                final boolean res;
19141                try (PackageFreezer freezer = freezePackageForDelete(pkgName, deleteFlags,
19142                        "unloadMediaPackages")) {
19143                    res = deletePackageLIF(pkgName, null, false, null, deleteFlags, outInfo, false,
19144                            null);
19145                }
19146                if (res) {
19147                    pkgList.add(pkgName);
19148                } else {
19149                    Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
19150                    failedList.add(args);
19151                }
19152            }
19153        }
19154
19155        // reader
19156        synchronized (mPackages) {
19157            // We didn't update the settings after removing each package;
19158            // write them now for all packages.
19159            mSettings.writeLPr();
19160        }
19161
19162        // We have to absolutely send UPDATED_MEDIA_STATUS only
19163        // after confirming that all the receivers processed the ordered
19164        // broadcast when packages get disabled, force a gc to clean things up.
19165        // and unload all the containers.
19166        if (pkgList.size() > 0) {
19167            sendResourcesChangedBroadcast(false, false, pkgList, uidArr,
19168                    new IIntentReceiver.Stub() {
19169                public void performReceive(Intent intent, int resultCode, String data,
19170                        Bundle extras, boolean ordered, boolean sticky,
19171                        int sendingUser) throws RemoteException {
19172                    Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
19173                            reportStatus ? 1 : 0, 1, keys);
19174                    mHandler.sendMessage(msg);
19175                }
19176            });
19177        } else {
19178            Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
19179                    keys);
19180            mHandler.sendMessage(msg);
19181        }
19182    }
19183
19184    private void loadPrivatePackages(final VolumeInfo vol) {
19185        mHandler.post(new Runnable() {
19186            @Override
19187            public void run() {
19188                loadPrivatePackagesInner(vol);
19189            }
19190        });
19191    }
19192
19193    private void loadPrivatePackagesInner(VolumeInfo vol) {
19194        final String volumeUuid = vol.fsUuid;
19195        if (TextUtils.isEmpty(volumeUuid)) {
19196            Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring");
19197            return;
19198        }
19199
19200        final ArrayList<PackageFreezer> freezers = new ArrayList<>();
19201        final ArrayList<ApplicationInfo> loaded = new ArrayList<>();
19202        final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE;
19203
19204        final VersionInfo ver;
19205        final List<PackageSetting> packages;
19206        synchronized (mPackages) {
19207            ver = mSettings.findOrCreateVersion(volumeUuid);
19208            packages = mSettings.getVolumePackagesLPr(volumeUuid);
19209        }
19210
19211        for (PackageSetting ps : packages) {
19212            freezers.add(freezePackage(ps.name, "loadPrivatePackagesInner"));
19213            synchronized (mInstallLock) {
19214                final PackageParser.Package pkg;
19215                try {
19216                    pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null);
19217                    loaded.add(pkg.applicationInfo);
19218
19219                } catch (PackageManagerException e) {
19220                    Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage());
19221                }
19222
19223                if (!Build.FINGERPRINT.equals(ver.fingerprint)) {
19224                    clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
19225                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
19226                                    | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
19227                }
19228            }
19229        }
19230
19231        // Reconcile app data for all started/unlocked users
19232        final StorageManager sm = mContext.getSystemService(StorageManager.class);
19233        final UserManager um = mContext.getSystemService(UserManager.class);
19234        UserManagerInternal umInternal = getUserManagerInternal();
19235        for (UserInfo user : um.getUsers()) {
19236            final int flags;
19237            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
19238                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
19239            } else if (umInternal.isUserRunning(user.id)) {
19240                flags = StorageManager.FLAG_STORAGE_DE;
19241            } else {
19242                continue;
19243            }
19244
19245            try {
19246                sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags);
19247                synchronized (mInstallLock) {
19248                    reconcileAppsDataLI(volumeUuid, user.id, flags);
19249                }
19250            } catch (IllegalStateException e) {
19251                // Device was probably ejected, and we'll process that event momentarily
19252                Slog.w(TAG, "Failed to prepare storage: " + e);
19253            }
19254        }
19255
19256        synchronized (mPackages) {
19257            int updateFlags = UPDATE_PERMISSIONS_ALL;
19258            if (ver.sdkVersion != mSdkVersion) {
19259                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
19260                        + mSdkVersion + "; regranting permissions for " + volumeUuid);
19261                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
19262            }
19263            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
19264
19265            // Yay, everything is now upgraded
19266            ver.forceCurrent();
19267
19268            mSettings.writeLPr();
19269        }
19270
19271        for (PackageFreezer freezer : freezers) {
19272            freezer.close();
19273        }
19274
19275        if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded);
19276        sendResourcesChangedBroadcast(true, false, loaded, null);
19277    }
19278
19279    private void unloadPrivatePackages(final VolumeInfo vol) {
19280        mHandler.post(new Runnable() {
19281            @Override
19282            public void run() {
19283                unloadPrivatePackagesInner(vol);
19284            }
19285        });
19286    }
19287
19288    private void unloadPrivatePackagesInner(VolumeInfo vol) {
19289        final String volumeUuid = vol.fsUuid;
19290        if (TextUtils.isEmpty(volumeUuid)) {
19291            Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring");
19292            return;
19293        }
19294
19295        final ArrayList<ApplicationInfo> unloaded = new ArrayList<>();
19296        synchronized (mInstallLock) {
19297        synchronized (mPackages) {
19298            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid);
19299            for (PackageSetting ps : packages) {
19300                if (ps.pkg == null) continue;
19301
19302                final ApplicationInfo info = ps.pkg.applicationInfo;
19303                final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
19304                final PackageRemovedInfo outInfo = new PackageRemovedInfo();
19305
19306                try (PackageFreezer freezer = freezePackageForDelete(ps.name, deleteFlags,
19307                        "unloadPrivatePackagesInner")) {
19308                    if (deletePackageLIF(ps.name, null, false, null, deleteFlags, outInfo,
19309                            false, null)) {
19310                        unloaded.add(info);
19311                    } else {
19312                        Slog.w(TAG, "Failed to unload " + ps.codePath);
19313                    }
19314                }
19315
19316                // Try very hard to release any references to this package
19317                // so we don't risk the system server being killed due to
19318                // open FDs
19319                AttributeCache.instance().removePackage(ps.name);
19320            }
19321
19322            mSettings.writeLPr();
19323        }
19324        }
19325
19326        if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded);
19327        sendResourcesChangedBroadcast(false, false, unloaded, null);
19328
19329        // Try very hard to release any references to this path so we don't risk
19330        // the system server being killed due to open FDs
19331        ResourcesManager.getInstance().invalidatePath(vol.getPath().getAbsolutePath());
19332
19333        for (int i = 0; i < 3; i++) {
19334            System.gc();
19335            System.runFinalization();
19336        }
19337    }
19338
19339    /**
19340     * Prepare storage areas for given user on all mounted devices.
19341     */
19342    void prepareUserData(int userId, int userSerial, int flags) {
19343        synchronized (mInstallLock) {
19344            final StorageManager storage = mContext.getSystemService(StorageManager.class);
19345            for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
19346                final String volumeUuid = vol.getFsUuid();
19347                prepareUserDataLI(volumeUuid, userId, userSerial, flags, true);
19348            }
19349        }
19350    }
19351
19352    private void prepareUserDataLI(String volumeUuid, int userId, int userSerial, int flags,
19353            boolean allowRecover) {
19354        // Prepare storage and verify that serial numbers are consistent; if
19355        // there's a mismatch we need to destroy to avoid leaking data
19356        final StorageManager storage = mContext.getSystemService(StorageManager.class);
19357        try {
19358            storage.prepareUserStorage(volumeUuid, userId, userSerial, flags);
19359
19360            if ((flags & StorageManager.FLAG_STORAGE_DE) != 0 && !mOnlyCore) {
19361                UserManagerService.enforceSerialNumber(
19362                        Environment.getDataUserDeDirectory(volumeUuid, userId), userSerial);
19363                if (Objects.equals(volumeUuid, StorageManager.UUID_PRIVATE_INTERNAL)) {
19364                    UserManagerService.enforceSerialNumber(
19365                            Environment.getDataSystemDeDirectory(userId), userSerial);
19366                }
19367            }
19368            if ((flags & StorageManager.FLAG_STORAGE_CE) != 0 && !mOnlyCore) {
19369                UserManagerService.enforceSerialNumber(
19370                        Environment.getDataUserCeDirectory(volumeUuid, userId), userSerial);
19371                if (Objects.equals(volumeUuid, StorageManager.UUID_PRIVATE_INTERNAL)) {
19372                    UserManagerService.enforceSerialNumber(
19373                            Environment.getDataSystemCeDirectory(userId), userSerial);
19374                }
19375            }
19376
19377            synchronized (mInstallLock) {
19378                mInstaller.createUserData(volumeUuid, userId, userSerial, flags);
19379            }
19380        } catch (Exception e) {
19381            logCriticalInfo(Log.WARN, "Destroying user " + userId + " on volume " + volumeUuid
19382                    + " because we failed to prepare: " + e);
19383            destroyUserDataLI(volumeUuid, userId,
19384                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
19385
19386            if (allowRecover) {
19387                // Try one last time; if we fail again we're really in trouble
19388                prepareUserDataLI(volumeUuid, userId, userSerial, flags, false);
19389            }
19390        }
19391    }
19392
19393    /**
19394     * Destroy storage areas for given user on all mounted devices.
19395     */
19396    void destroyUserData(int userId, int flags) {
19397        synchronized (mInstallLock) {
19398            final StorageManager storage = mContext.getSystemService(StorageManager.class);
19399            for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
19400                final String volumeUuid = vol.getFsUuid();
19401                destroyUserDataLI(volumeUuid, userId, flags);
19402            }
19403        }
19404    }
19405
19406    private void destroyUserDataLI(String volumeUuid, int userId, int flags) {
19407        final StorageManager storage = mContext.getSystemService(StorageManager.class);
19408        try {
19409            // Clean up app data, profile data, and media data
19410            mInstaller.destroyUserData(volumeUuid, userId, flags);
19411
19412            // Clean up system data
19413            if (Objects.equals(volumeUuid, StorageManager.UUID_PRIVATE_INTERNAL)) {
19414                if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) {
19415                    FileUtils.deleteContentsAndDir(Environment.getUserSystemDirectory(userId));
19416                    FileUtils.deleteContentsAndDir(Environment.getDataSystemDeDirectory(userId));
19417                }
19418                if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
19419                    FileUtils.deleteContentsAndDir(Environment.getDataSystemCeDirectory(userId));
19420                }
19421            }
19422
19423            // Data with special labels is now gone, so finish the job
19424            storage.destroyUserStorage(volumeUuid, userId, flags);
19425
19426        } catch (Exception e) {
19427            logCriticalInfo(Log.WARN,
19428                    "Failed to destroy user " + userId + " on volume " + volumeUuid + ": " + e);
19429        }
19430    }
19431
19432    /**
19433     * Examine all users present on given mounted volume, and destroy data
19434     * belonging to users that are no longer valid, or whose user ID has been
19435     * recycled.
19436     */
19437    private void reconcileUsers(String volumeUuid) {
19438        final List<File> files = new ArrayList<>();
19439        Collections.addAll(files, FileUtils
19440                .listFilesOrEmpty(Environment.getDataUserDeDirectory(volumeUuid)));
19441        Collections.addAll(files, FileUtils
19442                .listFilesOrEmpty(Environment.getDataUserCeDirectory(volumeUuid)));
19443        Collections.addAll(files, FileUtils
19444                .listFilesOrEmpty(Environment.getDataSystemDeDirectory()));
19445        Collections.addAll(files, FileUtils
19446                .listFilesOrEmpty(Environment.getDataSystemCeDirectory()));
19447        for (File file : files) {
19448            if (!file.isDirectory()) continue;
19449
19450            final int userId;
19451            final UserInfo info;
19452            try {
19453                userId = Integer.parseInt(file.getName());
19454                info = sUserManager.getUserInfo(userId);
19455            } catch (NumberFormatException e) {
19456                Slog.w(TAG, "Invalid user directory " + file);
19457                continue;
19458            }
19459
19460            boolean destroyUser = false;
19461            if (info == null) {
19462                logCriticalInfo(Log.WARN, "Destroying user directory " + file
19463                        + " because no matching user was found");
19464                destroyUser = true;
19465            } else if (!mOnlyCore) {
19466                try {
19467                    UserManagerService.enforceSerialNumber(file, info.serialNumber);
19468                } catch (IOException e) {
19469                    logCriticalInfo(Log.WARN, "Destroying user directory " + file
19470                            + " because we failed to enforce serial number: " + e);
19471                    destroyUser = true;
19472                }
19473            }
19474
19475            if (destroyUser) {
19476                synchronized (mInstallLock) {
19477                    destroyUserDataLI(volumeUuid, userId,
19478                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
19479                }
19480            }
19481        }
19482    }
19483
19484    private void assertPackageKnown(String volumeUuid, String packageName)
19485            throws PackageManagerException {
19486        synchronized (mPackages) {
19487            final PackageSetting ps = mSettings.mPackages.get(packageName);
19488            if (ps == null) {
19489                throw new PackageManagerException("Package " + packageName + " is unknown");
19490            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
19491                throw new PackageManagerException(
19492                        "Package " + packageName + " found on unknown volume " + volumeUuid
19493                                + "; expected volume " + ps.volumeUuid);
19494            }
19495        }
19496    }
19497
19498    private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId)
19499            throws PackageManagerException {
19500        synchronized (mPackages) {
19501            final PackageSetting ps = mSettings.mPackages.get(packageName);
19502            if (ps == null) {
19503                throw new PackageManagerException("Package " + packageName + " is unknown");
19504            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
19505                throw new PackageManagerException(
19506                        "Package " + packageName + " found on unknown volume " + volumeUuid
19507                                + "; expected volume " + ps.volumeUuid);
19508            } else if (!ps.getInstalled(userId)) {
19509                throw new PackageManagerException(
19510                        "Package " + packageName + " not installed for user " + userId);
19511            }
19512        }
19513    }
19514
19515    /**
19516     * Examine all apps present on given mounted volume, and destroy apps that
19517     * aren't expected, either due to uninstallation or reinstallation on
19518     * another volume.
19519     */
19520    private void reconcileApps(String volumeUuid) {
19521        final File[] files = FileUtils
19522                .listFilesOrEmpty(Environment.getDataAppDirectory(volumeUuid));
19523        for (File file : files) {
19524            final boolean isPackage = (isApkFile(file) || file.isDirectory())
19525                    && !PackageInstallerService.isStageName(file.getName());
19526            if (!isPackage) {
19527                // Ignore entries which are not packages
19528                continue;
19529            }
19530
19531            try {
19532                final PackageLite pkg = PackageParser.parsePackageLite(file,
19533                        PackageParser.PARSE_MUST_BE_APK);
19534                assertPackageKnown(volumeUuid, pkg.packageName);
19535
19536            } catch (PackageParserException | PackageManagerException e) {
19537                logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
19538                synchronized (mInstallLock) {
19539                    removeCodePathLI(file);
19540                }
19541            }
19542        }
19543    }
19544
19545    /**
19546     * Reconcile all app data for the given user.
19547     * <p>
19548     * Verifies that directories exist and that ownership and labeling is
19549     * correct for all installed apps on all mounted volumes.
19550     */
19551    void reconcileAppsData(int userId, int flags) {
19552        final StorageManager storage = mContext.getSystemService(StorageManager.class);
19553        for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
19554            final String volumeUuid = vol.getFsUuid();
19555            synchronized (mInstallLock) {
19556                reconcileAppsDataLI(volumeUuid, userId, flags);
19557            }
19558        }
19559    }
19560
19561    /**
19562     * Reconcile all app data on given mounted volume.
19563     * <p>
19564     * Destroys app data that isn't expected, either due to uninstallation or
19565     * reinstallation on another volume.
19566     * <p>
19567     * Verifies that directories exist and that ownership and labeling is
19568     * correct for all installed apps.
19569     */
19570    private void reconcileAppsDataLI(String volumeUuid, int userId, int flags) {
19571        Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x"
19572                + Integer.toHexString(flags));
19573
19574        final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId);
19575        final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId);
19576
19577        boolean restoreconNeeded = false;
19578
19579        // First look for stale data that doesn't belong, and check if things
19580        // have changed since we did our last restorecon
19581        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
19582            if (StorageManager.isFileEncryptedNativeOrEmulated()
19583                    && !StorageManager.isUserKeyUnlocked(userId)) {
19584                throw new RuntimeException(
19585                        "Yikes, someone asked us to reconcile CE storage while " + userId
19586                                + " was still locked; this would have caused massive data loss!");
19587            }
19588
19589            restoreconNeeded |= SELinuxMMAC.isRestoreconNeeded(ceDir);
19590
19591            final File[] files = FileUtils.listFilesOrEmpty(ceDir);
19592            for (File file : files) {
19593                final String packageName = file.getName();
19594                try {
19595                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
19596                } catch (PackageManagerException e) {
19597                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
19598                    try {
19599                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
19600                                StorageManager.FLAG_STORAGE_CE, 0);
19601                    } catch (InstallerException e2) {
19602                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
19603                    }
19604                }
19605            }
19606        }
19607        if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) {
19608            restoreconNeeded |= SELinuxMMAC.isRestoreconNeeded(deDir);
19609
19610            final File[] files = FileUtils.listFilesOrEmpty(deDir);
19611            for (File file : files) {
19612                final String packageName = file.getName();
19613                try {
19614                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
19615                } catch (PackageManagerException e) {
19616                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
19617                    try {
19618                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
19619                                StorageManager.FLAG_STORAGE_DE, 0);
19620                    } catch (InstallerException e2) {
19621                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
19622                    }
19623                }
19624            }
19625        }
19626
19627        // Ensure that data directories are ready to roll for all packages
19628        // installed for this volume and user
19629        final List<PackageSetting> packages;
19630        synchronized (mPackages) {
19631            packages = mSettings.getVolumePackagesLPr(volumeUuid);
19632        }
19633        int preparedCount = 0;
19634        for (PackageSetting ps : packages) {
19635            final String packageName = ps.name;
19636            if (ps.pkg == null) {
19637                Slog.w(TAG, "Odd, missing scanned package " + packageName);
19638                // TODO: might be due to legacy ASEC apps; we should circle back
19639                // and reconcile again once they're scanned
19640                continue;
19641            }
19642
19643            if (ps.getInstalled(userId)) {
19644                prepareAppDataLIF(ps.pkg, userId, flags, restoreconNeeded);
19645
19646                if (maybeMigrateAppDataLIF(ps.pkg, userId)) {
19647                    // We may have just shuffled around app data directories, so
19648                    // prepare them one more time
19649                    prepareAppDataLIF(ps.pkg, userId, flags, restoreconNeeded);
19650                }
19651
19652                preparedCount++;
19653            }
19654        }
19655
19656        if (restoreconNeeded) {
19657            if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
19658                SELinuxMMAC.setRestoreconDone(ceDir);
19659            }
19660            if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) {
19661                SELinuxMMAC.setRestoreconDone(deDir);
19662            }
19663        }
19664
19665        Slog.v(TAG, "reconcileAppsData finished " + preparedCount
19666                + " packages; restoreconNeeded was " + restoreconNeeded);
19667    }
19668
19669    /**
19670     * Prepare app data for the given app just after it was installed or
19671     * upgraded. This method carefully only touches users that it's installed
19672     * for, and it forces a restorecon to handle any seinfo changes.
19673     * <p>
19674     * Verifies that directories exist and that ownership and labeling is
19675     * correct for all installed apps. If there is an ownership mismatch, it
19676     * will try recovering system apps by wiping data; third-party app data is
19677     * left intact.
19678     * <p>
19679     * <em>Note: To avoid a deadlock, do not call this method with {@code mPackages} lock held</em>
19680     */
19681    private void prepareAppDataAfterInstallLIF(PackageParser.Package pkg) {
19682        final PackageSetting ps;
19683        synchronized (mPackages) {
19684            ps = mSettings.mPackages.get(pkg.packageName);
19685            mSettings.writeKernelMappingLPr(ps);
19686        }
19687
19688        final UserManager um = mContext.getSystemService(UserManager.class);
19689        UserManagerInternal umInternal = getUserManagerInternal();
19690        for (UserInfo user : um.getUsers()) {
19691            final int flags;
19692            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
19693                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
19694            } else if (umInternal.isUserRunning(user.id)) {
19695                flags = StorageManager.FLAG_STORAGE_DE;
19696            } else {
19697                continue;
19698            }
19699
19700            if (ps.getInstalled(user.id)) {
19701                // Whenever an app changes, force a restorecon of its data
19702                // TODO: when user data is locked, mark that we're still dirty
19703                prepareAppDataLIF(pkg, user.id, flags, true);
19704            }
19705        }
19706    }
19707
19708    /**
19709     * Prepare app data for the given app.
19710     * <p>
19711     * Verifies that directories exist and that ownership and labeling is
19712     * correct for all installed apps. If there is an ownership mismatch, this
19713     * will try recovering system apps by wiping data; third-party app data is
19714     * left intact.
19715     */
19716    private void prepareAppDataLIF(PackageParser.Package pkg, int userId, int flags,
19717            boolean restoreconNeeded) {
19718        if (pkg == null) {
19719            Slog.wtf(TAG, "Package was null!", new Throwable());
19720            return;
19721        }
19722        prepareAppDataLeafLIF(pkg, userId, flags, restoreconNeeded);
19723        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
19724        for (int i = 0; i < childCount; i++) {
19725            prepareAppDataLeafLIF(pkg.childPackages.get(i), userId, flags, restoreconNeeded);
19726        }
19727    }
19728
19729    private void prepareAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags,
19730            boolean restoreconNeeded) {
19731        if (DEBUG_APP_DATA) {
19732            Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x"
19733                    + Integer.toHexString(flags) + (restoreconNeeded ? " restoreconNeeded" : ""));
19734        }
19735
19736        final String volumeUuid = pkg.volumeUuid;
19737        final String packageName = pkg.packageName;
19738        final ApplicationInfo app = pkg.applicationInfo;
19739        final int appId = UserHandle.getAppId(app.uid);
19740
19741        Preconditions.checkNotNull(app.seinfo);
19742
19743        try {
19744            mInstaller.createAppData(volumeUuid, packageName, userId, flags,
19745                    appId, app.seinfo, app.targetSdkVersion);
19746        } catch (InstallerException e) {
19747            if (app.isSystemApp()) {
19748                logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName
19749                        + ", but trying to recover: " + e);
19750                destroyAppDataLeafLIF(pkg, userId, flags);
19751                try {
19752                    mInstaller.createAppData(volumeUuid, packageName, userId, flags,
19753                            appId, app.seinfo, app.targetSdkVersion);
19754                    logCriticalInfo(Log.DEBUG, "Recovery succeeded!");
19755                } catch (InstallerException e2) {
19756                    logCriticalInfo(Log.DEBUG, "Recovery failed!");
19757                }
19758            } else {
19759                Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e);
19760            }
19761        }
19762
19763        if (restoreconNeeded) {
19764            try {
19765                mInstaller.restoreconAppData(volumeUuid, packageName, userId, flags, appId,
19766                        app.seinfo);
19767            } catch (InstallerException e) {
19768                Slog.e(TAG, "Failed to restorecon for " + packageName + ": " + e);
19769            }
19770        }
19771
19772        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
19773            try {
19774                // CE storage is unlocked right now, so read out the inode and
19775                // remember for use later when it's locked
19776                // TODO: mark this structure as dirty so we persist it!
19777                final long ceDataInode = mInstaller.getAppDataInode(volumeUuid, packageName, userId,
19778                        StorageManager.FLAG_STORAGE_CE);
19779                synchronized (mPackages) {
19780                    final PackageSetting ps = mSettings.mPackages.get(packageName);
19781                    if (ps != null) {
19782                        ps.setCeDataInode(ceDataInode, userId);
19783                    }
19784                }
19785            } catch (InstallerException e) {
19786                Slog.e(TAG, "Failed to find inode for " + packageName + ": " + e);
19787            }
19788        }
19789
19790        prepareAppDataContentsLeafLIF(pkg, userId, flags);
19791    }
19792
19793    private void prepareAppDataContentsLIF(PackageParser.Package pkg, int userId, int flags) {
19794        if (pkg == null) {
19795            Slog.wtf(TAG, "Package was null!", new Throwable());
19796            return;
19797        }
19798        prepareAppDataContentsLeafLIF(pkg, userId, flags);
19799        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
19800        for (int i = 0; i < childCount; i++) {
19801            prepareAppDataContentsLeafLIF(pkg.childPackages.get(i), userId, flags);
19802        }
19803    }
19804
19805    private void prepareAppDataContentsLeafLIF(PackageParser.Package pkg, int userId, int flags) {
19806        final String volumeUuid = pkg.volumeUuid;
19807        final String packageName = pkg.packageName;
19808        final ApplicationInfo app = pkg.applicationInfo;
19809
19810        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
19811            // Create a native library symlink only if we have native libraries
19812            // and if the native libraries are 32 bit libraries. We do not provide
19813            // this symlink for 64 bit libraries.
19814            if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) {
19815                final String nativeLibPath = app.nativeLibraryDir;
19816                try {
19817                    mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName,
19818                            nativeLibPath, userId);
19819                } catch (InstallerException e) {
19820                    Slog.e(TAG, "Failed to link native for " + packageName + ": " + e);
19821                }
19822            }
19823        }
19824    }
19825
19826    /**
19827     * For system apps on non-FBE devices, this method migrates any existing
19828     * CE/DE data to match the {@code defaultToDeviceProtectedStorage} flag
19829     * requested by the app.
19830     */
19831    private boolean maybeMigrateAppDataLIF(PackageParser.Package pkg, int userId) {
19832        if (pkg.isSystemApp() && !StorageManager.isFileEncryptedNativeOrEmulated()
19833                && PackageManager.APPLY_DEFAULT_TO_DEVICE_PROTECTED_STORAGE) {
19834            final int storageTarget = pkg.applicationInfo.isDefaultToDeviceProtectedStorage()
19835                    ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE;
19836            try {
19837                mInstaller.migrateAppData(pkg.volumeUuid, pkg.packageName, userId,
19838                        storageTarget);
19839            } catch (InstallerException e) {
19840                logCriticalInfo(Log.WARN,
19841                        "Failed to migrate " + pkg.packageName + ": " + e.getMessage());
19842            }
19843            return true;
19844        } else {
19845            return false;
19846        }
19847    }
19848
19849    public PackageFreezer freezePackage(String packageName, String killReason) {
19850        return new PackageFreezer(packageName, killReason);
19851    }
19852
19853    public PackageFreezer freezePackageForInstall(String packageName, int installFlags,
19854            String killReason) {
19855        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
19856            return new PackageFreezer();
19857        } else {
19858            return freezePackage(packageName, killReason);
19859        }
19860    }
19861
19862    public PackageFreezer freezePackageForDelete(String packageName, int deleteFlags,
19863            String killReason) {
19864        if ((deleteFlags & PackageManager.DELETE_DONT_KILL_APP) != 0) {
19865            return new PackageFreezer();
19866        } else {
19867            return freezePackage(packageName, killReason);
19868        }
19869    }
19870
19871    /**
19872     * Class that freezes and kills the given package upon creation, and
19873     * unfreezes it upon closing. This is typically used when doing surgery on
19874     * app code/data to prevent the app from running while you're working.
19875     */
19876    private class PackageFreezer implements AutoCloseable {
19877        private final String mPackageName;
19878        private final PackageFreezer[] mChildren;
19879
19880        private final boolean mWeFroze;
19881
19882        private final AtomicBoolean mClosed = new AtomicBoolean();
19883        private final CloseGuard mCloseGuard = CloseGuard.get();
19884
19885        /**
19886         * Create and return a stub freezer that doesn't actually do anything,
19887         * typically used when someone requested
19888         * {@link PackageManager#INSTALL_DONT_KILL_APP} or
19889         * {@link PackageManager#DELETE_DONT_KILL_APP}.
19890         */
19891        public PackageFreezer() {
19892            mPackageName = null;
19893            mChildren = null;
19894            mWeFroze = false;
19895            mCloseGuard.open("close");
19896        }
19897
19898        public PackageFreezer(String packageName, String killReason) {
19899            synchronized (mPackages) {
19900                mPackageName = packageName;
19901                mWeFroze = mFrozenPackages.add(mPackageName);
19902
19903                final PackageSetting ps = mSettings.mPackages.get(mPackageName);
19904                if (ps != null) {
19905                    killApplication(ps.name, ps.appId, killReason);
19906                }
19907
19908                final PackageParser.Package p = mPackages.get(packageName);
19909                if (p != null && p.childPackages != null) {
19910                    final int N = p.childPackages.size();
19911                    mChildren = new PackageFreezer[N];
19912                    for (int i = 0; i < N; i++) {
19913                        mChildren[i] = new PackageFreezer(p.childPackages.get(i).packageName,
19914                                killReason);
19915                    }
19916                } else {
19917                    mChildren = null;
19918                }
19919            }
19920            mCloseGuard.open("close");
19921        }
19922
19923        @Override
19924        protected void finalize() throws Throwable {
19925            try {
19926                mCloseGuard.warnIfOpen();
19927                close();
19928            } finally {
19929                super.finalize();
19930            }
19931        }
19932
19933        @Override
19934        public void close() {
19935            mCloseGuard.close();
19936            if (mClosed.compareAndSet(false, true)) {
19937                synchronized (mPackages) {
19938                    if (mWeFroze) {
19939                        mFrozenPackages.remove(mPackageName);
19940                    }
19941
19942                    if (mChildren != null) {
19943                        for (PackageFreezer freezer : mChildren) {
19944                            freezer.close();
19945                        }
19946                    }
19947                }
19948            }
19949        }
19950    }
19951
19952    /**
19953     * Verify that given package is currently frozen.
19954     */
19955    private void checkPackageFrozen(String packageName) {
19956        synchronized (mPackages) {
19957            if (!mFrozenPackages.contains(packageName)) {
19958                Slog.wtf(TAG, "Expected " + packageName + " to be frozen!", new Throwable());
19959            }
19960        }
19961    }
19962
19963    @Override
19964    public int movePackage(final String packageName, final String volumeUuid) {
19965        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
19966
19967        final UserHandle user = new UserHandle(UserHandle.getCallingUserId());
19968        final int moveId = mNextMoveId.getAndIncrement();
19969        mHandler.post(new Runnable() {
19970            @Override
19971            public void run() {
19972                try {
19973                    movePackageInternal(packageName, volumeUuid, moveId, user);
19974                } catch (PackageManagerException e) {
19975                    Slog.w(TAG, "Failed to move " + packageName, e);
19976                    mMoveCallbacks.notifyStatusChanged(moveId,
19977                            PackageManager.MOVE_FAILED_INTERNAL_ERROR);
19978                }
19979            }
19980        });
19981        return moveId;
19982    }
19983
19984    private void movePackageInternal(final String packageName, final String volumeUuid,
19985            final int moveId, UserHandle user) throws PackageManagerException {
19986        final StorageManager storage = mContext.getSystemService(StorageManager.class);
19987        final PackageManager pm = mContext.getPackageManager();
19988
19989        final boolean currentAsec;
19990        final String currentVolumeUuid;
19991        final File codeFile;
19992        final String installerPackageName;
19993        final String packageAbiOverride;
19994        final int appId;
19995        final String seinfo;
19996        final String label;
19997        final int targetSdkVersion;
19998        final PackageFreezer freezer;
19999        final int[] installedUserIds;
20000
20001        // reader
20002        synchronized (mPackages) {
20003            final PackageParser.Package pkg = mPackages.get(packageName);
20004            final PackageSetting ps = mSettings.mPackages.get(packageName);
20005            if (pkg == null || ps == null) {
20006                throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package");
20007            }
20008
20009            if (pkg.applicationInfo.isSystemApp()) {
20010                throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE,
20011                        "Cannot move system application");
20012            }
20013
20014            if (pkg.applicationInfo.isExternalAsec()) {
20015                currentAsec = true;
20016                currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL;
20017            } else if (pkg.applicationInfo.isForwardLocked()) {
20018                currentAsec = true;
20019                currentVolumeUuid = "forward_locked";
20020            } else {
20021                currentAsec = false;
20022                currentVolumeUuid = ps.volumeUuid;
20023
20024                final File probe = new File(pkg.codePath);
20025                final File probeOat = new File(probe, "oat");
20026                if (!probe.isDirectory() || !probeOat.isDirectory()) {
20027                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
20028                            "Move only supported for modern cluster style installs");
20029                }
20030            }
20031
20032            if (Objects.equals(currentVolumeUuid, volumeUuid)) {
20033                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
20034                        "Package already moved to " + volumeUuid);
20035            }
20036            if (pkg.applicationInfo.isInternal() && isPackageDeviceAdminOnAnyUser(packageName)) {
20037                throw new PackageManagerException(MOVE_FAILED_DEVICE_ADMIN,
20038                        "Device admin cannot be moved");
20039            }
20040
20041            if (mFrozenPackages.contains(packageName)) {
20042                throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING,
20043                        "Failed to move already frozen package");
20044            }
20045
20046            codeFile = new File(pkg.codePath);
20047            installerPackageName = ps.installerPackageName;
20048            packageAbiOverride = ps.cpuAbiOverrideString;
20049            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
20050            seinfo = pkg.applicationInfo.seinfo;
20051            label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo));
20052            targetSdkVersion = pkg.applicationInfo.targetSdkVersion;
20053            freezer = new PackageFreezer(packageName, "movePackageInternal");
20054            installedUserIds = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
20055        }
20056
20057        final Bundle extras = new Bundle();
20058        extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName);
20059        extras.putString(Intent.EXTRA_TITLE, label);
20060        mMoveCallbacks.notifyCreated(moveId, extras);
20061
20062        int installFlags;
20063        final boolean moveCompleteApp;
20064        final File measurePath;
20065
20066        if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) {
20067            installFlags = INSTALL_INTERNAL;
20068            moveCompleteApp = !currentAsec;
20069            measurePath = Environment.getDataAppDirectory(volumeUuid);
20070        } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) {
20071            installFlags = INSTALL_EXTERNAL;
20072            moveCompleteApp = false;
20073            measurePath = storage.getPrimaryPhysicalVolume().getPath();
20074        } else {
20075            final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid);
20076            if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE
20077                    || !volume.isMountedWritable()) {
20078                freezer.close();
20079                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
20080                        "Move location not mounted private volume");
20081            }
20082
20083            Preconditions.checkState(!currentAsec);
20084
20085            installFlags = INSTALL_INTERNAL;
20086            moveCompleteApp = true;
20087            measurePath = Environment.getDataAppDirectory(volumeUuid);
20088        }
20089
20090        final PackageStats stats = new PackageStats(null, -1);
20091        synchronized (mInstaller) {
20092            for (int userId : installedUserIds) {
20093                if (!getPackageSizeInfoLI(packageName, userId, stats)) {
20094                    freezer.close();
20095                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
20096                            "Failed to measure package size");
20097                }
20098            }
20099        }
20100
20101        if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size "
20102                + stats.dataSize);
20103
20104        final long startFreeBytes = measurePath.getFreeSpace();
20105        final long sizeBytes;
20106        if (moveCompleteApp) {
20107            sizeBytes = stats.codeSize + stats.dataSize;
20108        } else {
20109            sizeBytes = stats.codeSize;
20110        }
20111
20112        if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) {
20113            freezer.close();
20114            throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
20115                    "Not enough free space to move");
20116        }
20117
20118        mMoveCallbacks.notifyStatusChanged(moveId, 10);
20119
20120        final CountDownLatch installedLatch = new CountDownLatch(1);
20121        final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
20122            @Override
20123            public void onUserActionRequired(Intent intent) throws RemoteException {
20124                throw new IllegalStateException();
20125            }
20126
20127            @Override
20128            public void onPackageInstalled(String basePackageName, int returnCode, String msg,
20129                    Bundle extras) throws RemoteException {
20130                if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: "
20131                        + PackageManager.installStatusToString(returnCode, msg));
20132
20133                installedLatch.countDown();
20134                freezer.close();
20135
20136                final int status = PackageManager.installStatusToPublicStatus(returnCode);
20137                switch (status) {
20138                    case PackageInstaller.STATUS_SUCCESS:
20139                        mMoveCallbacks.notifyStatusChanged(moveId,
20140                                PackageManager.MOVE_SUCCEEDED);
20141                        break;
20142                    case PackageInstaller.STATUS_FAILURE_STORAGE:
20143                        mMoveCallbacks.notifyStatusChanged(moveId,
20144                                PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
20145                        break;
20146                    default:
20147                        mMoveCallbacks.notifyStatusChanged(moveId,
20148                                PackageManager.MOVE_FAILED_INTERNAL_ERROR);
20149                        break;
20150                }
20151            }
20152        };
20153
20154        final MoveInfo move;
20155        if (moveCompleteApp) {
20156            // Kick off a thread to report progress estimates
20157            new Thread() {
20158                @Override
20159                public void run() {
20160                    while (true) {
20161                        try {
20162                            if (installedLatch.await(1, TimeUnit.SECONDS)) {
20163                                break;
20164                            }
20165                        } catch (InterruptedException ignored) {
20166                        }
20167
20168                        final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace();
20169                        final int progress = 10 + (int) MathUtils.constrain(
20170                                ((deltaFreeBytes * 80) / sizeBytes), 0, 80);
20171                        mMoveCallbacks.notifyStatusChanged(moveId, progress);
20172                    }
20173                }
20174            }.start();
20175
20176            final String dataAppName = codeFile.getName();
20177            move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName,
20178                    dataAppName, appId, seinfo, targetSdkVersion);
20179        } else {
20180            move = null;
20181        }
20182
20183        installFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
20184
20185        final Message msg = mHandler.obtainMessage(INIT_COPY);
20186        final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
20187        final InstallParams params = new InstallParams(origin, move, installObserver, installFlags,
20188                installerPackageName, volumeUuid, null /*verificationInfo*/, user,
20189                packageAbiOverride, null /*grantedPermissions*/, null /*certificates*/);
20190        params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params));
20191        msg.obj = params;
20192
20193        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage",
20194                System.identityHashCode(msg.obj));
20195        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
20196                System.identityHashCode(msg.obj));
20197
20198        mHandler.sendMessage(msg);
20199    }
20200
20201    @Override
20202    public int movePrimaryStorage(String volumeUuid) throws RemoteException {
20203        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
20204
20205        final int realMoveId = mNextMoveId.getAndIncrement();
20206        final Bundle extras = new Bundle();
20207        extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid);
20208        mMoveCallbacks.notifyCreated(realMoveId, extras);
20209
20210        final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() {
20211            @Override
20212            public void onCreated(int moveId, Bundle extras) {
20213                // Ignored
20214            }
20215
20216            @Override
20217            public void onStatusChanged(int moveId, int status, long estMillis) {
20218                mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis);
20219            }
20220        };
20221
20222        final StorageManager storage = mContext.getSystemService(StorageManager.class);
20223        storage.setPrimaryStorageUuid(volumeUuid, callback);
20224        return realMoveId;
20225    }
20226
20227    @Override
20228    public int getMoveStatus(int moveId) {
20229        mContext.enforceCallingOrSelfPermission(
20230                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
20231        return mMoveCallbacks.mLastStatus.get(moveId);
20232    }
20233
20234    @Override
20235    public void registerMoveCallback(IPackageMoveObserver callback) {
20236        mContext.enforceCallingOrSelfPermission(
20237                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
20238        mMoveCallbacks.register(callback);
20239    }
20240
20241    @Override
20242    public void unregisterMoveCallback(IPackageMoveObserver callback) {
20243        mContext.enforceCallingOrSelfPermission(
20244                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
20245        mMoveCallbacks.unregister(callback);
20246    }
20247
20248    @Override
20249    public boolean setInstallLocation(int loc) {
20250        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
20251                null);
20252        if (getInstallLocation() == loc) {
20253            return true;
20254        }
20255        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
20256                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
20257            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
20258                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
20259            return true;
20260        }
20261        return false;
20262   }
20263
20264    @Override
20265    public int getInstallLocation() {
20266        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
20267                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
20268                PackageHelper.APP_INSTALL_AUTO);
20269    }
20270
20271    /** Called by UserManagerService */
20272    void cleanUpUser(UserManagerService userManager, int userHandle) {
20273        synchronized (mPackages) {
20274            mDirtyUsers.remove(userHandle);
20275            mUserNeedsBadging.delete(userHandle);
20276            mSettings.removeUserLPw(userHandle);
20277            mPendingBroadcasts.remove(userHandle);
20278            mEphemeralApplicationRegistry.onUserRemovedLPw(userHandle);
20279            removeUnusedPackagesLPw(userManager, userHandle);
20280        }
20281    }
20282
20283    /**
20284     * We're removing userHandle and would like to remove any downloaded packages
20285     * that are no longer in use by any other user.
20286     * @param userHandle the user being removed
20287     */
20288    private void removeUnusedPackagesLPw(UserManagerService userManager, final int userHandle) {
20289        final boolean DEBUG_CLEAN_APKS = false;
20290        int [] users = userManager.getUserIds();
20291        Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
20292        while (psit.hasNext()) {
20293            PackageSetting ps = psit.next();
20294            if (ps.pkg == null) {
20295                continue;
20296            }
20297            final String packageName = ps.pkg.packageName;
20298            // Skip over if system app
20299            if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
20300                continue;
20301            }
20302            if (DEBUG_CLEAN_APKS) {
20303                Slog.i(TAG, "Checking package " + packageName);
20304            }
20305            boolean keep = shouldKeepUninstalledPackageLPr(packageName);
20306            if (keep) {
20307                if (DEBUG_CLEAN_APKS) {
20308                    Slog.i(TAG, "  Keeping package " + packageName + " - requested by DO");
20309                }
20310            } else {
20311                for (int i = 0; i < users.length; i++) {
20312                    if (users[i] != userHandle && ps.getInstalled(users[i])) {
20313                        keep = true;
20314                        if (DEBUG_CLEAN_APKS) {
20315                            Slog.i(TAG, "  Keeping package " + packageName + " for user "
20316                                    + users[i]);
20317                        }
20318                        break;
20319                    }
20320                }
20321            }
20322            if (!keep) {
20323                if (DEBUG_CLEAN_APKS) {
20324                    Slog.i(TAG, "  Removing package " + packageName);
20325                }
20326                mHandler.post(new Runnable() {
20327                    public void run() {
20328                        deletePackageX(packageName, userHandle, 0);
20329                    } //end run
20330                });
20331            }
20332        }
20333    }
20334
20335    /** Called by UserManagerService */
20336    void createNewUser(int userId) {
20337        synchronized (mInstallLock) {
20338            mSettings.createNewUserLI(this, mInstaller, userId);
20339        }
20340        synchronized (mPackages) {
20341            scheduleWritePackageRestrictionsLocked(userId);
20342            scheduleWritePackageListLocked(userId);
20343            applyFactoryDefaultBrowserLPw(userId);
20344            primeDomainVerificationsLPw(userId);
20345        }
20346    }
20347
20348    void onBeforeUserStartUninitialized(final int userId) {
20349        synchronized (mPackages) {
20350            if (mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) {
20351                return;
20352            }
20353        }
20354        mDefaultPermissionPolicy.grantDefaultPermissions(userId);
20355        // If permission review for legacy apps is required, we represent
20356        // dagerous permissions for such apps as always granted runtime
20357        // permissions to keep per user flag state whether review is needed.
20358        // Hence, if a new user is added we have to propagate dangerous
20359        // permission grants for these legacy apps.
20360        if (Build.PERMISSIONS_REVIEW_REQUIRED) {
20361            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
20362                    | UPDATE_PERMISSIONS_REPLACE_ALL);
20363        }
20364    }
20365
20366    @Override
20367    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
20368        mContext.enforceCallingOrSelfPermission(
20369                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
20370                "Only package verification agents can read the verifier device identity");
20371
20372        synchronized (mPackages) {
20373            return mSettings.getVerifierDeviceIdentityLPw();
20374        }
20375    }
20376
20377    @Override
20378    public void setPermissionEnforced(String permission, boolean enforced) {
20379        // TODO: Now that we no longer change GID for storage, this should to away.
20380        mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
20381                "setPermissionEnforced");
20382        if (READ_EXTERNAL_STORAGE.equals(permission)) {
20383            synchronized (mPackages) {
20384                if (mSettings.mReadExternalStorageEnforced == null
20385                        || mSettings.mReadExternalStorageEnforced != enforced) {
20386                    mSettings.mReadExternalStorageEnforced = enforced;
20387                    mSettings.writeLPr();
20388                }
20389            }
20390            // kill any non-foreground processes so we restart them and
20391            // grant/revoke the GID.
20392            final IActivityManager am = ActivityManagerNative.getDefault();
20393            if (am != null) {
20394                final long token = Binder.clearCallingIdentity();
20395                try {
20396                    am.killProcessesBelowForeground("setPermissionEnforcement");
20397                } catch (RemoteException e) {
20398                } finally {
20399                    Binder.restoreCallingIdentity(token);
20400                }
20401            }
20402        } else {
20403            throw new IllegalArgumentException("No selective enforcement for " + permission);
20404        }
20405    }
20406
20407    @Override
20408    @Deprecated
20409    public boolean isPermissionEnforced(String permission) {
20410        return true;
20411    }
20412
20413    @Override
20414    public boolean isStorageLow() {
20415        final long token = Binder.clearCallingIdentity();
20416        try {
20417            final DeviceStorageMonitorInternal
20418                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
20419            if (dsm != null) {
20420                return dsm.isMemoryLow();
20421            } else {
20422                return false;
20423            }
20424        } finally {
20425            Binder.restoreCallingIdentity(token);
20426        }
20427    }
20428
20429    @Override
20430    public IPackageInstaller getPackageInstaller() {
20431        return mInstallerService;
20432    }
20433
20434    private boolean userNeedsBadging(int userId) {
20435        int index = mUserNeedsBadging.indexOfKey(userId);
20436        if (index < 0) {
20437            final UserInfo userInfo;
20438            final long token = Binder.clearCallingIdentity();
20439            try {
20440                userInfo = sUserManager.getUserInfo(userId);
20441            } finally {
20442                Binder.restoreCallingIdentity(token);
20443            }
20444            final boolean b;
20445            if (userInfo != null && userInfo.isManagedProfile()) {
20446                b = true;
20447            } else {
20448                b = false;
20449            }
20450            mUserNeedsBadging.put(userId, b);
20451            return b;
20452        }
20453        return mUserNeedsBadging.valueAt(index);
20454    }
20455
20456    @Override
20457    public KeySet getKeySetByAlias(String packageName, String alias) {
20458        if (packageName == null || alias == null) {
20459            return null;
20460        }
20461        synchronized(mPackages) {
20462            final PackageParser.Package pkg = mPackages.get(packageName);
20463            if (pkg == null) {
20464                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
20465                throw new IllegalArgumentException("Unknown package: " + packageName);
20466            }
20467            KeySetManagerService ksms = mSettings.mKeySetManagerService;
20468            return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
20469        }
20470    }
20471
20472    @Override
20473    public KeySet getSigningKeySet(String packageName) {
20474        if (packageName == null) {
20475            return null;
20476        }
20477        synchronized(mPackages) {
20478            final PackageParser.Package pkg = mPackages.get(packageName);
20479            if (pkg == null) {
20480                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
20481                throw new IllegalArgumentException("Unknown package: " + packageName);
20482            }
20483            if (pkg.applicationInfo.uid != Binder.getCallingUid()
20484                    && Process.SYSTEM_UID != Binder.getCallingUid()) {
20485                throw new SecurityException("May not access signing KeySet of other apps.");
20486            }
20487            KeySetManagerService ksms = mSettings.mKeySetManagerService;
20488            return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
20489        }
20490    }
20491
20492    @Override
20493    public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
20494        if (packageName == null || ks == null) {
20495            return false;
20496        }
20497        synchronized(mPackages) {
20498            final PackageParser.Package pkg = mPackages.get(packageName);
20499            if (pkg == null) {
20500                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
20501                throw new IllegalArgumentException("Unknown package: " + packageName);
20502            }
20503            IBinder ksh = ks.getToken();
20504            if (ksh instanceof KeySetHandle) {
20505                KeySetManagerService ksms = mSettings.mKeySetManagerService;
20506                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
20507            }
20508            return false;
20509        }
20510    }
20511
20512    @Override
20513    public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
20514        if (packageName == null || ks == null) {
20515            return false;
20516        }
20517        synchronized(mPackages) {
20518            final PackageParser.Package pkg = mPackages.get(packageName);
20519            if (pkg == null) {
20520                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
20521                throw new IllegalArgumentException("Unknown package: " + packageName);
20522            }
20523            IBinder ksh = ks.getToken();
20524            if (ksh instanceof KeySetHandle) {
20525                KeySetManagerService ksms = mSettings.mKeySetManagerService;
20526                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
20527            }
20528            return false;
20529        }
20530    }
20531
20532    private void deletePackageIfUnusedLPr(final String packageName) {
20533        PackageSetting ps = mSettings.mPackages.get(packageName);
20534        if (ps == null) {
20535            return;
20536        }
20537        if (!ps.isAnyInstalled(sUserManager.getUserIds())) {
20538            // TODO Implement atomic delete if package is unused
20539            // It is currently possible that the package will be deleted even if it is installed
20540            // after this method returns.
20541            mHandler.post(new Runnable() {
20542                public void run() {
20543                    deletePackageX(packageName, 0, PackageManager.DELETE_ALL_USERS);
20544                }
20545            });
20546        }
20547    }
20548
20549    /**
20550     * Check and throw if the given before/after packages would be considered a
20551     * downgrade.
20552     */
20553    private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after)
20554            throws PackageManagerException {
20555        if (after.versionCode < before.mVersionCode) {
20556            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
20557                    "Update version code " + after.versionCode + " is older than current "
20558                    + before.mVersionCode);
20559        } else if (after.versionCode == before.mVersionCode) {
20560            if (after.baseRevisionCode < before.baseRevisionCode) {
20561                throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
20562                        "Update base revision code " + after.baseRevisionCode
20563                        + " is older than current " + before.baseRevisionCode);
20564            }
20565
20566            if (!ArrayUtils.isEmpty(after.splitNames)) {
20567                for (int i = 0; i < after.splitNames.length; i++) {
20568                    final String splitName = after.splitNames[i];
20569                    final int j = ArrayUtils.indexOf(before.splitNames, splitName);
20570                    if (j != -1) {
20571                        if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) {
20572                            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
20573                                    "Update split " + splitName + " revision code "
20574                                    + after.splitRevisionCodes[i] + " is older than current "
20575                                    + before.splitRevisionCodes[j]);
20576                        }
20577                    }
20578                }
20579            }
20580        }
20581    }
20582
20583    private static class MoveCallbacks extends Handler {
20584        private static final int MSG_CREATED = 1;
20585        private static final int MSG_STATUS_CHANGED = 2;
20586
20587        private final RemoteCallbackList<IPackageMoveObserver>
20588                mCallbacks = new RemoteCallbackList<>();
20589
20590        private final SparseIntArray mLastStatus = new SparseIntArray();
20591
20592        public MoveCallbacks(Looper looper) {
20593            super(looper);
20594        }
20595
20596        public void register(IPackageMoveObserver callback) {
20597            mCallbacks.register(callback);
20598        }
20599
20600        public void unregister(IPackageMoveObserver callback) {
20601            mCallbacks.unregister(callback);
20602        }
20603
20604        @Override
20605        public void handleMessage(Message msg) {
20606            final SomeArgs args = (SomeArgs) msg.obj;
20607            final int n = mCallbacks.beginBroadcast();
20608            for (int i = 0; i < n; i++) {
20609                final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i);
20610                try {
20611                    invokeCallback(callback, msg.what, args);
20612                } catch (RemoteException ignored) {
20613                }
20614            }
20615            mCallbacks.finishBroadcast();
20616            args.recycle();
20617        }
20618
20619        private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args)
20620                throws RemoteException {
20621            switch (what) {
20622                case MSG_CREATED: {
20623                    callback.onCreated(args.argi1, (Bundle) args.arg2);
20624                    break;
20625                }
20626                case MSG_STATUS_CHANGED: {
20627                    callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3);
20628                    break;
20629                }
20630            }
20631        }
20632
20633        private void notifyCreated(int moveId, Bundle extras) {
20634            Slog.v(TAG, "Move " + moveId + " created " + extras.toString());
20635
20636            final SomeArgs args = SomeArgs.obtain();
20637            args.argi1 = moveId;
20638            args.arg2 = extras;
20639            obtainMessage(MSG_CREATED, args).sendToTarget();
20640        }
20641
20642        private void notifyStatusChanged(int moveId, int status) {
20643            notifyStatusChanged(moveId, status, -1);
20644        }
20645
20646        private void notifyStatusChanged(int moveId, int status, long estMillis) {
20647            Slog.v(TAG, "Move " + moveId + " status " + status);
20648
20649            final SomeArgs args = SomeArgs.obtain();
20650            args.argi1 = moveId;
20651            args.argi2 = status;
20652            args.arg3 = estMillis;
20653            obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget();
20654
20655            synchronized (mLastStatus) {
20656                mLastStatus.put(moveId, status);
20657            }
20658        }
20659    }
20660
20661    private final static class OnPermissionChangeListeners extends Handler {
20662        private static final int MSG_ON_PERMISSIONS_CHANGED = 1;
20663
20664        private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners =
20665                new RemoteCallbackList<>();
20666
20667        public OnPermissionChangeListeners(Looper looper) {
20668            super(looper);
20669        }
20670
20671        @Override
20672        public void handleMessage(Message msg) {
20673            switch (msg.what) {
20674                case MSG_ON_PERMISSIONS_CHANGED: {
20675                    final int uid = msg.arg1;
20676                    handleOnPermissionsChanged(uid);
20677                } break;
20678            }
20679        }
20680
20681        public void addListenerLocked(IOnPermissionsChangeListener listener) {
20682            mPermissionListeners.register(listener);
20683
20684        }
20685
20686        public void removeListenerLocked(IOnPermissionsChangeListener listener) {
20687            mPermissionListeners.unregister(listener);
20688        }
20689
20690        public void onPermissionsChanged(int uid) {
20691            if (mPermissionListeners.getRegisteredCallbackCount() > 0) {
20692                obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget();
20693            }
20694        }
20695
20696        private void handleOnPermissionsChanged(int uid) {
20697            final int count = mPermissionListeners.beginBroadcast();
20698            try {
20699                for (int i = 0; i < count; i++) {
20700                    IOnPermissionsChangeListener callback = mPermissionListeners
20701                            .getBroadcastItem(i);
20702                    try {
20703                        callback.onPermissionsChanged(uid);
20704                    } catch (RemoteException e) {
20705                        Log.e(TAG, "Permission listener is dead", e);
20706                    }
20707                }
20708            } finally {
20709                mPermissionListeners.finishBroadcast();
20710            }
20711        }
20712    }
20713
20714    private class PackageManagerInternalImpl extends PackageManagerInternal {
20715        @Override
20716        public void setLocationPackagesProvider(PackagesProvider provider) {
20717            synchronized (mPackages) {
20718                mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider);
20719            }
20720        }
20721
20722        @Override
20723        public void setVoiceInteractionPackagesProvider(PackagesProvider provider) {
20724            synchronized (mPackages) {
20725                mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider);
20726            }
20727        }
20728
20729        @Override
20730        public void setSmsAppPackagesProvider(PackagesProvider provider) {
20731            synchronized (mPackages) {
20732                mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider);
20733            }
20734        }
20735
20736        @Override
20737        public void setDialerAppPackagesProvider(PackagesProvider provider) {
20738            synchronized (mPackages) {
20739                mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider);
20740            }
20741        }
20742
20743        @Override
20744        public void setSimCallManagerPackagesProvider(PackagesProvider provider) {
20745            synchronized (mPackages) {
20746                mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider);
20747            }
20748        }
20749
20750        @Override
20751        public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) {
20752            synchronized (mPackages) {
20753                mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider);
20754            }
20755        }
20756
20757        @Override
20758        public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) {
20759            synchronized (mPackages) {
20760                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr(
20761                        packageName, userId);
20762            }
20763        }
20764
20765        @Override
20766        public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) {
20767            synchronized (mPackages) {
20768                mSettings.setDefaultDialerPackageNameLPw(packageName, userId);
20769                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr(
20770                        packageName, userId);
20771            }
20772        }
20773
20774        @Override
20775        public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) {
20776            synchronized (mPackages) {
20777                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr(
20778                        packageName, userId);
20779            }
20780        }
20781
20782        @Override
20783        public void setKeepUninstalledPackages(final List<String> packageList) {
20784            Preconditions.checkNotNull(packageList);
20785            List<String> removedFromList = null;
20786            synchronized (mPackages) {
20787                if (mKeepUninstalledPackages != null) {
20788                    final int packagesCount = mKeepUninstalledPackages.size();
20789                    for (int i = 0; i < packagesCount; i++) {
20790                        String oldPackage = mKeepUninstalledPackages.get(i);
20791                        if (packageList != null && packageList.contains(oldPackage)) {
20792                            continue;
20793                        }
20794                        if (removedFromList == null) {
20795                            removedFromList = new ArrayList<>();
20796                        }
20797                        removedFromList.add(oldPackage);
20798                    }
20799                }
20800                mKeepUninstalledPackages = new ArrayList<>(packageList);
20801                if (removedFromList != null) {
20802                    final int removedCount = removedFromList.size();
20803                    for (int i = 0; i < removedCount; i++) {
20804                        deletePackageIfUnusedLPr(removedFromList.get(i));
20805                    }
20806                }
20807            }
20808        }
20809
20810        @Override
20811        public boolean isPermissionsReviewRequired(String packageName, int userId) {
20812            synchronized (mPackages) {
20813                // If we do not support permission review, done.
20814                if (!Build.PERMISSIONS_REVIEW_REQUIRED) {
20815                    return false;
20816                }
20817
20818                PackageSetting packageSetting = mSettings.mPackages.get(packageName);
20819                if (packageSetting == null) {
20820                    return false;
20821                }
20822
20823                // Permission review applies only to apps not supporting the new permission model.
20824                if (packageSetting.pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.M) {
20825                    return false;
20826                }
20827
20828                // Legacy apps have the permission and get user consent on launch.
20829                PermissionsState permissionsState = packageSetting.getPermissionsState();
20830                return permissionsState.isPermissionReviewRequired(userId);
20831            }
20832        }
20833
20834        @Override
20835        public ApplicationInfo getApplicationInfo(String packageName, int userId) {
20836            return PackageManagerService.this.getApplicationInfo(packageName, 0 /*flags*/, userId);
20837        }
20838
20839        @Override
20840        public ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
20841                int userId) {
20842            return PackageManagerService.this.getHomeActivitiesAsUser(allHomeCandidates, userId);
20843        }
20844
20845        @Override
20846        public void setDeviceAndProfileOwnerPackages(
20847                int deviceOwnerUserId, String deviceOwnerPackage,
20848                SparseArray<String> profileOwnerPackages) {
20849            mProtectedPackages.setDeviceAndProfileOwnerPackages(
20850                    deviceOwnerUserId, deviceOwnerPackage, profileOwnerPackages);
20851        }
20852
20853        @Override
20854        public boolean canPackageBeWiped(int userId, String packageName) {
20855            return mProtectedPackages.canPackageBeWiped(userId,
20856                    packageName);
20857        }
20858    }
20859
20860    @Override
20861    public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) {
20862        enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps");
20863        synchronized (mPackages) {
20864            final long identity = Binder.clearCallingIdentity();
20865            try {
20866                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr(
20867                        packageNames, userId);
20868            } finally {
20869                Binder.restoreCallingIdentity(identity);
20870            }
20871        }
20872    }
20873
20874    private static void enforceSystemOrPhoneCaller(String tag) {
20875        int callingUid = Binder.getCallingUid();
20876        if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) {
20877            throw new SecurityException(
20878                    "Cannot call " + tag + " from UID " + callingUid);
20879        }
20880    }
20881
20882    boolean isHistoricalPackageUsageAvailable() {
20883        return mPackageUsage.isHistoricalPackageUsageAvailable();
20884    }
20885
20886    /**
20887     * Return a <b>copy</b> of the collection of packages known to the package manager.
20888     * @return A copy of the values of mPackages.
20889     */
20890    Collection<PackageParser.Package> getPackages() {
20891        synchronized (mPackages) {
20892            return new ArrayList<>(mPackages.values());
20893        }
20894    }
20895
20896    /**
20897     * Logs process start information (including base APK hash) to the security log.
20898     * @hide
20899     */
20900    public void logAppProcessStartIfNeeded(String processName, int uid, String seinfo,
20901            String apkFile, int pid) {
20902        if (!SecurityLog.isLoggingEnabled()) {
20903            return;
20904        }
20905        Bundle data = new Bundle();
20906        data.putLong("startTimestamp", System.currentTimeMillis());
20907        data.putString("processName", processName);
20908        data.putInt("uid", uid);
20909        data.putString("seinfo", seinfo);
20910        data.putString("apkFile", apkFile);
20911        data.putInt("pid", pid);
20912        Message msg = mProcessLoggingHandler.obtainMessage(
20913                ProcessLoggingHandler.LOG_APP_PROCESS_START_MSG);
20914        msg.setData(data);
20915        mProcessLoggingHandler.sendMessage(msg);
20916    }
20917}
20918