PackageManagerService.java revision 2527fa3067ce5ccc707203a06f00eea595d05308
1/*
2 * Copyright (C) 2006 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server.pm;
18
19import static android.Manifest.permission.READ_EXTERNAL_STORAGE;
20import static android.Manifest.permission.WRITE_EXTERNAL_STORAGE;
21import static android.Manifest.permission.WRITE_MEDIA_STORAGE;
22import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DEFAULT;
23import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED;
24import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED;
25import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER;
26import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_ENABLED;
27import static android.content.pm.PackageManager.DELETE_KEEP_DATA;
28import static android.content.pm.PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
29import static android.content.pm.PackageManager.FLAG_PERMISSION_POLICY_FIXED;
30import static android.content.pm.PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
31import static android.content.pm.PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE;
32import static android.content.pm.PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
33import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_FIXED;
34import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_SET;
35import static android.content.pm.PackageManager.INSTALL_EXTERNAL;
36import static android.content.pm.PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
37import static android.content.pm.PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER;
38import static android.content.pm.PackageManager.INSTALL_FAILED_DEXOPT;
39import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
40import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION;
41import static android.content.pm.PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID;
42import static android.content.pm.PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
43import static android.content.pm.PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
44import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_APK;
45import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
46import static android.content.pm.PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY;
47import static android.content.pm.PackageManager.INSTALL_FAILED_PACKAGE_CHANGED;
48import static android.content.pm.PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
49import static android.content.pm.PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE;
50import static android.content.pm.PackageManager.INSTALL_FAILED_TEST_ONLY;
51import static android.content.pm.PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE;
52import static android.content.pm.PackageManager.INSTALL_FAILED_USER_RESTRICTED;
53import static android.content.pm.PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
54import static android.content.pm.PackageManager.INSTALL_FORWARD_LOCK;
55import static android.content.pm.PackageManager.INSTALL_INTERNAL;
56import static android.content.pm.PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
57import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
58import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK;
59import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
60import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER;
61import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
62import static android.content.pm.PackageManager.MATCH_ALL;
63import static android.content.pm.PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
64import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_AWARE;
65import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_UNAWARE;
66import static android.content.pm.PackageManager.MATCH_DISABLED_COMPONENTS;
67import static android.content.pm.PackageManager.MATCH_FACTORY_ONLY;
68import static android.content.pm.PackageManager.MATCH_SYSTEM_ONLY;
69import static android.content.pm.PackageManager.MATCH_UNINSTALLED_PACKAGES;
70import static android.content.pm.PackageManager.MOVE_FAILED_DEVICE_ADMIN;
71import static android.content.pm.PackageManager.MOVE_FAILED_DOESNT_EXIST;
72import static android.content.pm.PackageManager.MOVE_FAILED_INTERNAL_ERROR;
73import static android.content.pm.PackageManager.MOVE_FAILED_OPERATION_PENDING;
74import static android.content.pm.PackageManager.MOVE_FAILED_SYSTEM_PACKAGE;
75import static android.content.pm.PackageManager.PERMISSION_DENIED;
76import static android.content.pm.PackageManager.PERMISSION_GRANTED;
77import static android.content.pm.PackageParser.PARSE_IS_PRIVILEGED;
78import static android.content.pm.PackageParser.isApkFile;
79import static android.os.Trace.TRACE_TAG_PACKAGE_MANAGER;
80import static android.system.OsConstants.O_CREAT;
81import static android.system.OsConstants.O_RDWR;
82
83import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE;
84import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_PARENT;
85import static com.android.internal.content.NativeLibraryHelper.LIB64_DIR_NAME;
86import static com.android.internal.content.NativeLibraryHelper.LIB_DIR_NAME;
87import static com.android.internal.util.ArrayUtils.appendInt;
88import static com.android.server.pm.Installer.DEXOPT_PUBLIC;
89import static com.android.server.pm.InstructionSets.getAppDexInstructionSets;
90import static com.android.server.pm.InstructionSets.getDexCodeInstructionSet;
91import static com.android.server.pm.InstructionSets.getDexCodeInstructionSets;
92import static com.android.server.pm.InstructionSets.getPreferredInstructionSet;
93import static com.android.server.pm.InstructionSets.getPrimaryInstructionSet;
94import static com.android.server.pm.PackageManagerServiceCompilerMapping.getCompilerFilterForReason;
95import static com.android.server.pm.PackageManagerServiceCompilerMapping.getFullCompilerFilter;
96import static com.android.server.pm.PackageManagerServiceCompilerMapping.getNonProfileGuidedCompilerFilter;
97import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_FAILURE;
98import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS;
99import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED;
100
101import android.Manifest;
102import android.annotation.NonNull;
103import android.annotation.Nullable;
104import android.annotation.UserIdInt;
105import android.app.ActivityManager;
106import android.app.ActivityManagerNative;
107import android.app.IActivityManager;
108import android.app.ResourcesManager;
109import android.app.admin.IDevicePolicyManager;
110import android.app.admin.SecurityLog;
111import android.app.backup.IBackupManager;
112import android.content.BroadcastReceiver;
113import android.content.ComponentName;
114import android.content.Context;
115import android.content.IIntentReceiver;
116import android.content.Intent;
117import android.content.IntentFilter;
118import android.content.IntentSender;
119import android.content.IntentSender.SendIntentException;
120import android.content.ServiceConnection;
121import android.content.pm.ActivityInfo;
122import android.content.pm.ApplicationInfo;
123import android.content.pm.AppsQueryHelper;
124import android.content.pm.ComponentInfo;
125import android.content.pm.EphemeralApplicationInfo;
126import android.content.pm.EphemeralResolveInfo;
127import android.content.pm.EphemeralResolveInfo.EphemeralResolveIntentInfo;
128import android.content.pm.FeatureInfo;
129import android.content.pm.IOnPermissionsChangeListener;
130import android.content.pm.IPackageDataObserver;
131import android.content.pm.IPackageDeleteObserver;
132import android.content.pm.IPackageDeleteObserver2;
133import android.content.pm.IPackageInstallObserver2;
134import android.content.pm.IPackageInstaller;
135import android.content.pm.IPackageManager;
136import android.content.pm.IPackageMoveObserver;
137import android.content.pm.IPackageStatsObserver;
138import android.content.pm.InstrumentationInfo;
139import android.content.pm.IntentFilterVerificationInfo;
140import android.content.pm.KeySet;
141import android.content.pm.PackageCleanItem;
142import android.content.pm.PackageInfo;
143import android.content.pm.PackageInfoLite;
144import android.content.pm.PackageInstaller;
145import android.content.pm.PackageManager;
146import android.content.pm.PackageManager.LegacyPackageDeleteObserver;
147import android.content.pm.PackageManagerInternal;
148import android.content.pm.PackageParser;
149import android.content.pm.PackageParser.ActivityIntentInfo;
150import android.content.pm.PackageParser.PackageLite;
151import android.content.pm.PackageParser.PackageParserException;
152import android.content.pm.PackageStats;
153import android.content.pm.PackageUserState;
154import android.content.pm.ParceledListSlice;
155import android.content.pm.PermissionGroupInfo;
156import android.content.pm.PermissionInfo;
157import android.content.pm.ProviderInfo;
158import android.content.pm.ResolveInfo;
159import android.content.pm.ServiceInfo;
160import android.content.pm.Signature;
161import android.content.pm.UserInfo;
162import android.content.pm.VerifierDeviceIdentity;
163import android.content.pm.VerifierInfo;
164import android.content.res.Resources;
165import android.graphics.Bitmap;
166import android.hardware.display.DisplayManager;
167import android.net.Uri;
168import android.os.Binder;
169import android.os.Build;
170import android.os.Bundle;
171import android.os.Debug;
172import android.os.Environment;
173import android.os.Environment.UserEnvironment;
174import android.os.FileUtils;
175import android.os.Handler;
176import android.os.IBinder;
177import android.os.Looper;
178import android.os.Message;
179import android.os.Parcel;
180import android.os.ParcelFileDescriptor;
181import android.os.Process;
182import android.os.RemoteCallbackList;
183import android.os.RemoteException;
184import android.os.ResultReceiver;
185import android.os.SELinux;
186import android.os.ServiceManager;
187import android.os.SystemClock;
188import android.os.SystemProperties;
189import android.os.Trace;
190import android.os.UserHandle;
191import android.os.UserManager;
192import android.os.UserManagerInternal;
193import android.os.storage.IMountService;
194import android.os.storage.MountServiceInternal;
195import android.os.storage.StorageEventListener;
196import android.os.storage.StorageManager;
197import android.os.storage.VolumeInfo;
198import android.os.storage.VolumeRecord;
199import android.security.KeyStore;
200import android.security.SystemKeyStore;
201import android.system.ErrnoException;
202import android.system.Os;
203import android.text.TextUtils;
204import android.text.format.DateUtils;
205import android.util.ArrayMap;
206import android.util.ArraySet;
207import android.util.DisplayMetrics;
208import android.util.EventLog;
209import android.util.ExceptionUtils;
210import android.util.Log;
211import android.util.LogPrinter;
212import android.util.MathUtils;
213import android.util.PrintStreamPrinter;
214import android.util.Slog;
215import android.util.SparseArray;
216import android.util.SparseBooleanArray;
217import android.util.SparseIntArray;
218import android.util.Xml;
219import android.util.jar.StrictJarFile;
220import android.view.Display;
221
222import com.android.internal.R;
223import com.android.internal.annotations.GuardedBy;
224import com.android.internal.app.IMediaContainerService;
225import com.android.internal.app.ResolverActivity;
226import com.android.internal.content.NativeLibraryHelper;
227import com.android.internal.content.PackageHelper;
228import com.android.internal.logging.MetricsLogger;
229import com.android.internal.os.IParcelFileDescriptorFactory;
230import com.android.internal.os.InstallerConnection.InstallerException;
231import com.android.internal.os.SomeArgs;
232import com.android.internal.os.Zygote;
233import com.android.internal.telephony.CarrierAppUtils;
234import com.android.internal.util.ArrayUtils;
235import com.android.internal.util.FastPrintWriter;
236import com.android.internal.util.FastXmlSerializer;
237import com.android.internal.util.IndentingPrintWriter;
238import com.android.internal.util.Preconditions;
239import com.android.internal.util.XmlUtils;
240import com.android.server.AttributeCache;
241import com.android.server.EventLogTags;
242import com.android.server.FgThread;
243import com.android.server.IntentResolver;
244import com.android.server.LocalServices;
245import com.android.server.ServiceThread;
246import com.android.server.SystemConfig;
247import com.android.server.Watchdog;
248import com.android.server.net.NetworkPolicyManagerInternal;
249import com.android.server.pm.PermissionsState.PermissionState;
250import com.android.server.pm.Settings.DatabaseVersion;
251import com.android.server.pm.Settings.VersionInfo;
252import com.android.server.storage.DeviceStorageMonitorInternal;
253
254import dalvik.system.CloseGuard;
255import dalvik.system.DexFile;
256import dalvik.system.VMRuntime;
257
258import libcore.io.IoUtils;
259import libcore.util.EmptyArray;
260
261import org.xmlpull.v1.XmlPullParser;
262import org.xmlpull.v1.XmlPullParserException;
263import org.xmlpull.v1.XmlSerializer;
264
265import java.io.BufferedOutputStream;
266import java.io.BufferedReader;
267import java.io.ByteArrayInputStream;
268import java.io.ByteArrayOutputStream;
269import java.io.File;
270import java.io.FileDescriptor;
271import java.io.FileInputStream;
272import java.io.FileNotFoundException;
273import java.io.FileOutputStream;
274import java.io.FileReader;
275import java.io.FilenameFilter;
276import java.io.IOException;
277import java.io.PrintWriter;
278import java.nio.charset.StandardCharsets;
279import java.security.DigestInputStream;
280import java.security.MessageDigest;
281import java.security.NoSuchAlgorithmException;
282import java.security.PublicKey;
283import java.security.cert.Certificate;
284import java.security.cert.CertificateEncodingException;
285import java.security.cert.CertificateException;
286import java.text.SimpleDateFormat;
287import java.util.ArrayList;
288import java.util.Arrays;
289import java.util.Collection;
290import java.util.Collections;
291import java.util.Comparator;
292import java.util.Date;
293import java.util.HashSet;
294import java.util.Iterator;
295import java.util.List;
296import java.util.Map;
297import java.util.Objects;
298import java.util.Set;
299import java.util.concurrent.CountDownLatch;
300import java.util.concurrent.TimeUnit;
301import java.util.concurrent.atomic.AtomicBoolean;
302import java.util.concurrent.atomic.AtomicInteger;
303
304/**
305 * Keep track of all those APKs everywhere.
306 * <p>
307 * Internally there are two important locks:
308 * <ul>
309 * <li>{@link #mPackages} is used to guard all in-memory parsed package details
310 * and other related state. It is a fine-grained lock that should only be held
311 * momentarily, as it's one of the most contended locks in the system.
312 * <li>{@link #mInstallLock} is used to guard all {@code installd} access, whose
313 * operations typically involve heavy lifting of application data on disk. Since
314 * {@code installd} is single-threaded, and it's operations can often be slow,
315 * this lock should never be acquired while already holding {@link #mPackages}.
316 * Conversely, it's safe to acquire {@link #mPackages} momentarily while already
317 * holding {@link #mInstallLock}.
318 * </ul>
319 * Many internal methods rely on the caller to hold the appropriate locks, and
320 * this contract is expressed through method name suffixes:
321 * <ul>
322 * <li>fooLI(): the caller must hold {@link #mInstallLock}
323 * <li>fooLIF(): the caller must hold {@link #mInstallLock} and the package
324 * being modified must be frozen
325 * <li>fooLPr(): the caller must hold {@link #mPackages} for reading
326 * <li>fooLPw(): the caller must hold {@link #mPackages} for writing
327 * </ul>
328 * <p>
329 * Because this class is very central to the platform's security; please run all
330 * CTS and unit tests whenever making modifications:
331 *
332 * <pre>
333 * $ runtest -c android.content.pm.PackageManagerTests frameworks-core
334 * $ cts-tradefed run commandAndExit cts -m AppSecurityTests
335 * </pre>
336 */
337public class PackageManagerService extends IPackageManager.Stub {
338    static final String TAG = "PackageManager";
339    static final boolean DEBUG_SETTINGS = false;
340    static final boolean DEBUG_PREFERRED = false;
341    static final boolean DEBUG_UPGRADE = false;
342    static final boolean DEBUG_DOMAIN_VERIFICATION = false;
343    private static final boolean DEBUG_BACKUP = false;
344    private static final boolean DEBUG_INSTALL = false;
345    private static final boolean DEBUG_REMOVE = false;
346    private static final boolean DEBUG_BROADCASTS = false;
347    private static final boolean DEBUG_SHOW_INFO = false;
348    private static final boolean DEBUG_PACKAGE_INFO = false;
349    private static final boolean DEBUG_INTENT_MATCHING = false;
350    private static final boolean DEBUG_PACKAGE_SCANNING = false;
351    private static final boolean DEBUG_VERIFY = false;
352    private static final boolean DEBUG_FILTERS = false;
353
354    // Debug output for dexopting. This is shared between PackageManagerService, OtaDexoptService
355    // and PackageDexOptimizer. All these classes have their own flag to allow switching a single
356    // user, but by default initialize to this.
357    static final boolean DEBUG_DEXOPT = false;
358
359    private static final boolean DEBUG_ABI_SELECTION = false;
360    private static final boolean DEBUG_EPHEMERAL = false;
361    private static final boolean DEBUG_TRIAGED_MISSING = false;
362    private static final boolean DEBUG_APP_DATA = false;
363
364    static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = false;
365
366    private static final boolean DISABLE_EPHEMERAL_APPS = true;
367
368    private static final int RADIO_UID = Process.PHONE_UID;
369    private static final int LOG_UID = Process.LOG_UID;
370    private static final int NFC_UID = Process.NFC_UID;
371    private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID;
372    private static final int SHELL_UID = Process.SHELL_UID;
373
374    // Cap the size of permission trees that 3rd party apps can define
375    private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768;     // characters of text
376
377    // Suffix used during package installation when copying/moving
378    // package apks to install directory.
379    private static final String INSTALL_PACKAGE_SUFFIX = "-";
380
381    static final int SCAN_NO_DEX = 1<<1;
382    static final int SCAN_FORCE_DEX = 1<<2;
383    static final int SCAN_UPDATE_SIGNATURE = 1<<3;
384    static final int SCAN_NEW_INSTALL = 1<<4;
385    static final int SCAN_NO_PATHS = 1<<5;
386    static final int SCAN_UPDATE_TIME = 1<<6;
387    static final int SCAN_DEFER_DEX = 1<<7;
388    static final int SCAN_BOOTING = 1<<8;
389    static final int SCAN_TRUSTED_OVERLAY = 1<<9;
390    static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<10;
391    static final int SCAN_REPLACING = 1<<11;
392    static final int SCAN_REQUIRE_KNOWN = 1<<12;
393    static final int SCAN_MOVE = 1<<13;
394    static final int SCAN_INITIAL = 1<<14;
395    static final int SCAN_CHECK_ONLY = 1<<15;
396    static final int SCAN_DONT_KILL_APP = 1<<17;
397    static final int SCAN_IGNORE_FROZEN = 1<<18;
398
399    static final int REMOVE_CHATTY = 1<<16;
400
401    private static final int[] EMPTY_INT_ARRAY = new int[0];
402
403    /**
404     * Timeout (in milliseconds) after which the watchdog should declare that
405     * our handler thread is wedged.  The usual default for such things is one
406     * minute but we sometimes do very lengthy I/O operations on this thread,
407     * such as installing multi-gigabyte applications, so ours needs to be longer.
408     */
409    private static final long WATCHDOG_TIMEOUT = 1000*60*10;     // ten minutes
410
411    /**
412     * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim
413     * be run on this device.  We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL
414     * settings entry if available, otherwise we use the hardcoded default.  If it's been
415     * more than this long since the last fstrim, we force one during the boot sequence.
416     *
417     * This backstops other fstrim scheduling:  if the device is alive at midnight+idle,
418     * one gets run at the next available charging+idle time.  This final mandatory
419     * no-fstrim check kicks in only of the other scheduling criteria is never met.
420     */
421    private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS;
422
423    /**
424     * Whether verification is enabled by default.
425     */
426    private static final boolean DEFAULT_VERIFY_ENABLE = true;
427
428    /**
429     * The default maximum time to wait for the verification agent to return in
430     * milliseconds.
431     */
432    private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000;
433
434    /**
435     * The default response for package verification timeout.
436     *
437     * This can be either PackageManager.VERIFICATION_ALLOW or
438     * PackageManager.VERIFICATION_REJECT.
439     */
440    private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW;
441
442    static final String PLATFORM_PACKAGE_NAME = "android";
443
444    static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer";
445
446    static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
447            DEFAULT_CONTAINER_PACKAGE,
448            "com.android.defcontainer.DefaultContainerService");
449
450    private static final String KILL_APP_REASON_GIDS_CHANGED =
451            "permission grant or revoke changed gids";
452
453    private static final String KILL_APP_REASON_PERMISSIONS_REVOKED =
454            "permissions revoked";
455
456    private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive";
457
458    private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay";
459
460    /** Permission grant: not grant the permission. */
461    private static final int GRANT_DENIED = 1;
462
463    /** Permission grant: grant the permission as an install permission. */
464    private static final int GRANT_INSTALL = 2;
465
466    /** Permission grant: grant the permission as a runtime one. */
467    private static final int GRANT_RUNTIME = 3;
468
469    /** Permission grant: grant as runtime a permission that was granted as an install time one. */
470    private static final int GRANT_UPGRADE = 4;
471
472    /** Canonical intent used to identify what counts as a "web browser" app */
473    private static final Intent sBrowserIntent;
474    static {
475        sBrowserIntent = new Intent();
476        sBrowserIntent.setAction(Intent.ACTION_VIEW);
477        sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE);
478        sBrowserIntent.setData(Uri.parse("http:"));
479    }
480
481    /**
482     * The set of all protected actions [i.e. those actions for which a high priority
483     * intent filter is disallowed].
484     */
485    private static final Set<String> PROTECTED_ACTIONS = new ArraySet<>();
486    static {
487        PROTECTED_ACTIONS.add(Intent.ACTION_SEND);
488        PROTECTED_ACTIONS.add(Intent.ACTION_SENDTO);
489        PROTECTED_ACTIONS.add(Intent.ACTION_SEND_MULTIPLE);
490        PROTECTED_ACTIONS.add(Intent.ACTION_VIEW);
491    }
492
493    // Compilation reasons.
494    public static final int REASON_FIRST_BOOT = 0;
495    public static final int REASON_BOOT = 1;
496    public static final int REASON_INSTALL = 2;
497    public static final int REASON_BACKGROUND_DEXOPT = 3;
498    public static final int REASON_AB_OTA = 4;
499    public static final int REASON_NON_SYSTEM_LIBRARY = 5;
500    public static final int REASON_SHARED_APK = 6;
501    public static final int REASON_FORCED_DEXOPT = 7;
502    public static final int REASON_CORE_APP = 8;
503
504    public static final int REASON_LAST = REASON_CORE_APP;
505
506    /** Special library name that skips shared libraries check during compilation. */
507    private static final String SKIP_SHARED_LIBRARY_CHECK = "&";
508
509    final ServiceThread mHandlerThread;
510
511    final PackageHandler mHandler;
512
513    private final ProcessLoggingHandler mProcessLoggingHandler;
514
515    /**
516     * Messages for {@link #mHandler} that need to wait for system ready before
517     * being dispatched.
518     */
519    private ArrayList<Message> mPostSystemReadyMessages;
520
521    final int mSdkVersion = Build.VERSION.SDK_INT;
522
523    final Context mContext;
524    final boolean mFactoryTest;
525    final boolean mOnlyCore;
526    final DisplayMetrics mMetrics;
527    final int mDefParseFlags;
528    final String[] mSeparateProcesses;
529    final boolean mIsUpgrade;
530    final boolean mIsPreNUpgrade;
531
532    /** The location for ASEC container files on internal storage. */
533    final String mAsecInternalPath;
534
535    // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages
536    // LOCK HELD.  Can be called with mInstallLock held.
537    @GuardedBy("mInstallLock")
538    final Installer mInstaller;
539
540    /** Directory where installed third-party apps stored */
541    final File mAppInstallDir;
542    final File mEphemeralInstallDir;
543
544    /**
545     * Directory to which applications installed internally have their
546     * 32 bit native libraries copied.
547     */
548    private File mAppLib32InstallDir;
549
550    // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked
551    // apps.
552    final File mDrmAppPrivateInstallDir;
553
554    // ----------------------------------------------------------------
555
556    // Lock for state used when installing and doing other long running
557    // operations.  Methods that must be called with this lock held have
558    // the suffix "LI".
559    final Object mInstallLock = new Object();
560
561    // ----------------------------------------------------------------
562
563    // Keys are String (package name), values are Package.  This also serves
564    // as the lock for the global state.  Methods that must be called with
565    // this lock held have the prefix "LP".
566    @GuardedBy("mPackages")
567    final ArrayMap<String, PackageParser.Package> mPackages =
568            new ArrayMap<String, PackageParser.Package>();
569
570    final ArrayMap<String, Set<String>> mKnownCodebase =
571            new ArrayMap<String, Set<String>>();
572
573    // Tracks available target package names -> overlay package paths.
574    final ArrayMap<String, ArrayMap<String, PackageParser.Package>> mOverlays =
575        new ArrayMap<String, ArrayMap<String, PackageParser.Package>>();
576
577    /**
578     * Tracks new system packages [received in an OTA] that we expect to
579     * find updated user-installed versions. Keys are package name, values
580     * are package location.
581     */
582    final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>();
583    /**
584     * Tracks high priority intent filters for protected actions. During boot, certain
585     * filter actions are protected and should never be allowed to have a high priority
586     * intent filter for them. However, there is one, and only one exception -- the
587     * setup wizard. It must be able to define a high priority intent filter for these
588     * actions to ensure there are no escapes from the wizard. We need to delay processing
589     * of these during boot as we need to look at all of the system packages in order
590     * to know which component is the setup wizard.
591     */
592    private final List<PackageParser.ActivityIntentInfo> mProtectedFilters = new ArrayList<>();
593    /**
594     * Whether or not processing protected filters should be deferred.
595     */
596    private boolean mDeferProtectedFilters = true;
597
598    /**
599     * Tracks existing system packages prior to receiving an OTA. Keys are package name.
600     */
601    final private ArraySet<String> mExistingSystemPackages = new ArraySet<>();
602    /**
603     * Whether or not system app permissions should be promoted from install to runtime.
604     */
605    boolean mPromoteSystemApps;
606
607    @GuardedBy("mPackages")
608    final Settings mSettings;
609
610    /**
611     * Set of package names that are currently "frozen", which means active
612     * surgery is being done on the code/data for that package. The platform
613     * will refuse to launch frozen packages to avoid race conditions.
614     *
615     * @see PackageFreezer
616     */
617    @GuardedBy("mPackages")
618    final ArraySet<String> mFrozenPackages = new ArraySet<>();
619
620    final ProtectedPackages mProtectedPackages = new ProtectedPackages();
621
622    boolean mFirstBoot;
623
624    // System configuration read by SystemConfig.
625    final int[] mGlobalGids;
626    final SparseArray<ArraySet<String>> mSystemPermissions;
627    final ArrayMap<String, FeatureInfo> mAvailableFeatures;
628
629    // If mac_permissions.xml was found for seinfo labeling.
630    boolean mFoundPolicyFile;
631
632    private final EphemeralApplicationRegistry mEphemeralApplicationRegistry;
633
634    public static final class SharedLibraryEntry {
635        public final String path;
636        public final String apk;
637
638        SharedLibraryEntry(String _path, String _apk) {
639            path = _path;
640            apk = _apk;
641        }
642    }
643
644    // Currently known shared libraries.
645    final ArrayMap<String, SharedLibraryEntry> mSharedLibraries =
646            new ArrayMap<String, SharedLibraryEntry>();
647
648    // All available activities, for your resolving pleasure.
649    final ActivityIntentResolver mActivities =
650            new ActivityIntentResolver();
651
652    // All available receivers, for your resolving pleasure.
653    final ActivityIntentResolver mReceivers =
654            new ActivityIntentResolver();
655
656    // All available services, for your resolving pleasure.
657    final ServiceIntentResolver mServices = new ServiceIntentResolver();
658
659    // All available providers, for your resolving pleasure.
660    final ProviderIntentResolver mProviders = new ProviderIntentResolver();
661
662    // Mapping from provider base names (first directory in content URI codePath)
663    // to the provider information.
664    final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority =
665            new ArrayMap<String, PackageParser.Provider>();
666
667    // Mapping from instrumentation class names to info about them.
668    final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
669            new ArrayMap<ComponentName, PackageParser.Instrumentation>();
670
671    // Mapping from permission names to info about them.
672    final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups =
673            new ArrayMap<String, PackageParser.PermissionGroup>();
674
675    // Packages whose data we have transfered into another package, thus
676    // should no longer exist.
677    final ArraySet<String> mTransferedPackages = new ArraySet<String>();
678
679    // Broadcast actions that are only available to the system.
680    final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>();
681
682    /** List of packages waiting for verification. */
683    final SparseArray<PackageVerificationState> mPendingVerification
684            = new SparseArray<PackageVerificationState>();
685
686    /** Set of packages associated with each app op permission. */
687    final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>();
688
689    final PackageInstallerService mInstallerService;
690
691    private final PackageDexOptimizer mPackageDexOptimizer;
692
693    private AtomicInteger mNextMoveId = new AtomicInteger();
694    private final MoveCallbacks mMoveCallbacks;
695
696    private final OnPermissionChangeListeners mOnPermissionChangeListeners;
697
698    // Cache of users who need badging.
699    SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray();
700
701    /** Token for keys in mPendingVerification. */
702    private int mPendingVerificationToken = 0;
703
704    volatile boolean mSystemReady;
705    volatile boolean mSafeMode;
706    volatile boolean mHasSystemUidErrors;
707
708    ApplicationInfo mAndroidApplication;
709    final ActivityInfo mResolveActivity = new ActivityInfo();
710    final ResolveInfo mResolveInfo = new ResolveInfo();
711    ComponentName mResolveComponentName;
712    PackageParser.Package mPlatformPackage;
713    ComponentName mCustomResolverComponentName;
714
715    boolean mResolverReplaced = false;
716
717    private final @Nullable ComponentName mIntentFilterVerifierComponent;
718    private final @Nullable IntentFilterVerifier<ActivityIntentInfo> mIntentFilterVerifier;
719
720    private int mIntentFilterVerificationToken = 0;
721
722    /** Component that knows whether or not an ephemeral application exists */
723    final ComponentName mEphemeralResolverComponent;
724    /** The service connection to the ephemeral resolver */
725    final EphemeralResolverConnection mEphemeralResolverConnection;
726
727    /** Component used to install ephemeral applications */
728    final ComponentName mEphemeralInstallerComponent;
729    final ActivityInfo mEphemeralInstallerActivity = new ActivityInfo();
730    final ResolveInfo mEphemeralInstallerInfo = new ResolveInfo();
731
732    final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates
733            = new SparseArray<IntentFilterVerificationState>();
734
735    final DefaultPermissionGrantPolicy mDefaultPermissionPolicy =
736            new DefaultPermissionGrantPolicy(this);
737
738    // List of packages names to keep cached, even if they are uninstalled for all users
739    private List<String> mKeepUninstalledPackages;
740
741    private UserManagerInternal mUserManagerInternal;
742
743    private static class IFVerificationParams {
744        PackageParser.Package pkg;
745        boolean replacing;
746        int userId;
747        int verifierUid;
748
749        public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing,
750                int _userId, int _verifierUid) {
751            pkg = _pkg;
752            replacing = _replacing;
753            userId = _userId;
754            replacing = _replacing;
755            verifierUid = _verifierUid;
756        }
757    }
758
759    private interface IntentFilterVerifier<T extends IntentFilter> {
760        boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId,
761                                               T filter, String packageName);
762        void startVerifications(int userId);
763        void receiveVerificationResponse(int verificationId);
764    }
765
766    private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> {
767        private Context mContext;
768        private ComponentName mIntentFilterVerifierComponent;
769        private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>();
770
771        public IntentVerifierProxy(Context context, ComponentName verifierComponent) {
772            mContext = context;
773            mIntentFilterVerifierComponent = verifierComponent;
774        }
775
776        private String getDefaultScheme() {
777            return IntentFilter.SCHEME_HTTPS;
778        }
779
780        @Override
781        public void startVerifications(int userId) {
782            // Launch verifications requests
783            int count = mCurrentIntentFilterVerifications.size();
784            for (int n=0; n<count; n++) {
785                int verificationId = mCurrentIntentFilterVerifications.get(n);
786                final IntentFilterVerificationState ivs =
787                        mIntentFilterVerificationStates.get(verificationId);
788
789                String packageName = ivs.getPackageName();
790
791                ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
792                final int filterCount = filters.size();
793                ArraySet<String> domainsSet = new ArraySet<>();
794                for (int m=0; m<filterCount; m++) {
795                    PackageParser.ActivityIntentInfo filter = filters.get(m);
796                    domainsSet.addAll(filter.getHostsList());
797                }
798                ArrayList<String> domainsList = new ArrayList<>(domainsSet);
799                synchronized (mPackages) {
800                    if (mSettings.createIntentFilterVerificationIfNeededLPw(
801                            packageName, domainsList) != null) {
802                        scheduleWriteSettingsLocked();
803                    }
804                }
805                sendVerificationRequest(userId, verificationId, ivs);
806            }
807            mCurrentIntentFilterVerifications.clear();
808        }
809
810        private void sendVerificationRequest(int userId, int verificationId,
811                IntentFilterVerificationState ivs) {
812
813            Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
814            verificationIntent.putExtra(
815                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID,
816                    verificationId);
817            verificationIntent.putExtra(
818                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME,
819                    getDefaultScheme());
820            verificationIntent.putExtra(
821                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS,
822                    ivs.getHostsString());
823            verificationIntent.putExtra(
824                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME,
825                    ivs.getPackageName());
826            verificationIntent.setComponent(mIntentFilterVerifierComponent);
827            verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
828
829            UserHandle user = new UserHandle(userId);
830            mContext.sendBroadcastAsUser(verificationIntent, user);
831            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
832                    "Sending IntentFilter verification broadcast");
833        }
834
835        public void receiveVerificationResponse(int verificationId) {
836            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
837
838            final boolean verified = ivs.isVerified();
839
840            ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
841            final int count = filters.size();
842            if (DEBUG_DOMAIN_VERIFICATION) {
843                Slog.i(TAG, "Received verification response " + verificationId
844                        + " for " + count + " filters, verified=" + verified);
845            }
846            for (int n=0; n<count; n++) {
847                PackageParser.ActivityIntentInfo filter = filters.get(n);
848                filter.setVerified(verified);
849
850                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString()
851                        + " verified with result:" + verified + " and hosts:"
852                        + ivs.getHostsString());
853            }
854
855            mIntentFilterVerificationStates.remove(verificationId);
856
857            final String packageName = ivs.getPackageName();
858            IntentFilterVerificationInfo ivi = null;
859
860            synchronized (mPackages) {
861                ivi = mSettings.getIntentFilterVerificationLPr(packageName);
862            }
863            if (ivi == null) {
864                Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:"
865                        + verificationId + " packageName:" + packageName);
866                return;
867            }
868            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
869                    "Updating IntentFilterVerificationInfo for package " + packageName
870                            +" verificationId:" + verificationId);
871
872            synchronized (mPackages) {
873                if (verified) {
874                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS);
875                } else {
876                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK);
877                }
878                scheduleWriteSettingsLocked();
879
880                final int userId = ivs.getUserId();
881                if (userId != UserHandle.USER_ALL) {
882                    final int userStatus =
883                            mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
884
885                    int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
886                    boolean needUpdate = false;
887
888                    // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have
889                    // already been set by the User thru the Disambiguation dialog
890                    switch (userStatus) {
891                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
892                            if (verified) {
893                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
894                            } else {
895                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
896                            }
897                            needUpdate = true;
898                            break;
899
900                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
901                            if (verified) {
902                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
903                                needUpdate = true;
904                            }
905                            break;
906
907                        default:
908                            // Nothing to do
909                    }
910
911                    if (needUpdate) {
912                        mSettings.updateIntentFilterVerificationStatusLPw(
913                                packageName, updatedStatus, userId);
914                        scheduleWritePackageRestrictionsLocked(userId);
915                    }
916                }
917            }
918        }
919
920        @Override
921        public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId,
922                    ActivityIntentInfo filter, String packageName) {
923            if (!hasValidDomains(filter)) {
924                return false;
925            }
926            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
927            if (ivs == null) {
928                ivs = createDomainVerificationState(verifierUid, userId, verificationId,
929                        packageName);
930            }
931            if (DEBUG_DOMAIN_VERIFICATION) {
932                Slog.d(TAG, "Adding verification filter for " + packageName + ": " + filter);
933            }
934            ivs.addFilter(filter);
935            return true;
936        }
937
938        private IntentFilterVerificationState createDomainVerificationState(int verifierUid,
939                int userId, int verificationId, String packageName) {
940            IntentFilterVerificationState ivs = new IntentFilterVerificationState(
941                    verifierUid, userId, packageName);
942            ivs.setPendingState();
943            synchronized (mPackages) {
944                mIntentFilterVerificationStates.append(verificationId, ivs);
945                mCurrentIntentFilterVerifications.add(verificationId);
946            }
947            return ivs;
948        }
949    }
950
951    private static boolean hasValidDomains(ActivityIntentInfo filter) {
952        return filter.hasCategory(Intent.CATEGORY_BROWSABLE)
953                && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
954                        filter.hasDataScheme(IntentFilter.SCHEME_HTTPS));
955    }
956
957    // Set of pending broadcasts for aggregating enable/disable of components.
958    static class PendingPackageBroadcasts {
959        // for each user id, a map of <package name -> components within that package>
960        final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap;
961
962        public PendingPackageBroadcasts() {
963            mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2);
964        }
965
966        public ArrayList<String> get(int userId, String packageName) {
967            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
968            return packages.get(packageName);
969        }
970
971        public void put(int userId, String packageName, ArrayList<String> components) {
972            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
973            packages.put(packageName, components);
974        }
975
976        public void remove(int userId, String packageName) {
977            ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId);
978            if (packages != null) {
979                packages.remove(packageName);
980            }
981        }
982
983        public void remove(int userId) {
984            mUidMap.remove(userId);
985        }
986
987        public int userIdCount() {
988            return mUidMap.size();
989        }
990
991        public int userIdAt(int n) {
992            return mUidMap.keyAt(n);
993        }
994
995        public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) {
996            return mUidMap.get(userId);
997        }
998
999        public int size() {
1000            // total number of pending broadcast entries across all userIds
1001            int num = 0;
1002            for (int i = 0; i< mUidMap.size(); i++) {
1003                num += mUidMap.valueAt(i).size();
1004            }
1005            return num;
1006        }
1007
1008        public void clear() {
1009            mUidMap.clear();
1010        }
1011
1012        private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) {
1013            ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId);
1014            if (map == null) {
1015                map = new ArrayMap<String, ArrayList<String>>();
1016                mUidMap.put(userId, map);
1017            }
1018            return map;
1019        }
1020    }
1021    final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts();
1022
1023    // Service Connection to remote media container service to copy
1024    // package uri's from external media onto secure containers
1025    // or internal storage.
1026    private IMediaContainerService mContainerService = null;
1027
1028    static final int SEND_PENDING_BROADCAST = 1;
1029    static final int MCS_BOUND = 3;
1030    static final int END_COPY = 4;
1031    static final int INIT_COPY = 5;
1032    static final int MCS_UNBIND = 6;
1033    static final int START_CLEANING_PACKAGE = 7;
1034    static final int FIND_INSTALL_LOC = 8;
1035    static final int POST_INSTALL = 9;
1036    static final int MCS_RECONNECT = 10;
1037    static final int MCS_GIVE_UP = 11;
1038    static final int UPDATED_MEDIA_STATUS = 12;
1039    static final int WRITE_SETTINGS = 13;
1040    static final int WRITE_PACKAGE_RESTRICTIONS = 14;
1041    static final int PACKAGE_VERIFIED = 15;
1042    static final int CHECK_PENDING_VERIFICATION = 16;
1043    static final int START_INTENT_FILTER_VERIFICATIONS = 17;
1044    static final int INTENT_FILTER_VERIFIED = 18;
1045    static final int WRITE_PACKAGE_LIST = 19;
1046
1047    static final int WRITE_SETTINGS_DELAY = 10*1000;  // 10 seconds
1048
1049    // Delay time in millisecs
1050    static final int BROADCAST_DELAY = 10 * 1000;
1051
1052    static UserManagerService sUserManager;
1053
1054    // Stores a list of users whose package restrictions file needs to be updated
1055    private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>();
1056
1057    final private DefaultContainerConnection mDefContainerConn =
1058            new DefaultContainerConnection();
1059    class DefaultContainerConnection implements ServiceConnection {
1060        public void onServiceConnected(ComponentName name, IBinder service) {
1061            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
1062            IMediaContainerService imcs =
1063                IMediaContainerService.Stub.asInterface(service);
1064            mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
1065        }
1066
1067        public void onServiceDisconnected(ComponentName name) {
1068            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
1069        }
1070    }
1071
1072    // Recordkeeping of restore-after-install operations that are currently in flight
1073    // between the Package Manager and the Backup Manager
1074    static class PostInstallData {
1075        public InstallArgs args;
1076        public PackageInstalledInfo res;
1077
1078        PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
1079            args = _a;
1080            res = _r;
1081        }
1082    }
1083
1084    final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
1085    int mNextInstallToken = 1;  // nonzero; will be wrapped back to 1 when ++ overflows
1086
1087    // XML tags for backup/restore of various bits of state
1088    private static final String TAG_PREFERRED_BACKUP = "pa";
1089    private static final String TAG_DEFAULT_APPS = "da";
1090    private static final String TAG_INTENT_FILTER_VERIFICATION = "iv";
1091
1092    private static final String TAG_PERMISSION_BACKUP = "perm-grant-backup";
1093    private static final String TAG_ALL_GRANTS = "rt-grants";
1094    private static final String TAG_GRANT = "grant";
1095    private static final String ATTR_PACKAGE_NAME = "pkg";
1096
1097    private static final String TAG_PERMISSION = "perm";
1098    private static final String ATTR_PERMISSION_NAME = "name";
1099    private static final String ATTR_IS_GRANTED = "g";
1100    private static final String ATTR_USER_SET = "set";
1101    private static final String ATTR_USER_FIXED = "fixed";
1102    private static final String ATTR_REVOKE_ON_UPGRADE = "rou";
1103
1104    // System/policy permission grants are not backed up
1105    private static final int SYSTEM_RUNTIME_GRANT_MASK =
1106            FLAG_PERMISSION_POLICY_FIXED
1107            | FLAG_PERMISSION_SYSTEM_FIXED
1108            | FLAG_PERMISSION_GRANTED_BY_DEFAULT;
1109
1110    // And we back up these user-adjusted states
1111    private static final int USER_RUNTIME_GRANT_MASK =
1112            FLAG_PERMISSION_USER_SET
1113            | FLAG_PERMISSION_USER_FIXED
1114            | FLAG_PERMISSION_REVOKE_ON_UPGRADE;
1115
1116    final @Nullable String mRequiredVerifierPackage;
1117    final @NonNull String mRequiredInstallerPackage;
1118    final @Nullable String mSetupWizardPackage;
1119    final @NonNull String mServicesSystemSharedLibraryPackageName;
1120    final @NonNull String mSharedSystemSharedLibraryPackageName;
1121
1122    private final PackageUsage mPackageUsage = new PackageUsage();
1123    private final CompilerStats mCompilerStats = new CompilerStats();
1124
1125    class PackageHandler extends Handler {
1126        private boolean mBound = false;
1127        final ArrayList<HandlerParams> mPendingInstalls =
1128            new ArrayList<HandlerParams>();
1129
1130        private boolean connectToService() {
1131            if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
1132                    " DefaultContainerService");
1133            Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
1134            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1135            if (mContext.bindServiceAsUser(service, mDefContainerConn,
1136                    Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
1137                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1138                mBound = true;
1139                return true;
1140            }
1141            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1142            return false;
1143        }
1144
1145        private void disconnectService() {
1146            mContainerService = null;
1147            mBound = false;
1148            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1149            mContext.unbindService(mDefContainerConn);
1150            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1151        }
1152
1153        PackageHandler(Looper looper) {
1154            super(looper);
1155        }
1156
1157        public void handleMessage(Message msg) {
1158            try {
1159                doHandleMessage(msg);
1160            } finally {
1161                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1162            }
1163        }
1164
1165        void doHandleMessage(Message msg) {
1166            switch (msg.what) {
1167                case INIT_COPY: {
1168                    HandlerParams params = (HandlerParams) msg.obj;
1169                    int idx = mPendingInstalls.size();
1170                    if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params);
1171                    // If a bind was already initiated we dont really
1172                    // need to do anything. The pending install
1173                    // will be processed later on.
1174                    if (!mBound) {
1175                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1176                                System.identityHashCode(mHandler));
1177                        // If this is the only one pending we might
1178                        // have to bind to the service again.
1179                        if (!connectToService()) {
1180                            Slog.e(TAG, "Failed to bind to media container service");
1181                            params.serviceError();
1182                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1183                                    System.identityHashCode(mHandler));
1184                            if (params.traceMethod != null) {
1185                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod,
1186                                        params.traceCookie);
1187                            }
1188                            return;
1189                        } else {
1190                            // Once we bind to the service, the first
1191                            // pending request will be processed.
1192                            mPendingInstalls.add(idx, params);
1193                        }
1194                    } else {
1195                        mPendingInstalls.add(idx, params);
1196                        // Already bound to the service. Just make
1197                        // sure we trigger off processing the first request.
1198                        if (idx == 0) {
1199                            mHandler.sendEmptyMessage(MCS_BOUND);
1200                        }
1201                    }
1202                    break;
1203                }
1204                case MCS_BOUND: {
1205                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound");
1206                    if (msg.obj != null) {
1207                        mContainerService = (IMediaContainerService) msg.obj;
1208                        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1209                                System.identityHashCode(mHandler));
1210                    }
1211                    if (mContainerService == null) {
1212                        if (!mBound) {
1213                            // Something seriously wrong since we are not bound and we are not
1214                            // waiting for connection. Bail out.
1215                            Slog.e(TAG, "Cannot bind to media container service");
1216                            for (HandlerParams params : mPendingInstalls) {
1217                                // Indicate service bind error
1218                                params.serviceError();
1219                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1220                                        System.identityHashCode(params));
1221                                if (params.traceMethod != null) {
1222                                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER,
1223                                            params.traceMethod, params.traceCookie);
1224                                }
1225                                return;
1226                            }
1227                            mPendingInstalls.clear();
1228                        } else {
1229                            Slog.w(TAG, "Waiting to connect to media container service");
1230                        }
1231                    } else if (mPendingInstalls.size() > 0) {
1232                        HandlerParams params = mPendingInstalls.get(0);
1233                        if (params != null) {
1234                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1235                                    System.identityHashCode(params));
1236                            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy");
1237                            if (params.startCopy()) {
1238                                // We are done...  look for more work or to
1239                                // go idle.
1240                                if (DEBUG_SD_INSTALL) Log.i(TAG,
1241                                        "Checking for more work or unbind...");
1242                                // Delete pending install
1243                                if (mPendingInstalls.size() > 0) {
1244                                    mPendingInstalls.remove(0);
1245                                }
1246                                if (mPendingInstalls.size() == 0) {
1247                                    if (mBound) {
1248                                        if (DEBUG_SD_INSTALL) Log.i(TAG,
1249                                                "Posting delayed MCS_UNBIND");
1250                                        removeMessages(MCS_UNBIND);
1251                                        Message ubmsg = obtainMessage(MCS_UNBIND);
1252                                        // Unbind after a little delay, to avoid
1253                                        // continual thrashing.
1254                                        sendMessageDelayed(ubmsg, 10000);
1255                                    }
1256                                } else {
1257                                    // There are more pending requests in queue.
1258                                    // Just post MCS_BOUND message to trigger processing
1259                                    // of next pending install.
1260                                    if (DEBUG_SD_INSTALL) Log.i(TAG,
1261                                            "Posting MCS_BOUND for next work");
1262                                    mHandler.sendEmptyMessage(MCS_BOUND);
1263                                }
1264                            }
1265                            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
1266                        }
1267                    } else {
1268                        // Should never happen ideally.
1269                        Slog.w(TAG, "Empty queue");
1270                    }
1271                    break;
1272                }
1273                case MCS_RECONNECT: {
1274                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect");
1275                    if (mPendingInstalls.size() > 0) {
1276                        if (mBound) {
1277                            disconnectService();
1278                        }
1279                        if (!connectToService()) {
1280                            Slog.e(TAG, "Failed to bind to media container service");
1281                            for (HandlerParams params : mPendingInstalls) {
1282                                // Indicate service bind error
1283                                params.serviceError();
1284                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1285                                        System.identityHashCode(params));
1286                            }
1287                            mPendingInstalls.clear();
1288                        }
1289                    }
1290                    break;
1291                }
1292                case MCS_UNBIND: {
1293                    // If there is no actual work left, then time to unbind.
1294                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind");
1295
1296                    if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) {
1297                        if (mBound) {
1298                            if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()");
1299
1300                            disconnectService();
1301                        }
1302                    } else if (mPendingInstalls.size() > 0) {
1303                        // There are more pending requests in queue.
1304                        // Just post MCS_BOUND message to trigger processing
1305                        // of next pending install.
1306                        mHandler.sendEmptyMessage(MCS_BOUND);
1307                    }
1308
1309                    break;
1310                }
1311                case MCS_GIVE_UP: {
1312                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries");
1313                    HandlerParams params = mPendingInstalls.remove(0);
1314                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1315                            System.identityHashCode(params));
1316                    break;
1317                }
1318                case SEND_PENDING_BROADCAST: {
1319                    String packages[];
1320                    ArrayList<String> components[];
1321                    int size = 0;
1322                    int uids[];
1323                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1324                    synchronized (mPackages) {
1325                        if (mPendingBroadcasts == null) {
1326                            return;
1327                        }
1328                        size = mPendingBroadcasts.size();
1329                        if (size <= 0) {
1330                            // Nothing to be done. Just return
1331                            return;
1332                        }
1333                        packages = new String[size];
1334                        components = new ArrayList[size];
1335                        uids = new int[size];
1336                        int i = 0;  // filling out the above arrays
1337
1338                        for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) {
1339                            int packageUserId = mPendingBroadcasts.userIdAt(n);
1340                            Iterator<Map.Entry<String, ArrayList<String>>> it
1341                                    = mPendingBroadcasts.packagesForUserId(packageUserId)
1342                                            .entrySet().iterator();
1343                            while (it.hasNext() && i < size) {
1344                                Map.Entry<String, ArrayList<String>> ent = it.next();
1345                                packages[i] = ent.getKey();
1346                                components[i] = ent.getValue();
1347                                PackageSetting ps = mSettings.mPackages.get(ent.getKey());
1348                                uids[i] = (ps != null)
1349                                        ? UserHandle.getUid(packageUserId, ps.appId)
1350                                        : -1;
1351                                i++;
1352                            }
1353                        }
1354                        size = i;
1355                        mPendingBroadcasts.clear();
1356                    }
1357                    // Send broadcasts
1358                    for (int i = 0; i < size; i++) {
1359                        sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]);
1360                    }
1361                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1362                    break;
1363                }
1364                case START_CLEANING_PACKAGE: {
1365                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1366                    final String packageName = (String)msg.obj;
1367                    final int userId = msg.arg1;
1368                    final boolean andCode = msg.arg2 != 0;
1369                    synchronized (mPackages) {
1370                        if (userId == UserHandle.USER_ALL) {
1371                            int[] users = sUserManager.getUserIds();
1372                            for (int user : users) {
1373                                mSettings.addPackageToCleanLPw(
1374                                        new PackageCleanItem(user, packageName, andCode));
1375                            }
1376                        } else {
1377                            mSettings.addPackageToCleanLPw(
1378                                    new PackageCleanItem(userId, packageName, andCode));
1379                        }
1380                    }
1381                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1382                    startCleaningPackages();
1383                } break;
1384                case POST_INSTALL: {
1385                    if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
1386
1387                    PostInstallData data = mRunningInstalls.get(msg.arg1);
1388                    final boolean didRestore = (msg.arg2 != 0);
1389                    mRunningInstalls.delete(msg.arg1);
1390
1391                    if (data != null) {
1392                        InstallArgs args = data.args;
1393                        PackageInstalledInfo parentRes = data.res;
1394
1395                        final boolean grantPermissions = (args.installFlags
1396                                & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0;
1397                        final boolean killApp = (args.installFlags
1398                                & PackageManager.INSTALL_DONT_KILL_APP) == 0;
1399                        final String[] grantedPermissions = args.installGrantPermissions;
1400
1401                        // Handle the parent package
1402                        handlePackagePostInstall(parentRes, grantPermissions, killApp,
1403                                grantedPermissions, didRestore, args.installerPackageName,
1404                                args.observer);
1405
1406                        // Handle the child packages
1407                        final int childCount = (parentRes.addedChildPackages != null)
1408                                ? parentRes.addedChildPackages.size() : 0;
1409                        for (int i = 0; i < childCount; i++) {
1410                            PackageInstalledInfo childRes = parentRes.addedChildPackages.valueAt(i);
1411                            handlePackagePostInstall(childRes, grantPermissions, killApp,
1412                                    grantedPermissions, false, args.installerPackageName,
1413                                    args.observer);
1414                        }
1415
1416                        // Log tracing if needed
1417                        if (args.traceMethod != null) {
1418                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod,
1419                                    args.traceCookie);
1420                        }
1421                    } else {
1422                        Slog.e(TAG, "Bogus post-install token " + msg.arg1);
1423                    }
1424
1425                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1);
1426                } break;
1427                case UPDATED_MEDIA_STATUS: {
1428                    if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS");
1429                    boolean reportStatus = msg.arg1 == 1;
1430                    boolean doGc = msg.arg2 == 1;
1431                    if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc);
1432                    if (doGc) {
1433                        // Force a gc to clear up stale containers.
1434                        Runtime.getRuntime().gc();
1435                    }
1436                    if (msg.obj != null) {
1437                        @SuppressWarnings("unchecked")
1438                        Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj;
1439                        if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers");
1440                        // Unload containers
1441                        unloadAllContainers(args);
1442                    }
1443                    if (reportStatus) {
1444                        try {
1445                            if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back");
1446                            PackageHelper.getMountService().finishMediaUpdate();
1447                        } catch (RemoteException e) {
1448                            Log.e(TAG, "MountService not running?");
1449                        }
1450                    }
1451                } break;
1452                case WRITE_SETTINGS: {
1453                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1454                    synchronized (mPackages) {
1455                        removeMessages(WRITE_SETTINGS);
1456                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1457                        mSettings.writeLPr();
1458                        mDirtyUsers.clear();
1459                    }
1460                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1461                } break;
1462                case WRITE_PACKAGE_RESTRICTIONS: {
1463                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1464                    synchronized (mPackages) {
1465                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1466                        for (int userId : mDirtyUsers) {
1467                            mSettings.writePackageRestrictionsLPr(userId);
1468                        }
1469                        mDirtyUsers.clear();
1470                    }
1471                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1472                } break;
1473                case WRITE_PACKAGE_LIST: {
1474                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1475                    synchronized (mPackages) {
1476                        removeMessages(WRITE_PACKAGE_LIST);
1477                        mSettings.writePackageListLPr(msg.arg1);
1478                    }
1479                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1480                } break;
1481                case CHECK_PENDING_VERIFICATION: {
1482                    final int verificationId = msg.arg1;
1483                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1484
1485                    if ((state != null) && !state.timeoutExtended()) {
1486                        final InstallArgs args = state.getInstallArgs();
1487                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1488
1489                        Slog.i(TAG, "Verification timed out for " + originUri);
1490                        mPendingVerification.remove(verificationId);
1491
1492                        int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1493
1494                        if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) {
1495                            Slog.i(TAG, "Continuing with installation of " + originUri);
1496                            state.setVerifierResponse(Binder.getCallingUid(),
1497                                    PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT);
1498                            broadcastPackageVerified(verificationId, originUri,
1499                                    PackageManager.VERIFICATION_ALLOW,
1500                                    state.getInstallArgs().getUser());
1501                            try {
1502                                ret = args.copyApk(mContainerService, true);
1503                            } catch (RemoteException e) {
1504                                Slog.e(TAG, "Could not contact the ContainerService");
1505                            }
1506                        } else {
1507                            broadcastPackageVerified(verificationId, originUri,
1508                                    PackageManager.VERIFICATION_REJECT,
1509                                    state.getInstallArgs().getUser());
1510                        }
1511
1512                        Trace.asyncTraceEnd(
1513                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1514
1515                        processPendingInstall(args, ret);
1516                        mHandler.sendEmptyMessage(MCS_UNBIND);
1517                    }
1518                    break;
1519                }
1520                case PACKAGE_VERIFIED: {
1521                    final int verificationId = msg.arg1;
1522
1523                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1524                    if (state == null) {
1525                        Slog.w(TAG, "Invalid verification token " + verificationId + " received");
1526                        break;
1527                    }
1528
1529                    final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj;
1530
1531                    state.setVerifierResponse(response.callerUid, response.code);
1532
1533                    if (state.isVerificationComplete()) {
1534                        mPendingVerification.remove(verificationId);
1535
1536                        final InstallArgs args = state.getInstallArgs();
1537                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1538
1539                        int ret;
1540                        if (state.isInstallAllowed()) {
1541                            ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
1542                            broadcastPackageVerified(verificationId, originUri,
1543                                    response.code, state.getInstallArgs().getUser());
1544                            try {
1545                                ret = args.copyApk(mContainerService, true);
1546                            } catch (RemoteException e) {
1547                                Slog.e(TAG, "Could not contact the ContainerService");
1548                            }
1549                        } else {
1550                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1551                        }
1552
1553                        Trace.asyncTraceEnd(
1554                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1555
1556                        processPendingInstall(args, ret);
1557                        mHandler.sendEmptyMessage(MCS_UNBIND);
1558                    }
1559
1560                    break;
1561                }
1562                case START_INTENT_FILTER_VERIFICATIONS: {
1563                    IFVerificationParams params = (IFVerificationParams) msg.obj;
1564                    verifyIntentFiltersIfNeeded(params.userId, params.verifierUid,
1565                            params.replacing, params.pkg);
1566                    break;
1567                }
1568                case INTENT_FILTER_VERIFIED: {
1569                    final int verificationId = msg.arg1;
1570
1571                    final IntentFilterVerificationState state = mIntentFilterVerificationStates.get(
1572                            verificationId);
1573                    if (state == null) {
1574                        Slog.w(TAG, "Invalid IntentFilter verification token "
1575                                + verificationId + " received");
1576                        break;
1577                    }
1578
1579                    final int userId = state.getUserId();
1580
1581                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1582                            "Processing IntentFilter verification with token:"
1583                            + verificationId + " and userId:" + userId);
1584
1585                    final IntentFilterVerificationResponse response =
1586                            (IntentFilterVerificationResponse) msg.obj;
1587
1588                    state.setVerifierResponse(response.callerUid, response.code);
1589
1590                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1591                            "IntentFilter verification with token:" + verificationId
1592                            + " and userId:" + userId
1593                            + " is settings verifier response with response code:"
1594                            + response.code);
1595
1596                    if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) {
1597                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: "
1598                                + response.getFailedDomainsString());
1599                    }
1600
1601                    if (state.isVerificationComplete()) {
1602                        mIntentFilterVerifier.receiveVerificationResponse(verificationId);
1603                    } else {
1604                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1605                                "IntentFilter verification with token:" + verificationId
1606                                + " was not said to be complete");
1607                    }
1608
1609                    break;
1610                }
1611            }
1612        }
1613    }
1614
1615    private void handlePackagePostInstall(PackageInstalledInfo res, boolean grantPermissions,
1616            boolean killApp, String[] grantedPermissions,
1617            boolean launchedForRestore, String installerPackage,
1618            IPackageInstallObserver2 installObserver) {
1619        if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
1620            // Send the removed broadcasts
1621            if (res.removedInfo != null) {
1622                res.removedInfo.sendPackageRemovedBroadcasts(killApp);
1623            }
1624
1625            // Now that we successfully installed the package, grant runtime
1626            // permissions if requested before broadcasting the install.
1627            if (grantPermissions && res.pkg.applicationInfo.targetSdkVersion
1628                    >= Build.VERSION_CODES.M) {
1629                grantRequestedRuntimePermissions(res.pkg, res.newUsers, grantedPermissions);
1630            }
1631
1632            final boolean update = res.removedInfo != null
1633                    && res.removedInfo.removedPackage != null;
1634
1635            // If this is the first time we have child packages for a disabled privileged
1636            // app that had no children, we grant requested runtime permissions to the new
1637            // children if the parent on the system image had them already granted.
1638            if (res.pkg.parentPackage != null) {
1639                synchronized (mPackages) {
1640                    grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(res.pkg);
1641                }
1642            }
1643
1644            synchronized (mPackages) {
1645                mEphemeralApplicationRegistry.onPackageInstalledLPw(res.pkg);
1646            }
1647
1648            final String packageName = res.pkg.applicationInfo.packageName;
1649            Bundle extras = new Bundle(1);
1650            extras.putInt(Intent.EXTRA_UID, res.uid);
1651
1652            // Determine the set of users who are adding this package for
1653            // the first time vs. those who are seeing an update.
1654            int[] firstUsers = EMPTY_INT_ARRAY;
1655            int[] updateUsers = EMPTY_INT_ARRAY;
1656            if (res.origUsers == null || res.origUsers.length == 0) {
1657                firstUsers = res.newUsers;
1658            } else {
1659                for (int newUser : res.newUsers) {
1660                    boolean isNew = true;
1661                    for (int origUser : res.origUsers) {
1662                        if (origUser == newUser) {
1663                            isNew = false;
1664                            break;
1665                        }
1666                    }
1667                    if (isNew) {
1668                        firstUsers = ArrayUtils.appendInt(firstUsers, newUser);
1669                    } else {
1670                        updateUsers = ArrayUtils.appendInt(updateUsers, newUser);
1671                    }
1672                }
1673            }
1674
1675            // Send installed broadcasts if the install/update is not ephemeral
1676            if (!isEphemeral(res.pkg)) {
1677                mProcessLoggingHandler.invalidateProcessLoggingBaseApkHash(res.pkg.baseCodePath);
1678
1679                // Send added for users that see the package for the first time
1680                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
1681                        extras, 0 /*flags*/, null /*targetPackage*/,
1682                        null /*finishedReceiver*/, firstUsers);
1683
1684                // Send added for users that don't see the package for the first time
1685                if (update) {
1686                    extras.putBoolean(Intent.EXTRA_REPLACING, true);
1687                }
1688                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
1689                        extras, 0 /*flags*/, null /*targetPackage*/,
1690                        null /*finishedReceiver*/, updateUsers);
1691
1692                // Send replaced for users that don't see the package for the first time
1693                if (update) {
1694                    sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
1695                            packageName, extras, 0 /*flags*/,
1696                            null /*targetPackage*/, null /*finishedReceiver*/,
1697                            updateUsers);
1698                    sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
1699                            null /*package*/, null /*extras*/, 0 /*flags*/,
1700                            packageName /*targetPackage*/,
1701                            null /*finishedReceiver*/, updateUsers);
1702                } else if (launchedForRestore && !isSystemApp(res.pkg)) {
1703                    // First-install and we did a restore, so we're responsible for the
1704                    // first-launch broadcast.
1705                    if (DEBUG_BACKUP) {
1706                        Slog.i(TAG, "Post-restore of " + packageName
1707                                + " sending FIRST_LAUNCH in " + Arrays.toString(firstUsers));
1708                    }
1709                    sendFirstLaunchBroadcast(packageName, installerPackage, firstUsers);
1710                }
1711
1712                // Send broadcast package appeared if forward locked/external for all users
1713                // treat asec-hosted packages like removable media on upgrade
1714                if (res.pkg.isForwardLocked() || isExternal(res.pkg)) {
1715                    if (DEBUG_INSTALL) {
1716                        Slog.i(TAG, "upgrading pkg " + res.pkg
1717                                + " is ASEC-hosted -> AVAILABLE");
1718                    }
1719                    final int[] uidArray = new int[]{res.pkg.applicationInfo.uid};
1720                    ArrayList<String> pkgList = new ArrayList<>(1);
1721                    pkgList.add(packageName);
1722                    sendResourcesChangedBroadcast(true, true, pkgList, uidArray, null);
1723                }
1724            }
1725
1726            // Work that needs to happen on first install within each user
1727            if (firstUsers != null && firstUsers.length > 0) {
1728                synchronized (mPackages) {
1729                    for (int userId : firstUsers) {
1730                        // If this app is a browser and it's newly-installed for some
1731                        // users, clear any default-browser state in those users. The
1732                        // app's nature doesn't depend on the user, so we can just check
1733                        // its browser nature in any user and generalize.
1734                        if (packageIsBrowser(packageName, userId)) {
1735                            mSettings.setDefaultBrowserPackageNameLPw(null, userId);
1736                        }
1737
1738                        // We may also need to apply pending (restored) runtime
1739                        // permission grants within these users.
1740                        mSettings.applyPendingPermissionGrantsLPw(packageName, userId);
1741                    }
1742                }
1743            }
1744
1745            // Log current value of "unknown sources" setting
1746            EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED,
1747                    getUnknownSourcesSettings());
1748
1749            // Force a gc to clear up things
1750            Runtime.getRuntime().gc();
1751
1752            // Remove the replaced package's older resources safely now
1753            // We delete after a gc for applications  on sdcard.
1754            if (res.removedInfo != null && res.removedInfo.args != null) {
1755                synchronized (mInstallLock) {
1756                    res.removedInfo.args.doPostDeleteLI(true);
1757                }
1758            }
1759        }
1760
1761        // If someone is watching installs - notify them
1762        if (installObserver != null) {
1763            try {
1764                Bundle extras = extrasForInstallResult(res);
1765                installObserver.onPackageInstalled(res.name, res.returnCode,
1766                        res.returnMsg, extras);
1767            } catch (RemoteException e) {
1768                Slog.i(TAG, "Observer no longer exists.");
1769            }
1770        }
1771    }
1772
1773    private void grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(
1774            PackageParser.Package pkg) {
1775        if (pkg.parentPackage == null) {
1776            return;
1777        }
1778        if (pkg.requestedPermissions == null) {
1779            return;
1780        }
1781        final PackageSetting disabledSysParentPs = mSettings
1782                .getDisabledSystemPkgLPr(pkg.parentPackage.packageName);
1783        if (disabledSysParentPs == null || disabledSysParentPs.pkg == null
1784                || !disabledSysParentPs.isPrivileged()
1785                || (disabledSysParentPs.childPackageNames != null
1786                        && !disabledSysParentPs.childPackageNames.isEmpty())) {
1787            return;
1788        }
1789        final int[] allUserIds = sUserManager.getUserIds();
1790        final int permCount = pkg.requestedPermissions.size();
1791        for (int i = 0; i < permCount; i++) {
1792            String permission = pkg.requestedPermissions.get(i);
1793            BasePermission bp = mSettings.mPermissions.get(permission);
1794            if (bp == null || !(bp.isRuntime() || bp.isDevelopment())) {
1795                continue;
1796            }
1797            for (int userId : allUserIds) {
1798                if (disabledSysParentPs.getPermissionsState().hasRuntimePermission(
1799                        permission, userId)) {
1800                    grantRuntimePermission(pkg.packageName, permission, userId);
1801                }
1802            }
1803        }
1804    }
1805
1806    private StorageEventListener mStorageListener = new StorageEventListener() {
1807        @Override
1808        public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) {
1809            if (vol.type == VolumeInfo.TYPE_PRIVATE) {
1810                if (vol.state == VolumeInfo.STATE_MOUNTED) {
1811                    final String volumeUuid = vol.getFsUuid();
1812
1813                    // Clean up any users or apps that were removed or recreated
1814                    // while this volume was missing
1815                    reconcileUsers(volumeUuid);
1816                    reconcileApps(volumeUuid);
1817
1818                    // Clean up any install sessions that expired or were
1819                    // cancelled while this volume was missing
1820                    mInstallerService.onPrivateVolumeMounted(volumeUuid);
1821
1822                    loadPrivatePackages(vol);
1823
1824                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
1825                    unloadPrivatePackages(vol);
1826                }
1827            }
1828
1829            if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) {
1830                if (vol.state == VolumeInfo.STATE_MOUNTED) {
1831                    updateExternalMediaStatus(true, false);
1832                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
1833                    updateExternalMediaStatus(false, false);
1834                }
1835            }
1836        }
1837
1838        @Override
1839        public void onVolumeForgotten(String fsUuid) {
1840            if (TextUtils.isEmpty(fsUuid)) {
1841                Slog.e(TAG, "Forgetting internal storage is probably a mistake; ignoring");
1842                return;
1843            }
1844
1845            // Remove any apps installed on the forgotten volume
1846            synchronized (mPackages) {
1847                final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid);
1848                for (PackageSetting ps : packages) {
1849                    Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten");
1850                    deletePackage(ps.name, new LegacyPackageDeleteObserver(null).getBinder(),
1851                            UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS);
1852                }
1853
1854                mSettings.onVolumeForgotten(fsUuid);
1855                mSettings.writeLPr();
1856            }
1857        }
1858    };
1859
1860    private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int[] userIds,
1861            String[] grantedPermissions) {
1862        for (int userId : userIds) {
1863            grantRequestedRuntimePermissionsForUser(pkg, userId, grantedPermissions);
1864        }
1865
1866        // We could have touched GID membership, so flush out packages.list
1867        synchronized (mPackages) {
1868            mSettings.writePackageListLPr();
1869        }
1870    }
1871
1872    private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId,
1873            String[] grantedPermissions) {
1874        SettingBase sb = (SettingBase) pkg.mExtras;
1875        if (sb == null) {
1876            return;
1877        }
1878
1879        PermissionsState permissionsState = sb.getPermissionsState();
1880
1881        final int immutableFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
1882                | PackageManager.FLAG_PERMISSION_POLICY_FIXED;
1883
1884        for (String permission : pkg.requestedPermissions) {
1885            final BasePermission bp;
1886            synchronized (mPackages) {
1887                bp = mSettings.mPermissions.get(permission);
1888            }
1889            if (bp != null && (bp.isRuntime() || bp.isDevelopment())
1890                    && (grantedPermissions == null
1891                           || ArrayUtils.contains(grantedPermissions, permission))) {
1892                final int flags = permissionsState.getPermissionFlags(permission, userId);
1893                // Installer cannot change immutable permissions.
1894                if ((flags & immutableFlags) == 0) {
1895                    grantRuntimePermission(pkg.packageName, permission, userId);
1896                }
1897            }
1898        }
1899    }
1900
1901    Bundle extrasForInstallResult(PackageInstalledInfo res) {
1902        Bundle extras = null;
1903        switch (res.returnCode) {
1904            case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: {
1905                extras = new Bundle();
1906                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION,
1907                        res.origPermission);
1908                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE,
1909                        res.origPackage);
1910                break;
1911            }
1912            case PackageManager.INSTALL_SUCCEEDED: {
1913                extras = new Bundle();
1914                extras.putBoolean(Intent.EXTRA_REPLACING,
1915                        res.removedInfo != null && res.removedInfo.removedPackage != null);
1916                break;
1917            }
1918        }
1919        return extras;
1920    }
1921
1922    void scheduleWriteSettingsLocked() {
1923        if (!mHandler.hasMessages(WRITE_SETTINGS)) {
1924            mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
1925        }
1926    }
1927
1928    void scheduleWritePackageListLocked(int userId) {
1929        if (!mHandler.hasMessages(WRITE_PACKAGE_LIST)) {
1930            Message msg = mHandler.obtainMessage(WRITE_PACKAGE_LIST);
1931            msg.arg1 = userId;
1932            mHandler.sendMessageDelayed(msg, WRITE_SETTINGS_DELAY);
1933        }
1934    }
1935
1936    void scheduleWritePackageRestrictionsLocked(UserHandle user) {
1937        final int userId = user == null ? UserHandle.USER_ALL : user.getIdentifier();
1938        scheduleWritePackageRestrictionsLocked(userId);
1939    }
1940
1941    void scheduleWritePackageRestrictionsLocked(int userId) {
1942        final int[] userIds = (userId == UserHandle.USER_ALL)
1943                ? sUserManager.getUserIds() : new int[]{userId};
1944        for (int nextUserId : userIds) {
1945            if (!sUserManager.exists(nextUserId)) return;
1946            mDirtyUsers.add(nextUserId);
1947            if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) {
1948                mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY);
1949            }
1950        }
1951    }
1952
1953    public static PackageManagerService main(Context context, Installer installer,
1954            boolean factoryTest, boolean onlyCore) {
1955        // Self-check for initial settings.
1956        PackageManagerServiceCompilerMapping.checkProperties();
1957
1958        PackageManagerService m = new PackageManagerService(context, installer,
1959                factoryTest, onlyCore);
1960        m.enableSystemUserPackages();
1961        // Disable any carrier apps. We do this very early in boot to prevent the apps from being
1962        // disabled after already being started.
1963        CarrierAppUtils.disableCarrierAppsUntilPrivileged(context.getOpPackageName(), m,
1964                UserHandle.USER_SYSTEM);
1965        ServiceManager.addService("package", m);
1966        return m;
1967    }
1968
1969    private void enableSystemUserPackages() {
1970        if (!UserManager.isSplitSystemUser()) {
1971            return;
1972        }
1973        // For system user, enable apps based on the following conditions:
1974        // - app is whitelisted or belong to one of these groups:
1975        //   -- system app which has no launcher icons
1976        //   -- system app which has INTERACT_ACROSS_USERS permission
1977        //   -- system IME app
1978        // - app is not in the blacklist
1979        AppsQueryHelper queryHelper = new AppsQueryHelper(this);
1980        Set<String> enableApps = new ArraySet<>();
1981        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS
1982                | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM
1983                | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM));
1984        ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps();
1985        enableApps.addAll(wlApps);
1986        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_REQUIRED_FOR_SYSTEM_USER,
1987                /* systemAppsOnly */ false, UserHandle.SYSTEM));
1988        ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps();
1989        enableApps.removeAll(blApps);
1990        Log.i(TAG, "Applications installed for system user: " + enableApps);
1991        List<String> allAps = queryHelper.queryApps(0, /* systemAppsOnly */ false,
1992                UserHandle.SYSTEM);
1993        final int allAppsSize = allAps.size();
1994        synchronized (mPackages) {
1995            for (int i = 0; i < allAppsSize; i++) {
1996                String pName = allAps.get(i);
1997                PackageSetting pkgSetting = mSettings.mPackages.get(pName);
1998                // Should not happen, but we shouldn't be failing if it does
1999                if (pkgSetting == null) {
2000                    continue;
2001                }
2002                boolean install = enableApps.contains(pName);
2003                if (pkgSetting.getInstalled(UserHandle.USER_SYSTEM) != install) {
2004                    Log.i(TAG, (install ? "Installing " : "Uninstalling ") + pName
2005                            + " for system user");
2006                    pkgSetting.setInstalled(install, UserHandle.USER_SYSTEM);
2007                }
2008            }
2009        }
2010    }
2011
2012    private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) {
2013        DisplayManager displayManager = (DisplayManager) context.getSystemService(
2014                Context.DISPLAY_SERVICE);
2015        displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics);
2016    }
2017
2018    /**
2019     * Requests that files preopted on a secondary system partition be copied to the data partition
2020     * if possible.  Note that the actual copying of the files is accomplished by init for security
2021     * reasons. This simply requests that the copy takes place and awaits confirmation of its
2022     * completion. See platform/system/extras/cppreopt/ for the implementation of the actual copy.
2023     */
2024    private static void requestCopyPreoptedFiles() {
2025        final int WAIT_TIME_MS = 100;
2026        final String CP_PREOPT_PROPERTY = "sys.cppreopt";
2027        if (SystemProperties.getInt("ro.cp_system_other_odex", 0) == 1) {
2028            SystemProperties.set(CP_PREOPT_PROPERTY, "requested");
2029            // We will wait for up to 100 seconds.
2030            final long timeEnd = SystemClock.uptimeMillis() + 100 * 1000;
2031            while (!SystemProperties.get(CP_PREOPT_PROPERTY).equals("finished")) {
2032                try {
2033                    Thread.sleep(WAIT_TIME_MS);
2034                } catch (InterruptedException e) {
2035                    // Do nothing
2036                }
2037                if (SystemClock.uptimeMillis() > timeEnd) {
2038                    SystemProperties.set(CP_PREOPT_PROPERTY, "timed-out");
2039                    Slog.wtf(TAG, "cppreopt did not finish!");
2040                    break;
2041                }
2042            }
2043        }
2044    }
2045
2046    public PackageManagerService(Context context, Installer installer,
2047            boolean factoryTest, boolean onlyCore) {
2048        EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
2049                SystemClock.uptimeMillis());
2050
2051        if (mSdkVersion <= 0) {
2052            Slog.w(TAG, "**** ro.build.version.sdk not set!");
2053        }
2054
2055        mContext = context;
2056        mFactoryTest = factoryTest;
2057        mOnlyCore = onlyCore;
2058        mMetrics = new DisplayMetrics();
2059        mSettings = new Settings(mPackages);
2060        mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID,
2061                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2062        mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID,
2063                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2064        mSettings.addSharedUserLPw("android.uid.log", LOG_UID,
2065                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2066        mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID,
2067                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2068        mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID,
2069                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2070        mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID,
2071                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2072
2073        String separateProcesses = SystemProperties.get("debug.separate_processes");
2074        if (separateProcesses != null && separateProcesses.length() > 0) {
2075            if ("*".equals(separateProcesses)) {
2076                mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
2077                mSeparateProcesses = null;
2078                Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
2079            } else {
2080                mDefParseFlags = 0;
2081                mSeparateProcesses = separateProcesses.split(",");
2082                Slog.w(TAG, "Running with debug.separate_processes: "
2083                        + separateProcesses);
2084            }
2085        } else {
2086            mDefParseFlags = 0;
2087            mSeparateProcesses = null;
2088        }
2089
2090        mInstaller = installer;
2091        mPackageDexOptimizer = new PackageDexOptimizer(installer, mInstallLock, context,
2092                "*dexopt*");
2093        mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper());
2094
2095        mOnPermissionChangeListeners = new OnPermissionChangeListeners(
2096                FgThread.get().getLooper());
2097
2098        getDefaultDisplayMetrics(context, mMetrics);
2099
2100        SystemConfig systemConfig = SystemConfig.getInstance();
2101        mGlobalGids = systemConfig.getGlobalGids();
2102        mSystemPermissions = systemConfig.getSystemPermissions();
2103        mAvailableFeatures = systemConfig.getAvailableFeatures();
2104
2105        synchronized (mInstallLock) {
2106        // writer
2107        synchronized (mPackages) {
2108            mHandlerThread = new ServiceThread(TAG,
2109                    Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/);
2110            mHandlerThread.start();
2111            mHandler = new PackageHandler(mHandlerThread.getLooper());
2112            mProcessLoggingHandler = new ProcessLoggingHandler();
2113            Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT);
2114
2115            File dataDir = Environment.getDataDirectory();
2116            mAppInstallDir = new File(dataDir, "app");
2117            mAppLib32InstallDir = new File(dataDir, "app-lib");
2118            mEphemeralInstallDir = new File(dataDir, "app-ephemeral");
2119            mAsecInternalPath = new File(dataDir, "app-asec").getPath();
2120            mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
2121
2122            sUserManager = new UserManagerService(context, this, mPackages);
2123
2124            // Propagate permission configuration in to package manager.
2125            ArrayMap<String, SystemConfig.PermissionEntry> permConfig
2126                    = systemConfig.getPermissions();
2127            for (int i=0; i<permConfig.size(); i++) {
2128                SystemConfig.PermissionEntry perm = permConfig.valueAt(i);
2129                BasePermission bp = mSettings.mPermissions.get(perm.name);
2130                if (bp == null) {
2131                    bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN);
2132                    mSettings.mPermissions.put(perm.name, bp);
2133                }
2134                if (perm.gids != null) {
2135                    bp.setGids(perm.gids, perm.perUser);
2136                }
2137            }
2138
2139            ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries();
2140            for (int i=0; i<libConfig.size(); i++) {
2141                mSharedLibraries.put(libConfig.keyAt(i),
2142                        new SharedLibraryEntry(libConfig.valueAt(i), null));
2143            }
2144
2145            mFoundPolicyFile = SELinuxMMAC.readInstallPolicy();
2146
2147            mFirstBoot = !mSettings.readLPw(sUserManager.getUsers(false));
2148
2149            if (mFirstBoot) {
2150                requestCopyPreoptedFiles();
2151            }
2152
2153            String customResolverActivity = Resources.getSystem().getString(
2154                    R.string.config_customResolverActivity);
2155            if (TextUtils.isEmpty(customResolverActivity)) {
2156                customResolverActivity = null;
2157            } else {
2158                mCustomResolverComponentName = ComponentName.unflattenFromString(
2159                        customResolverActivity);
2160            }
2161
2162            long startTime = SystemClock.uptimeMillis();
2163
2164            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
2165                    startTime);
2166
2167            // Set flag to monitor and not change apk file paths when
2168            // scanning install directories.
2169            final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING | SCAN_INITIAL;
2170
2171            final String bootClassPath = System.getenv("BOOTCLASSPATH");
2172            final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH");
2173
2174            if (bootClassPath == null) {
2175                Slog.w(TAG, "No BOOTCLASSPATH found!");
2176            }
2177
2178            if (systemServerClassPath == null) {
2179                Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!");
2180            }
2181
2182            final List<String> allInstructionSets = InstructionSets.getAllInstructionSets();
2183            final String[] dexCodeInstructionSets =
2184                    getDexCodeInstructionSets(
2185                            allInstructionSets.toArray(new String[allInstructionSets.size()]));
2186
2187            /**
2188             * Ensure all external libraries have had dexopt run on them.
2189             */
2190            if (mSharedLibraries.size() > 0) {
2191                // NOTE: For now, we're compiling these system "shared libraries"
2192                // (and framework jars) into all available architectures. It's possible
2193                // to compile them only when we come across an app that uses them (there's
2194                // already logic for that in scanPackageLI) but that adds some complexity.
2195                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
2196                    for (SharedLibraryEntry libEntry : mSharedLibraries.values()) {
2197                        final String lib = libEntry.path;
2198                        if (lib == null) {
2199                            continue;
2200                        }
2201
2202                        try {
2203                            // Shared libraries do not have profiles so we perform a full
2204                            // AOT compilation (if needed).
2205                            int dexoptNeeded = DexFile.getDexOptNeeded(
2206                                    lib, dexCodeInstructionSet,
2207                                    getCompilerFilterForReason(REASON_SHARED_APK),
2208                                    false /* newProfile */);
2209                            if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) {
2210                                mInstaller.dexopt(lib, Process.SYSTEM_UID, dexCodeInstructionSet,
2211                                        dexoptNeeded, DEXOPT_PUBLIC /*dexFlags*/,
2212                                        getCompilerFilterForReason(REASON_SHARED_APK),
2213                                        StorageManager.UUID_PRIVATE_INTERNAL,
2214                                        SKIP_SHARED_LIBRARY_CHECK);
2215                            }
2216                        } catch (FileNotFoundException e) {
2217                            Slog.w(TAG, "Library not found: " + lib);
2218                        } catch (IOException | InstallerException e) {
2219                            Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? "
2220                                    + e.getMessage());
2221                        }
2222                    }
2223                }
2224            }
2225
2226            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
2227
2228            final VersionInfo ver = mSettings.getInternalVersion();
2229            mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint);
2230
2231            // when upgrading from pre-M, promote system app permissions from install to runtime
2232            mPromoteSystemApps =
2233                    mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1;
2234
2235            // When upgrading from pre-N, we need to handle package extraction like first boot,
2236            // as there is no profiling data available.
2237            mIsPreNUpgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N;
2238
2239            // save off the names of pre-existing system packages prior to scanning; we don't
2240            // want to automatically grant runtime permissions for new system apps
2241            if (mPromoteSystemApps) {
2242                Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator();
2243                while (pkgSettingIter.hasNext()) {
2244                    PackageSetting ps = pkgSettingIter.next();
2245                    if (isSystemApp(ps)) {
2246                        mExistingSystemPackages.add(ps.name);
2247                    }
2248                }
2249            }
2250
2251            // Collect vendor overlay packages.
2252            // (Do this before scanning any apps.)
2253            // For security and version matching reason, only consider
2254            // overlay packages if they reside in VENDOR_OVERLAY_DIR.
2255            File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR);
2256            scanDirTracedLI(vendorOverlayDir, mDefParseFlags
2257                    | PackageParser.PARSE_IS_SYSTEM
2258                    | PackageParser.PARSE_IS_SYSTEM_DIR
2259                    | PackageParser.PARSE_TRUSTED_OVERLAY, scanFlags | SCAN_TRUSTED_OVERLAY, 0);
2260
2261            // Find base frameworks (resource packages without code).
2262            scanDirTracedLI(frameworkDir, mDefParseFlags
2263                    | PackageParser.PARSE_IS_SYSTEM
2264                    | PackageParser.PARSE_IS_SYSTEM_DIR
2265                    | PackageParser.PARSE_IS_PRIVILEGED,
2266                    scanFlags | SCAN_NO_DEX, 0);
2267
2268            // Collected privileged system packages.
2269            final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
2270            scanDirTracedLI(privilegedAppDir, mDefParseFlags
2271                    | PackageParser.PARSE_IS_SYSTEM
2272                    | PackageParser.PARSE_IS_SYSTEM_DIR
2273                    | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0);
2274
2275            // Collect ordinary system packages.
2276            final File systemAppDir = new File(Environment.getRootDirectory(), "app");
2277            scanDirTracedLI(systemAppDir, mDefParseFlags
2278                    | PackageParser.PARSE_IS_SYSTEM
2279                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2280
2281            // Collect all vendor packages.
2282            File vendorAppDir = new File("/vendor/app");
2283            try {
2284                vendorAppDir = vendorAppDir.getCanonicalFile();
2285            } catch (IOException e) {
2286                // failed to look up canonical path, continue with original one
2287            }
2288            scanDirTracedLI(vendorAppDir, mDefParseFlags
2289                    | PackageParser.PARSE_IS_SYSTEM
2290                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2291
2292            // Collect all OEM packages.
2293            final File oemAppDir = new File(Environment.getOemDirectory(), "app");
2294            scanDirTracedLI(oemAppDir, mDefParseFlags
2295                    | PackageParser.PARSE_IS_SYSTEM
2296                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2297
2298            // Prune any system packages that no longer exist.
2299            final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>();
2300            if (!mOnlyCore) {
2301                Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
2302                while (psit.hasNext()) {
2303                    PackageSetting ps = psit.next();
2304
2305                    /*
2306                     * If this is not a system app, it can't be a
2307                     * disable system app.
2308                     */
2309                    if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
2310                        continue;
2311                    }
2312
2313                    /*
2314                     * If the package is scanned, it's not erased.
2315                     */
2316                    final PackageParser.Package scannedPkg = mPackages.get(ps.name);
2317                    if (scannedPkg != null) {
2318                        /*
2319                         * If the system app is both scanned and in the
2320                         * disabled packages list, then it must have been
2321                         * added via OTA. Remove it from the currently
2322                         * scanned package so the previously user-installed
2323                         * application can be scanned.
2324                         */
2325                        if (mSettings.isDisabledSystemPackageLPr(ps.name)) {
2326                            logCriticalInfo(Log.WARN, "Expecting better updated system app for "
2327                                    + ps.name + "; removing system app.  Last known codePath="
2328                                    + ps.codePathString + ", installStatus=" + ps.installStatus
2329                                    + ", versionCode=" + ps.versionCode + "; scanned versionCode="
2330                                    + scannedPkg.mVersionCode);
2331                            removePackageLI(scannedPkg, true);
2332                            mExpectingBetter.put(ps.name, ps.codePath);
2333                        }
2334
2335                        continue;
2336                    }
2337
2338                    if (!mSettings.isDisabledSystemPackageLPr(ps.name)) {
2339                        psit.remove();
2340                        logCriticalInfo(Log.WARN, "System package " + ps.name
2341                                + " no longer exists; it's data will be wiped");
2342                        // Actual deletion of code and data will be handled by later
2343                        // reconciliation step
2344                    } else {
2345                        final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name);
2346                        if (disabledPs.codePath == null || !disabledPs.codePath.exists()) {
2347                            possiblyDeletedUpdatedSystemApps.add(ps.name);
2348                        }
2349                    }
2350                }
2351            }
2352
2353            //look for any incomplete package installations
2354            ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr();
2355            for (int i = 0; i < deletePkgsList.size(); i++) {
2356                // Actual deletion of code and data will be handled by later
2357                // reconciliation step
2358                final String packageName = deletePkgsList.get(i).name;
2359                logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + packageName);
2360                synchronized (mPackages) {
2361                    mSettings.removePackageLPw(packageName);
2362                }
2363            }
2364
2365            //delete tmp files
2366            deleteTempPackageFiles();
2367
2368            // Remove any shared userIDs that have no associated packages
2369            mSettings.pruneSharedUsersLPw();
2370
2371            if (!mOnlyCore) {
2372                EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
2373                        SystemClock.uptimeMillis());
2374                scanDirTracedLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0);
2375
2376                scanDirTracedLI(mDrmAppPrivateInstallDir, mDefParseFlags
2377                        | PackageParser.PARSE_FORWARD_LOCK,
2378                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2379
2380                scanDirLI(mEphemeralInstallDir, mDefParseFlags
2381                        | PackageParser.PARSE_IS_EPHEMERAL,
2382                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2383
2384                /**
2385                 * Remove disable package settings for any updated system
2386                 * apps that were removed via an OTA. If they're not a
2387                 * previously-updated app, remove them completely.
2388                 * Otherwise, just revoke their system-level permissions.
2389                 */
2390                for (String deletedAppName : possiblyDeletedUpdatedSystemApps) {
2391                    PackageParser.Package deletedPkg = mPackages.get(deletedAppName);
2392                    mSettings.removeDisabledSystemPackageLPw(deletedAppName);
2393
2394                    String msg;
2395                    if (deletedPkg == null) {
2396                        msg = "Updated system package " + deletedAppName
2397                                + " no longer exists; it's data will be wiped";
2398                        // Actual deletion of code and data will be handled by later
2399                        // reconciliation step
2400                    } else {
2401                        msg = "Updated system app + " + deletedAppName
2402                                + " no longer present; removing system privileges for "
2403                                + deletedAppName;
2404
2405                        deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM;
2406
2407                        PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName);
2408                        deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM;
2409                    }
2410                    logCriticalInfo(Log.WARN, msg);
2411                }
2412
2413                /**
2414                 * Make sure all system apps that we expected to appear on
2415                 * the userdata partition actually showed up. If they never
2416                 * appeared, crawl back and revive the system version.
2417                 */
2418                for (int i = 0; i < mExpectingBetter.size(); i++) {
2419                    final String packageName = mExpectingBetter.keyAt(i);
2420                    if (!mPackages.containsKey(packageName)) {
2421                        final File scanFile = mExpectingBetter.valueAt(i);
2422
2423                        logCriticalInfo(Log.WARN, "Expected better " + packageName
2424                                + " but never showed up; reverting to system");
2425
2426                        int reparseFlags = mDefParseFlags;
2427                        if (FileUtils.contains(privilegedAppDir, scanFile)) {
2428                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2429                                    | PackageParser.PARSE_IS_SYSTEM_DIR
2430                                    | PackageParser.PARSE_IS_PRIVILEGED;
2431                        } else if (FileUtils.contains(systemAppDir, scanFile)) {
2432                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2433                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2434                        } else if (FileUtils.contains(vendorAppDir, scanFile)) {
2435                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2436                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2437                        } else if (FileUtils.contains(oemAppDir, scanFile)) {
2438                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2439                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2440                        } else {
2441                            Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile);
2442                            continue;
2443                        }
2444
2445                        mSettings.enableSystemPackageLPw(packageName);
2446
2447                        try {
2448                            scanPackageTracedLI(scanFile, reparseFlags, scanFlags, 0, null);
2449                        } catch (PackageManagerException e) {
2450                            Slog.e(TAG, "Failed to parse original system package: "
2451                                    + e.getMessage());
2452                        }
2453                    }
2454                }
2455            }
2456            mExpectingBetter.clear();
2457
2458            // Resolve protected action filters. Only the setup wizard is allowed to
2459            // have a high priority filter for these actions.
2460            mSetupWizardPackage = getSetupWizardPackageName();
2461            if (mProtectedFilters.size() > 0) {
2462                if (DEBUG_FILTERS && mSetupWizardPackage == null) {
2463                    Slog.i(TAG, "No setup wizard;"
2464                        + " All protected intents capped to priority 0");
2465                }
2466                for (ActivityIntentInfo filter : mProtectedFilters) {
2467                    if (filter.activity.info.packageName.equals(mSetupWizardPackage)) {
2468                        if (DEBUG_FILTERS) {
2469                            Slog.i(TAG, "Found setup wizard;"
2470                                + " allow priority " + filter.getPriority() + ";"
2471                                + " package: " + filter.activity.info.packageName
2472                                + " activity: " + filter.activity.className
2473                                + " priority: " + filter.getPriority());
2474                        }
2475                        // skip setup wizard; allow it to keep the high priority filter
2476                        continue;
2477                    }
2478                    Slog.w(TAG, "Protected action; cap priority to 0;"
2479                            + " package: " + filter.activity.info.packageName
2480                            + " activity: " + filter.activity.className
2481                            + " origPrio: " + filter.getPriority());
2482                    filter.setPriority(0);
2483                }
2484            }
2485            mDeferProtectedFilters = false;
2486            mProtectedFilters.clear();
2487
2488            // Now that we know all of the shared libraries, update all clients to have
2489            // the correct library paths.
2490            updateAllSharedLibrariesLPw();
2491
2492            for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) {
2493                // NOTE: We ignore potential failures here during a system scan (like
2494                // the rest of the commands above) because there's precious little we
2495                // can do about it. A settings error is reported, though.
2496                adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */,
2497                        false /* boot complete */);
2498            }
2499
2500            // Now that we know all the packages we are keeping,
2501            // read and update their last usage times.
2502            mPackageUsage.read(mPackages);
2503            mCompilerStats.read();
2504
2505            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
2506                    SystemClock.uptimeMillis());
2507            Slog.i(TAG, "Time to scan packages: "
2508                    + ((SystemClock.uptimeMillis()-startTime)/1000f)
2509                    + " seconds");
2510
2511            // If the platform SDK has changed since the last time we booted,
2512            // we need to re-grant app permission to catch any new ones that
2513            // appear.  This is really a hack, and means that apps can in some
2514            // cases get permissions that the user didn't initially explicitly
2515            // allow...  it would be nice to have some better way to handle
2516            // this situation.
2517            int updateFlags = UPDATE_PERMISSIONS_ALL;
2518            if (ver.sdkVersion != mSdkVersion) {
2519                Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to "
2520                        + mSdkVersion + "; regranting permissions for internal storage");
2521                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
2522            }
2523            updatePermissionsLPw(null, null, StorageManager.UUID_PRIVATE_INTERNAL, updateFlags);
2524            ver.sdkVersion = mSdkVersion;
2525
2526            // If this is the first boot or an update from pre-M, and it is a normal
2527            // boot, then we need to initialize the default preferred apps across
2528            // all defined users.
2529            if (!onlyCore && (mPromoteSystemApps || mFirstBoot)) {
2530                for (UserInfo user : sUserManager.getUsers(true)) {
2531                    mSettings.applyDefaultPreferredAppsLPw(this, user.id);
2532                    applyFactoryDefaultBrowserLPw(user.id);
2533                    primeDomainVerificationsLPw(user.id);
2534                }
2535            }
2536
2537            // Prepare storage for system user really early during boot,
2538            // since core system apps like SettingsProvider and SystemUI
2539            // can't wait for user to start
2540            final int storageFlags;
2541            if (StorageManager.isFileEncryptedNativeOrEmulated()) {
2542                storageFlags = StorageManager.FLAG_STORAGE_DE;
2543            } else {
2544                storageFlags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
2545            }
2546            reconcileAppsDataLI(StorageManager.UUID_PRIVATE_INTERNAL, UserHandle.USER_SYSTEM,
2547                    storageFlags);
2548
2549            // If this is first boot after an OTA, and a normal boot, then
2550            // we need to clear code cache directories.
2551            // Note that we do *not* clear the application profiles. These remain valid
2552            // across OTAs and are used to drive profile verification (post OTA) and
2553            // profile compilation (without waiting to collect a fresh set of profiles).
2554            if (mIsUpgrade && !onlyCore) {
2555                Slog.i(TAG, "Build fingerprint changed; clearing code caches");
2556                for (int i = 0; i < mSettings.mPackages.size(); i++) {
2557                    final PackageSetting ps = mSettings.mPackages.valueAt(i);
2558                    if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) {
2559                        // No apps are running this early, so no need to freeze
2560                        clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
2561                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
2562                                        | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
2563                    }
2564                }
2565                ver.fingerprint = Build.FINGERPRINT;
2566            }
2567
2568            checkDefaultBrowser();
2569
2570            // clear only after permissions and other defaults have been updated
2571            mExistingSystemPackages.clear();
2572            mPromoteSystemApps = false;
2573
2574            // All the changes are done during package scanning.
2575            ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION;
2576
2577            // can downgrade to reader
2578            mSettings.writeLPr();
2579
2580            // Perform dexopt on all apps that mark themselves as coreApps. We do this pretty
2581            // early on (before the package manager declares itself as early) because other
2582            // components in the system server might ask for package contexts for these apps.
2583            //
2584            // Note that "onlyCore" in this context means the system is encrypted or encrypting
2585            // (i.e, that the data partition is unavailable).
2586            if ((isFirstBoot() || isUpgrade() || VMRuntime.didPruneDalvikCache()) && !onlyCore) {
2587                long start = System.nanoTime();
2588                List<PackageParser.Package> coreApps = new ArrayList<>();
2589                for (PackageParser.Package pkg : mPackages.values()) {
2590                    if (pkg.coreApp) {
2591                        coreApps.add(pkg);
2592                    }
2593                }
2594
2595                int[] stats = performDexOptUpgrade(coreApps, false,
2596                        getCompilerFilterForReason(REASON_CORE_APP));
2597
2598                final int elapsedTimeSeconds =
2599                        (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - start);
2600                MetricsLogger.histogram(mContext, "opt_coreapps_time_s", elapsedTimeSeconds);
2601
2602                if (DEBUG_DEXOPT) {
2603                    Slog.i(TAG, "Dex-opt core apps took : " + elapsedTimeSeconds + " seconds (" +
2604                            stats[0] + ", " + stats[1] + ", " + stats[2] + ")");
2605                }
2606
2607
2608                // TODO: Should we log these stats to tron too ?
2609                // MetricsLogger.histogram(mContext, "opt_coreapps_num_dexopted", stats[0]);
2610                // MetricsLogger.histogram(mContext, "opt_coreapps_num_skipped", stats[1]);
2611                // MetricsLogger.histogram(mContext, "opt_coreapps_num_failed", stats[2]);
2612                // MetricsLogger.histogram(mContext, "opt_coreapps_num_total", coreApps.size());
2613            }
2614
2615            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
2616                    SystemClock.uptimeMillis());
2617
2618            if (!mOnlyCore) {
2619                mRequiredVerifierPackage = getRequiredButNotReallyRequiredVerifierLPr();
2620                mRequiredInstallerPackage = getRequiredInstallerLPr();
2621                mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr();
2622                mIntentFilterVerifier = new IntentVerifierProxy(mContext,
2623                        mIntentFilterVerifierComponent);
2624                mServicesSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
2625                        PackageManager.SYSTEM_SHARED_LIBRARY_SERVICES);
2626                mSharedSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
2627                        PackageManager.SYSTEM_SHARED_LIBRARY_SHARED);
2628            } else {
2629                mRequiredVerifierPackage = null;
2630                mRequiredInstallerPackage = null;
2631                mIntentFilterVerifierComponent = null;
2632                mIntentFilterVerifier = null;
2633                mServicesSystemSharedLibraryPackageName = null;
2634                mSharedSystemSharedLibraryPackageName = null;
2635            }
2636
2637            mInstallerService = new PackageInstallerService(context, this);
2638
2639            final ComponentName ephemeralResolverComponent = getEphemeralResolverLPr();
2640            final ComponentName ephemeralInstallerComponent = getEphemeralInstallerLPr();
2641            // both the installer and resolver must be present to enable ephemeral
2642            if (ephemeralInstallerComponent != null && ephemeralResolverComponent != null) {
2643                if (DEBUG_EPHEMERAL) {
2644                    Slog.i(TAG, "Ephemeral activated; resolver: " + ephemeralResolverComponent
2645                            + " installer:" + ephemeralInstallerComponent);
2646                }
2647                mEphemeralResolverComponent = ephemeralResolverComponent;
2648                mEphemeralInstallerComponent = ephemeralInstallerComponent;
2649                setUpEphemeralInstallerActivityLP(mEphemeralInstallerComponent);
2650                mEphemeralResolverConnection =
2651                        new EphemeralResolverConnection(mContext, mEphemeralResolverComponent);
2652            } else {
2653                if (DEBUG_EPHEMERAL) {
2654                    final String missingComponent =
2655                            (ephemeralResolverComponent == null)
2656                            ? (ephemeralInstallerComponent == null)
2657                                    ? "resolver and installer"
2658                                    : "resolver"
2659                            : "installer";
2660                    Slog.i(TAG, "Ephemeral deactivated; missing " + missingComponent);
2661                }
2662                mEphemeralResolverComponent = null;
2663                mEphemeralInstallerComponent = null;
2664                mEphemeralResolverConnection = null;
2665            }
2666
2667            mEphemeralApplicationRegistry = new EphemeralApplicationRegistry(this);
2668        } // synchronized (mPackages)
2669        } // synchronized (mInstallLock)
2670
2671        // Now after opening every single application zip, make sure they
2672        // are all flushed.  Not really needed, but keeps things nice and
2673        // tidy.
2674        Runtime.getRuntime().gc();
2675
2676        // The initial scanning above does many calls into installd while
2677        // holding the mPackages lock, but we're mostly interested in yelling
2678        // once we have a booted system.
2679        mInstaller.setWarnIfHeld(mPackages);
2680
2681        // Expose private service for system components to use.
2682        LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl());
2683    }
2684
2685    @Override
2686    public boolean isFirstBoot() {
2687        return mFirstBoot;
2688    }
2689
2690    @Override
2691    public boolean isOnlyCoreApps() {
2692        return mOnlyCore;
2693    }
2694
2695    @Override
2696    public boolean isUpgrade() {
2697        return mIsUpgrade;
2698    }
2699
2700    private @Nullable String getRequiredButNotReallyRequiredVerifierLPr() {
2701        final Intent intent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
2702
2703        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
2704                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
2705                UserHandle.USER_SYSTEM);
2706        if (matches.size() == 1) {
2707            return matches.get(0).getComponentInfo().packageName;
2708        } else {
2709            Log.e(TAG, "There should probably be exactly one verifier; found " + matches);
2710            return null;
2711        }
2712    }
2713
2714    private @NonNull String getRequiredSharedLibraryLPr(String libraryName) {
2715        synchronized (mPackages) {
2716            SharedLibraryEntry libraryEntry = mSharedLibraries.get(libraryName);
2717            if (libraryEntry == null) {
2718                throw new IllegalStateException("Missing required shared library:" + libraryName);
2719            }
2720            return libraryEntry.apk;
2721        }
2722    }
2723
2724    private @NonNull String getRequiredInstallerLPr() {
2725        final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
2726        intent.addCategory(Intent.CATEGORY_DEFAULT);
2727        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
2728
2729        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
2730                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
2731                UserHandle.USER_SYSTEM);
2732        if (matches.size() == 1) {
2733            ResolveInfo resolveInfo = matches.get(0);
2734            if (!resolveInfo.activityInfo.applicationInfo.isPrivilegedApp()) {
2735                throw new RuntimeException("The installer must be a privileged app");
2736            }
2737            return matches.get(0).getComponentInfo().packageName;
2738        } else {
2739            throw new RuntimeException("There must be exactly one installer; found " + matches);
2740        }
2741    }
2742
2743    private @NonNull ComponentName getIntentFilterVerifierComponentNameLPr() {
2744        final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
2745
2746        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
2747                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
2748                UserHandle.USER_SYSTEM);
2749        ResolveInfo best = null;
2750        final int N = matches.size();
2751        for (int i = 0; i < N; i++) {
2752            final ResolveInfo cur = matches.get(i);
2753            final String packageName = cur.getComponentInfo().packageName;
2754            if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
2755                    packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) {
2756                continue;
2757            }
2758
2759            if (best == null || cur.priority > best.priority) {
2760                best = cur;
2761            }
2762        }
2763
2764        if (best != null) {
2765            return best.getComponentInfo().getComponentName();
2766        } else {
2767            throw new RuntimeException("There must be at least one intent filter verifier");
2768        }
2769    }
2770
2771    private @Nullable ComponentName getEphemeralResolverLPr() {
2772        final String[] packageArray =
2773                mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage);
2774        if (packageArray.length == 0) {
2775            if (DEBUG_EPHEMERAL) {
2776                Slog.d(TAG, "Ephemeral resolver NOT found; empty package list");
2777            }
2778            return null;
2779        }
2780
2781        final Intent resolverIntent = new Intent(Intent.ACTION_RESOLVE_EPHEMERAL_PACKAGE);
2782        final List<ResolveInfo> resolvers = queryIntentServicesInternal(resolverIntent, null,
2783                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
2784                UserHandle.USER_SYSTEM);
2785
2786        final int N = resolvers.size();
2787        if (N == 0) {
2788            if (DEBUG_EPHEMERAL) {
2789                Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters");
2790            }
2791            return null;
2792        }
2793
2794        final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray));
2795        for (int i = 0; i < N; i++) {
2796            final ResolveInfo info = resolvers.get(i);
2797
2798            if (info.serviceInfo == null) {
2799                continue;
2800            }
2801
2802            final String packageName = info.serviceInfo.packageName;
2803            if (!possiblePackages.contains(packageName)) {
2804                if (DEBUG_EPHEMERAL) {
2805                    Slog.d(TAG, "Ephemeral resolver not in allowed package list;"
2806                            + " pkg: " + packageName + ", info:" + info);
2807                }
2808                continue;
2809            }
2810
2811            if (DEBUG_EPHEMERAL) {
2812                Slog.v(TAG, "Ephemeral resolver found;"
2813                        + " pkg: " + packageName + ", info:" + info);
2814            }
2815            return new ComponentName(packageName, info.serviceInfo.name);
2816        }
2817        if (DEBUG_EPHEMERAL) {
2818            Slog.v(TAG, "Ephemeral resolver NOT found");
2819        }
2820        return null;
2821    }
2822
2823    private @Nullable ComponentName getEphemeralInstallerLPr() {
2824        final Intent intent = new Intent(Intent.ACTION_INSTALL_EPHEMERAL_PACKAGE);
2825        intent.addCategory(Intent.CATEGORY_DEFAULT);
2826        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
2827
2828        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
2829                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
2830                UserHandle.USER_SYSTEM);
2831        if (matches.size() == 0) {
2832            return null;
2833        } else if (matches.size() == 1) {
2834            return matches.get(0).getComponentInfo().getComponentName();
2835        } else {
2836            throw new RuntimeException(
2837                    "There must be at most one ephemeral installer; found " + matches);
2838        }
2839    }
2840
2841    private void primeDomainVerificationsLPw(int userId) {
2842        if (DEBUG_DOMAIN_VERIFICATION) {
2843            Slog.d(TAG, "Priming domain verifications in user " + userId);
2844        }
2845
2846        SystemConfig systemConfig = SystemConfig.getInstance();
2847        ArraySet<String> packages = systemConfig.getLinkedApps();
2848        ArraySet<String> domains = new ArraySet<String>();
2849
2850        for (String packageName : packages) {
2851            PackageParser.Package pkg = mPackages.get(packageName);
2852            if (pkg != null) {
2853                if (!pkg.isSystemApp()) {
2854                    Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>");
2855                    continue;
2856                }
2857
2858                domains.clear();
2859                for (PackageParser.Activity a : pkg.activities) {
2860                    for (ActivityIntentInfo filter : a.intents) {
2861                        if (hasValidDomains(filter)) {
2862                            domains.addAll(filter.getHostsList());
2863                        }
2864                    }
2865                }
2866
2867                if (domains.size() > 0) {
2868                    if (DEBUG_DOMAIN_VERIFICATION) {
2869                        Slog.v(TAG, "      + " + packageName);
2870                    }
2871                    // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual
2872                    // state w.r.t. the formal app-linkage "no verification attempted" state;
2873                    // and then 'always' in the per-user state actually used for intent resolution.
2874                    final IntentFilterVerificationInfo ivi;
2875                    ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName,
2876                            new ArrayList<String>(domains));
2877                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED);
2878                    mSettings.updateIntentFilterVerificationStatusLPw(packageName,
2879                            INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId);
2880                } else {
2881                    Slog.w(TAG, "Sysconfig <app-link> package '" + packageName
2882                            + "' does not handle web links");
2883                }
2884            } else {
2885                Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>");
2886            }
2887        }
2888
2889        scheduleWritePackageRestrictionsLocked(userId);
2890        scheduleWriteSettingsLocked();
2891    }
2892
2893    private void applyFactoryDefaultBrowserLPw(int userId) {
2894        // The default browser app's package name is stored in a string resource,
2895        // with a product-specific overlay used for vendor customization.
2896        String browserPkg = mContext.getResources().getString(
2897                com.android.internal.R.string.default_browser);
2898        if (!TextUtils.isEmpty(browserPkg)) {
2899            // non-empty string => required to be a known package
2900            PackageSetting ps = mSettings.mPackages.get(browserPkg);
2901            if (ps == null) {
2902                Slog.e(TAG, "Product default browser app does not exist: " + browserPkg);
2903                browserPkg = null;
2904            } else {
2905                mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
2906            }
2907        }
2908
2909        // Nothing valid explicitly set? Make the factory-installed browser the explicit
2910        // default.  If there's more than one, just leave everything alone.
2911        if (browserPkg == null) {
2912            calculateDefaultBrowserLPw(userId);
2913        }
2914    }
2915
2916    private void calculateDefaultBrowserLPw(int userId) {
2917        List<String> allBrowsers = resolveAllBrowserApps(userId);
2918        final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null;
2919        mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
2920    }
2921
2922    private List<String> resolveAllBrowserApps(int userId) {
2923        // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set
2924        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
2925                PackageManager.MATCH_ALL, userId);
2926
2927        final int count = list.size();
2928        List<String> result = new ArrayList<String>(count);
2929        for (int i=0; i<count; i++) {
2930            ResolveInfo info = list.get(i);
2931            if (info.activityInfo == null
2932                    || !info.handleAllWebDataURI
2933                    || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0
2934                    || result.contains(info.activityInfo.packageName)) {
2935                continue;
2936            }
2937            result.add(info.activityInfo.packageName);
2938        }
2939
2940        return result;
2941    }
2942
2943    private boolean packageIsBrowser(String packageName, int userId) {
2944        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
2945                PackageManager.MATCH_ALL, userId);
2946        final int N = list.size();
2947        for (int i = 0; i < N; i++) {
2948            ResolveInfo info = list.get(i);
2949            if (packageName.equals(info.activityInfo.packageName)) {
2950                return true;
2951            }
2952        }
2953        return false;
2954    }
2955
2956    private void checkDefaultBrowser() {
2957        final int myUserId = UserHandle.myUserId();
2958        final String packageName = getDefaultBrowserPackageName(myUserId);
2959        if (packageName != null) {
2960            PackageInfo info = getPackageInfo(packageName, 0, myUserId);
2961            if (info == null) {
2962                Slog.w(TAG, "Default browser no longer installed: " + packageName);
2963                synchronized (mPackages) {
2964                    applyFactoryDefaultBrowserLPw(myUserId);    // leaves ambiguous when > 1
2965                }
2966            }
2967        }
2968    }
2969
2970    @Override
2971    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
2972            throws RemoteException {
2973        try {
2974            return super.onTransact(code, data, reply, flags);
2975        } catch (RuntimeException e) {
2976            if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
2977                Slog.wtf(TAG, "Package Manager Crash", e);
2978            }
2979            throw e;
2980        }
2981    }
2982
2983    static int[] appendInts(int[] cur, int[] add) {
2984        if (add == null) return cur;
2985        if (cur == null) return add;
2986        final int N = add.length;
2987        for (int i=0; i<N; i++) {
2988            cur = appendInt(cur, add[i]);
2989        }
2990        return cur;
2991    }
2992
2993    private PackageInfo generatePackageInfo(PackageSetting ps, int flags, int userId) {
2994        if (!sUserManager.exists(userId)) return null;
2995        if (ps == null) {
2996            return null;
2997        }
2998        final PackageParser.Package p = ps.pkg;
2999        if (p == null) {
3000            return null;
3001        }
3002
3003        final PermissionsState permissionsState = ps.getPermissionsState();
3004
3005        final int[] gids = permissionsState.computeGids(userId);
3006        final Set<String> permissions = permissionsState.getPermissions(userId);
3007        final PackageUserState state = ps.readUserState(userId);
3008
3009        return PackageParser.generatePackageInfo(p, gids, flags,
3010                ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId);
3011    }
3012
3013    @Override
3014    public void checkPackageStartable(String packageName, int userId) {
3015        final boolean userKeyUnlocked = StorageManager.isUserKeyUnlocked(userId);
3016
3017        synchronized (mPackages) {
3018            final PackageSetting ps = mSettings.mPackages.get(packageName);
3019            if (ps == null) {
3020                throw new SecurityException("Package " + packageName + " was not found!");
3021            }
3022
3023            if (!ps.getInstalled(userId)) {
3024                throw new SecurityException(
3025                        "Package " + packageName + " was not installed for user " + userId + "!");
3026            }
3027
3028            if (mSafeMode && !ps.isSystem()) {
3029                throw new SecurityException("Package " + packageName + " not a system app!");
3030            }
3031
3032            if (mFrozenPackages.contains(packageName)) {
3033                throw new SecurityException("Package " + packageName + " is currently frozen!");
3034            }
3035
3036            if (!userKeyUnlocked && !(ps.pkg.applicationInfo.isDirectBootAware()
3037                    || ps.pkg.applicationInfo.isPartiallyDirectBootAware())) {
3038                throw new SecurityException("Package " + packageName + " is not encryption aware!");
3039            }
3040        }
3041    }
3042
3043    @Override
3044    public boolean isPackageAvailable(String packageName, int userId) {
3045        if (!sUserManager.exists(userId)) return false;
3046        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3047                false /* requireFullPermission */, false /* checkShell */, "is package available");
3048        synchronized (mPackages) {
3049            PackageParser.Package p = mPackages.get(packageName);
3050            if (p != null) {
3051                final PackageSetting ps = (PackageSetting) p.mExtras;
3052                if (ps != null) {
3053                    final PackageUserState state = ps.readUserState(userId);
3054                    if (state != null) {
3055                        return PackageParser.isAvailable(state);
3056                    }
3057                }
3058            }
3059        }
3060        return false;
3061    }
3062
3063    @Override
3064    public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
3065        if (!sUserManager.exists(userId)) return null;
3066        flags = updateFlagsForPackage(flags, userId, packageName);
3067        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3068                false /* requireFullPermission */, false /* checkShell */, "get package info");
3069        // reader
3070        synchronized (mPackages) {
3071            final boolean matchFactoryOnly = (flags & MATCH_FACTORY_ONLY) != 0;
3072            PackageParser.Package p = null;
3073            if (matchFactoryOnly) {
3074                final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName);
3075                if (ps != null) {
3076                    return generatePackageInfo(ps, flags, userId);
3077                }
3078            }
3079            if (p == null) {
3080                p = mPackages.get(packageName);
3081                if (matchFactoryOnly && p != null && !isSystemApp(p)) {
3082                    return null;
3083                }
3084            }
3085            if (DEBUG_PACKAGE_INFO)
3086                Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
3087            if (p != null) {
3088                return generatePackageInfo((PackageSetting)p.mExtras, flags, userId);
3089            }
3090            if (!matchFactoryOnly && (flags & MATCH_UNINSTALLED_PACKAGES) != 0) {
3091                final PackageSetting ps = mSettings.mPackages.get(packageName);
3092                return generatePackageInfo(ps, flags, userId);
3093            }
3094        }
3095        return null;
3096    }
3097
3098    @Override
3099    public String[] currentToCanonicalPackageNames(String[] names) {
3100        String[] out = new String[names.length];
3101        // reader
3102        synchronized (mPackages) {
3103            for (int i=names.length-1; i>=0; i--) {
3104                PackageSetting ps = mSettings.mPackages.get(names[i]);
3105                out[i] = ps != null && ps.realName != null ? ps.realName : names[i];
3106            }
3107        }
3108        return out;
3109    }
3110
3111    @Override
3112    public String[] canonicalToCurrentPackageNames(String[] names) {
3113        String[] out = new String[names.length];
3114        // reader
3115        synchronized (mPackages) {
3116            for (int i=names.length-1; i>=0; i--) {
3117                String cur = mSettings.mRenamedPackages.get(names[i]);
3118                out[i] = cur != null ? cur : names[i];
3119            }
3120        }
3121        return out;
3122    }
3123
3124    @Override
3125    public int getPackageUid(String packageName, int flags, int userId) {
3126        if (!sUserManager.exists(userId)) return -1;
3127        flags = updateFlagsForPackage(flags, userId, packageName);
3128        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3129                false /* requireFullPermission */, false /* checkShell */, "get package uid");
3130
3131        // reader
3132        synchronized (mPackages) {
3133            final PackageParser.Package p = mPackages.get(packageName);
3134            if (p != null && p.isMatch(flags)) {
3135                return UserHandle.getUid(userId, p.applicationInfo.uid);
3136            }
3137            if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) {
3138                final PackageSetting ps = mSettings.mPackages.get(packageName);
3139                if (ps != null && ps.isMatch(flags)) {
3140                    return UserHandle.getUid(userId, ps.appId);
3141                }
3142            }
3143        }
3144
3145        return -1;
3146    }
3147
3148    @Override
3149    public int[] getPackageGids(String packageName, int flags, int userId) {
3150        if (!sUserManager.exists(userId)) return null;
3151        flags = updateFlagsForPackage(flags, userId, packageName);
3152        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3153                false /* requireFullPermission */, false /* checkShell */,
3154                "getPackageGids");
3155
3156        // reader
3157        synchronized (mPackages) {
3158            final PackageParser.Package p = mPackages.get(packageName);
3159            if (p != null && p.isMatch(flags)) {
3160                PackageSetting ps = (PackageSetting) p.mExtras;
3161                return ps.getPermissionsState().computeGids(userId);
3162            }
3163            if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) {
3164                final PackageSetting ps = mSettings.mPackages.get(packageName);
3165                if (ps != null && ps.isMatch(flags)) {
3166                    return ps.getPermissionsState().computeGids(userId);
3167                }
3168            }
3169        }
3170
3171        return null;
3172    }
3173
3174    static PermissionInfo generatePermissionInfo(BasePermission bp, int flags) {
3175        if (bp.perm != null) {
3176            return PackageParser.generatePermissionInfo(bp.perm, flags);
3177        }
3178        PermissionInfo pi = new PermissionInfo();
3179        pi.name = bp.name;
3180        pi.packageName = bp.sourcePackage;
3181        pi.nonLocalizedLabel = bp.name;
3182        pi.protectionLevel = bp.protectionLevel;
3183        return pi;
3184    }
3185
3186    @Override
3187    public PermissionInfo getPermissionInfo(String name, int flags) {
3188        // reader
3189        synchronized (mPackages) {
3190            final BasePermission p = mSettings.mPermissions.get(name);
3191            if (p != null) {
3192                return generatePermissionInfo(p, flags);
3193            }
3194            return null;
3195        }
3196    }
3197
3198    @Override
3199    public @Nullable ParceledListSlice<PermissionInfo> queryPermissionsByGroup(String group,
3200            int flags) {
3201        // reader
3202        synchronized (mPackages) {
3203            if (group != null && !mPermissionGroups.containsKey(group)) {
3204                // This is thrown as NameNotFoundException
3205                return null;
3206            }
3207
3208            ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
3209            for (BasePermission p : mSettings.mPermissions.values()) {
3210                if (group == null) {
3211                    if (p.perm == null || p.perm.info.group == null) {
3212                        out.add(generatePermissionInfo(p, flags));
3213                    }
3214                } else {
3215                    if (p.perm != null && group.equals(p.perm.info.group)) {
3216                        out.add(PackageParser.generatePermissionInfo(p.perm, flags));
3217                    }
3218                }
3219            }
3220            return new ParceledListSlice<>(out);
3221        }
3222    }
3223
3224    @Override
3225    public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
3226        // reader
3227        synchronized (mPackages) {
3228            return PackageParser.generatePermissionGroupInfo(
3229                    mPermissionGroups.get(name), flags);
3230        }
3231    }
3232
3233    @Override
3234    public @NonNull ParceledListSlice<PermissionGroupInfo> getAllPermissionGroups(int flags) {
3235        // reader
3236        synchronized (mPackages) {
3237            final int N = mPermissionGroups.size();
3238            ArrayList<PermissionGroupInfo> out
3239                    = new ArrayList<PermissionGroupInfo>(N);
3240            for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
3241                out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
3242            }
3243            return new ParceledListSlice<>(out);
3244        }
3245    }
3246
3247    private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
3248            int userId) {
3249        if (!sUserManager.exists(userId)) return null;
3250        PackageSetting ps = mSettings.mPackages.get(packageName);
3251        if (ps != null) {
3252            if (ps.pkg == null) {
3253                final PackageInfo pInfo = generatePackageInfo(ps, flags, userId);
3254                if (pInfo != null) {
3255                    return pInfo.applicationInfo;
3256                }
3257                return null;
3258            }
3259            return PackageParser.generateApplicationInfo(ps.pkg, flags,
3260                    ps.readUserState(userId), userId);
3261        }
3262        return null;
3263    }
3264
3265    @Override
3266    public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
3267        if (!sUserManager.exists(userId)) return null;
3268        flags = updateFlagsForApplication(flags, userId, packageName);
3269        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3270                false /* requireFullPermission */, false /* checkShell */, "get application info");
3271        // writer
3272        synchronized (mPackages) {
3273            PackageParser.Package p = mPackages.get(packageName);
3274            if (DEBUG_PACKAGE_INFO) Log.v(
3275                    TAG, "getApplicationInfo " + packageName
3276                    + ": " + p);
3277            if (p != null) {
3278                PackageSetting ps = mSettings.mPackages.get(packageName);
3279                if (ps == null) return null;
3280                // Note: isEnabledLP() does not apply here - always return info
3281                return PackageParser.generateApplicationInfo(
3282                        p, flags, ps.readUserState(userId), userId);
3283            }
3284            if ("android".equals(packageName)||"system".equals(packageName)) {
3285                return mAndroidApplication;
3286            }
3287            if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) {
3288                return generateApplicationInfoFromSettingsLPw(packageName, flags, userId);
3289            }
3290        }
3291        return null;
3292    }
3293
3294    @Override
3295    public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize,
3296            final IPackageDataObserver observer) {
3297        mContext.enforceCallingOrSelfPermission(
3298                android.Manifest.permission.CLEAR_APP_CACHE, null);
3299        // Queue up an async operation since clearing cache may take a little while.
3300        mHandler.post(new Runnable() {
3301            public void run() {
3302                mHandler.removeCallbacks(this);
3303                boolean success = true;
3304                synchronized (mInstallLock) {
3305                    try {
3306                        mInstaller.freeCache(volumeUuid, freeStorageSize);
3307                    } catch (InstallerException e) {
3308                        Slog.w(TAG, "Couldn't clear application caches: " + e);
3309                        success = false;
3310                    }
3311                }
3312                if (observer != null) {
3313                    try {
3314                        observer.onRemoveCompleted(null, success);
3315                    } catch (RemoteException e) {
3316                        Slog.w(TAG, "RemoveException when invoking call back");
3317                    }
3318                }
3319            }
3320        });
3321    }
3322
3323    @Override
3324    public void freeStorage(final String volumeUuid, final long freeStorageSize,
3325            final IntentSender pi) {
3326        mContext.enforceCallingOrSelfPermission(
3327                android.Manifest.permission.CLEAR_APP_CACHE, null);
3328        // Queue up an async operation since clearing cache may take a little while.
3329        mHandler.post(new Runnable() {
3330            public void run() {
3331                mHandler.removeCallbacks(this);
3332                boolean success = true;
3333                synchronized (mInstallLock) {
3334                    try {
3335                        mInstaller.freeCache(volumeUuid, freeStorageSize);
3336                    } catch (InstallerException e) {
3337                        Slog.w(TAG, "Couldn't clear application caches: " + e);
3338                        success = false;
3339                    }
3340                }
3341                if(pi != null) {
3342                    try {
3343                        // Callback via pending intent
3344                        int code = success ? 1 : 0;
3345                        pi.sendIntent(null, code, null,
3346                                null, null);
3347                    } catch (SendIntentException e1) {
3348                        Slog.i(TAG, "Failed to send pending intent");
3349                    }
3350                }
3351            }
3352        });
3353    }
3354
3355    void freeStorage(String volumeUuid, long freeStorageSize) throws IOException {
3356        synchronized (mInstallLock) {
3357            try {
3358                mInstaller.freeCache(volumeUuid, freeStorageSize);
3359            } catch (InstallerException e) {
3360                throw new IOException("Failed to free enough space", e);
3361            }
3362        }
3363    }
3364
3365    /**
3366     * Update given flags based on encryption status of current user.
3367     */
3368    private int updateFlags(int flags, int userId) {
3369        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
3370                | PackageManager.MATCH_DIRECT_BOOT_AWARE)) != 0) {
3371            // Caller expressed an explicit opinion about what encryption
3372            // aware/unaware components they want to see, so fall through and
3373            // give them what they want
3374        } else {
3375            // Caller expressed no opinion, so match based on user state
3376            if (getUserManagerInternal().isUserUnlockingOrUnlocked(userId)) {
3377                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE;
3378            } else {
3379                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE;
3380            }
3381        }
3382        return flags;
3383    }
3384
3385    private UserManagerInternal getUserManagerInternal() {
3386        if (mUserManagerInternal == null) {
3387            mUserManagerInternal = LocalServices.getService(UserManagerInternal.class);
3388        }
3389        return mUserManagerInternal;
3390    }
3391
3392    /**
3393     * Update given flags when being used to request {@link PackageInfo}.
3394     */
3395    private int updateFlagsForPackage(int flags, int userId, Object cookie) {
3396        boolean triaged = true;
3397        if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS
3398                | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) {
3399            // Caller is asking for component details, so they'd better be
3400            // asking for specific encryption matching behavior, or be triaged
3401            if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
3402                    | PackageManager.MATCH_DIRECT_BOOT_AWARE
3403                    | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
3404                triaged = false;
3405            }
3406        }
3407        if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES
3408                | PackageManager.MATCH_SYSTEM_ONLY
3409                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
3410            triaged = false;
3411        }
3412        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
3413            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
3414                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
3415        }
3416        return updateFlags(flags, userId);
3417    }
3418
3419    /**
3420     * Update given flags when being used to request {@link ApplicationInfo}.
3421     */
3422    private int updateFlagsForApplication(int flags, int userId, Object cookie) {
3423        return updateFlagsForPackage(flags, userId, cookie);
3424    }
3425
3426    /**
3427     * Update given flags when being used to request {@link ComponentInfo}.
3428     */
3429    private int updateFlagsForComponent(int flags, int userId, Object cookie) {
3430        if (cookie instanceof Intent) {
3431            if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) {
3432                flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
3433            }
3434        }
3435
3436        boolean triaged = true;
3437        // Caller is asking for component details, so they'd better be
3438        // asking for specific encryption matching behavior, or be triaged
3439        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
3440                | PackageManager.MATCH_DIRECT_BOOT_AWARE
3441                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
3442            triaged = false;
3443        }
3444        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
3445            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
3446                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
3447        }
3448
3449        return updateFlags(flags, userId);
3450    }
3451
3452    /**
3453     * Update given flags when being used to request {@link ResolveInfo}.
3454     */
3455    int updateFlagsForResolve(int flags, int userId, Object cookie) {
3456        // Safe mode means we shouldn't match any third-party components
3457        if (mSafeMode) {
3458            flags |= PackageManager.MATCH_SYSTEM_ONLY;
3459        }
3460
3461        return updateFlagsForComponent(flags, userId, cookie);
3462    }
3463
3464    @Override
3465    public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
3466        if (!sUserManager.exists(userId)) return null;
3467        flags = updateFlagsForComponent(flags, userId, component);
3468        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3469                false /* requireFullPermission */, false /* checkShell */, "get activity info");
3470        synchronized (mPackages) {
3471            PackageParser.Activity a = mActivities.mActivities.get(component);
3472
3473            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
3474            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
3475                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3476                if (ps == null) return null;
3477                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
3478                        userId);
3479            }
3480            if (mResolveComponentName.equals(component)) {
3481                return PackageParser.generateActivityInfo(mResolveActivity, flags,
3482                        new PackageUserState(), userId);
3483            }
3484        }
3485        return null;
3486    }
3487
3488    @Override
3489    public boolean activitySupportsIntent(ComponentName component, Intent intent,
3490            String resolvedType) {
3491        synchronized (mPackages) {
3492            if (component.equals(mResolveComponentName)) {
3493                // The resolver supports EVERYTHING!
3494                return true;
3495            }
3496            PackageParser.Activity a = mActivities.mActivities.get(component);
3497            if (a == null) {
3498                return false;
3499            }
3500            for (int i=0; i<a.intents.size(); i++) {
3501                if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
3502                        intent.getData(), intent.getCategories(), TAG) >= 0) {
3503                    return true;
3504                }
3505            }
3506            return false;
3507        }
3508    }
3509
3510    @Override
3511    public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
3512        if (!sUserManager.exists(userId)) return null;
3513        flags = updateFlagsForComponent(flags, userId, component);
3514        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3515                false /* requireFullPermission */, false /* checkShell */, "get receiver info");
3516        synchronized (mPackages) {
3517            PackageParser.Activity a = mReceivers.mActivities.get(component);
3518            if (DEBUG_PACKAGE_INFO) Log.v(
3519                TAG, "getReceiverInfo " + component + ": " + a);
3520            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
3521                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3522                if (ps == null) return null;
3523                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
3524                        userId);
3525            }
3526        }
3527        return null;
3528    }
3529
3530    @Override
3531    public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
3532        if (!sUserManager.exists(userId)) return null;
3533        flags = updateFlagsForComponent(flags, userId, component);
3534        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3535                false /* requireFullPermission */, false /* checkShell */, "get service info");
3536        synchronized (mPackages) {
3537            PackageParser.Service s = mServices.mServices.get(component);
3538            if (DEBUG_PACKAGE_INFO) Log.v(
3539                TAG, "getServiceInfo " + component + ": " + s);
3540            if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) {
3541                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3542                if (ps == null) return null;
3543                return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId),
3544                        userId);
3545            }
3546        }
3547        return null;
3548    }
3549
3550    @Override
3551    public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
3552        if (!sUserManager.exists(userId)) return null;
3553        flags = updateFlagsForComponent(flags, userId, component);
3554        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3555                false /* requireFullPermission */, false /* checkShell */, "get provider info");
3556        synchronized (mPackages) {
3557            PackageParser.Provider p = mProviders.mProviders.get(component);
3558            if (DEBUG_PACKAGE_INFO) Log.v(
3559                TAG, "getProviderInfo " + component + ": " + p);
3560            if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
3561                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3562                if (ps == null) return null;
3563                return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId),
3564                        userId);
3565            }
3566        }
3567        return null;
3568    }
3569
3570    @Override
3571    public String[] getSystemSharedLibraryNames() {
3572        Set<String> libSet;
3573        synchronized (mPackages) {
3574            libSet = mSharedLibraries.keySet();
3575            int size = libSet.size();
3576            if (size > 0) {
3577                String[] libs = new String[size];
3578                libSet.toArray(libs);
3579                return libs;
3580            }
3581        }
3582        return null;
3583    }
3584
3585    @Override
3586    public @NonNull String getServicesSystemSharedLibraryPackageName() {
3587        synchronized (mPackages) {
3588            return mServicesSystemSharedLibraryPackageName;
3589        }
3590    }
3591
3592    @Override
3593    public @NonNull String getSharedSystemSharedLibraryPackageName() {
3594        synchronized (mPackages) {
3595            return mSharedSystemSharedLibraryPackageName;
3596        }
3597    }
3598
3599    @Override
3600    public @NonNull ParceledListSlice<FeatureInfo> getSystemAvailableFeatures() {
3601        synchronized (mPackages) {
3602            final ArrayList<FeatureInfo> res = new ArrayList<>(mAvailableFeatures.values());
3603
3604            final FeatureInfo fi = new FeatureInfo();
3605            fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
3606                    FeatureInfo.GL_ES_VERSION_UNDEFINED);
3607            res.add(fi);
3608
3609            return new ParceledListSlice<>(res);
3610        }
3611    }
3612
3613    @Override
3614    public boolean hasSystemFeature(String name, int version) {
3615        synchronized (mPackages) {
3616            final FeatureInfo feat = mAvailableFeatures.get(name);
3617            if (feat == null) {
3618                return false;
3619            } else {
3620                return feat.version >= version;
3621            }
3622        }
3623    }
3624
3625    @Override
3626    public int checkPermission(String permName, String pkgName, int userId) {
3627        if (!sUserManager.exists(userId)) {
3628            return PackageManager.PERMISSION_DENIED;
3629        }
3630
3631        synchronized (mPackages) {
3632            final PackageParser.Package p = mPackages.get(pkgName);
3633            if (p != null && p.mExtras != null) {
3634                final PackageSetting ps = (PackageSetting) p.mExtras;
3635                final PermissionsState permissionsState = ps.getPermissionsState();
3636                if (permissionsState.hasPermission(permName, userId)) {
3637                    return PackageManager.PERMISSION_GRANTED;
3638                }
3639                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
3640                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
3641                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
3642                    return PackageManager.PERMISSION_GRANTED;
3643                }
3644            }
3645        }
3646
3647        return PackageManager.PERMISSION_DENIED;
3648    }
3649
3650    @Override
3651    public int checkUidPermission(String permName, int uid) {
3652        final int userId = UserHandle.getUserId(uid);
3653
3654        if (!sUserManager.exists(userId)) {
3655            return PackageManager.PERMISSION_DENIED;
3656        }
3657
3658        synchronized (mPackages) {
3659            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
3660            if (obj != null) {
3661                final SettingBase ps = (SettingBase) obj;
3662                final PermissionsState permissionsState = ps.getPermissionsState();
3663                if (permissionsState.hasPermission(permName, userId)) {
3664                    return PackageManager.PERMISSION_GRANTED;
3665                }
3666                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
3667                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
3668                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
3669                    return PackageManager.PERMISSION_GRANTED;
3670                }
3671            } else {
3672                ArraySet<String> perms = mSystemPermissions.get(uid);
3673                if (perms != null) {
3674                    if (perms.contains(permName)) {
3675                        return PackageManager.PERMISSION_GRANTED;
3676                    }
3677                    if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms
3678                            .contains(Manifest.permission.ACCESS_FINE_LOCATION)) {
3679                        return PackageManager.PERMISSION_GRANTED;
3680                    }
3681                }
3682            }
3683        }
3684
3685        return PackageManager.PERMISSION_DENIED;
3686    }
3687
3688    @Override
3689    public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) {
3690        if (UserHandle.getCallingUserId() != userId) {
3691            mContext.enforceCallingPermission(
3692                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
3693                    "isPermissionRevokedByPolicy for user " + userId);
3694        }
3695
3696        if (checkPermission(permission, packageName, userId)
3697                == PackageManager.PERMISSION_GRANTED) {
3698            return false;
3699        }
3700
3701        final long identity = Binder.clearCallingIdentity();
3702        try {
3703            final int flags = getPermissionFlags(permission, packageName, userId);
3704            return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0;
3705        } finally {
3706            Binder.restoreCallingIdentity(identity);
3707        }
3708    }
3709
3710    @Override
3711    public String getPermissionControllerPackageName() {
3712        synchronized (mPackages) {
3713            return mRequiredInstallerPackage;
3714        }
3715    }
3716
3717    /**
3718     * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS
3719     * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller.
3720     * @param checkShell whether to prevent shell from access if there's a debugging restriction
3721     * @param message the message to log on security exception
3722     */
3723    void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission,
3724            boolean checkShell, String message) {
3725        if (userId < 0) {
3726            throw new IllegalArgumentException("Invalid userId " + userId);
3727        }
3728        if (checkShell) {
3729            enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId);
3730        }
3731        if (userId == UserHandle.getUserId(callingUid)) return;
3732        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
3733            if (requireFullPermission) {
3734                mContext.enforceCallingOrSelfPermission(
3735                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
3736            } else {
3737                try {
3738                    mContext.enforceCallingOrSelfPermission(
3739                            android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
3740                } catch (SecurityException se) {
3741                    mContext.enforceCallingOrSelfPermission(
3742                            android.Manifest.permission.INTERACT_ACROSS_USERS, message);
3743                }
3744            }
3745        }
3746    }
3747
3748    void enforceShellRestriction(String restriction, int callingUid, int userHandle) {
3749        if (callingUid == Process.SHELL_UID) {
3750            if (userHandle >= 0
3751                    && sUserManager.hasUserRestriction(restriction, userHandle)) {
3752                throw new SecurityException("Shell does not have permission to access user "
3753                        + userHandle);
3754            } else if (userHandle < 0) {
3755                Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t"
3756                        + Debug.getCallers(3));
3757            }
3758        }
3759    }
3760
3761    private BasePermission findPermissionTreeLP(String permName) {
3762        for(BasePermission bp : mSettings.mPermissionTrees.values()) {
3763            if (permName.startsWith(bp.name) &&
3764                    permName.length() > bp.name.length() &&
3765                    permName.charAt(bp.name.length()) == '.') {
3766                return bp;
3767            }
3768        }
3769        return null;
3770    }
3771
3772    private BasePermission checkPermissionTreeLP(String permName) {
3773        if (permName != null) {
3774            BasePermission bp = findPermissionTreeLP(permName);
3775            if (bp != null) {
3776                if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) {
3777                    return bp;
3778                }
3779                throw new SecurityException("Calling uid "
3780                        + Binder.getCallingUid()
3781                        + " is not allowed to add to permission tree "
3782                        + bp.name + " owned by uid " + bp.uid);
3783            }
3784        }
3785        throw new SecurityException("No permission tree found for " + permName);
3786    }
3787
3788    static boolean compareStrings(CharSequence s1, CharSequence s2) {
3789        if (s1 == null) {
3790            return s2 == null;
3791        }
3792        if (s2 == null) {
3793            return false;
3794        }
3795        if (s1.getClass() != s2.getClass()) {
3796            return false;
3797        }
3798        return s1.equals(s2);
3799    }
3800
3801    static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
3802        if (pi1.icon != pi2.icon) return false;
3803        if (pi1.logo != pi2.logo) return false;
3804        if (pi1.protectionLevel != pi2.protectionLevel) return false;
3805        if (!compareStrings(pi1.name, pi2.name)) return false;
3806        if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
3807        // We'll take care of setting this one.
3808        if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
3809        // These are not currently stored in settings.
3810        //if (!compareStrings(pi1.group, pi2.group)) return false;
3811        //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
3812        //if (pi1.labelRes != pi2.labelRes) return false;
3813        //if (pi1.descriptionRes != pi2.descriptionRes) return false;
3814        return true;
3815    }
3816
3817    int permissionInfoFootprint(PermissionInfo info) {
3818        int size = info.name.length();
3819        if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length();
3820        if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length();
3821        return size;
3822    }
3823
3824    int calculateCurrentPermissionFootprintLocked(BasePermission tree) {
3825        int size = 0;
3826        for (BasePermission perm : mSettings.mPermissions.values()) {
3827            if (perm.uid == tree.uid) {
3828                size += perm.name.length() + permissionInfoFootprint(perm.perm.info);
3829            }
3830        }
3831        return size;
3832    }
3833
3834    void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) {
3835        // We calculate the max size of permissions defined by this uid and throw
3836        // if that plus the size of 'info' would exceed our stated maximum.
3837        if (tree.uid != Process.SYSTEM_UID) {
3838            final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree);
3839            if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) {
3840                throw new SecurityException("Permission tree size cap exceeded");
3841            }
3842        }
3843    }
3844
3845    boolean addPermissionLocked(PermissionInfo info, boolean async) {
3846        if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
3847            throw new SecurityException("Label must be specified in permission");
3848        }
3849        BasePermission tree = checkPermissionTreeLP(info.name);
3850        BasePermission bp = mSettings.mPermissions.get(info.name);
3851        boolean added = bp == null;
3852        boolean changed = true;
3853        int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel);
3854        if (added) {
3855            enforcePermissionCapLocked(info, tree);
3856            bp = new BasePermission(info.name, tree.sourcePackage,
3857                    BasePermission.TYPE_DYNAMIC);
3858        } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
3859            throw new SecurityException(
3860                    "Not allowed to modify non-dynamic permission "
3861                    + info.name);
3862        } else {
3863            if (bp.protectionLevel == fixedLevel
3864                    && bp.perm.owner.equals(tree.perm.owner)
3865                    && bp.uid == tree.uid
3866                    && comparePermissionInfos(bp.perm.info, info)) {
3867                changed = false;
3868            }
3869        }
3870        bp.protectionLevel = fixedLevel;
3871        info = new PermissionInfo(info);
3872        info.protectionLevel = fixedLevel;
3873        bp.perm = new PackageParser.Permission(tree.perm.owner, info);
3874        bp.perm.info.packageName = tree.perm.info.packageName;
3875        bp.uid = tree.uid;
3876        if (added) {
3877            mSettings.mPermissions.put(info.name, bp);
3878        }
3879        if (changed) {
3880            if (!async) {
3881                mSettings.writeLPr();
3882            } else {
3883                scheduleWriteSettingsLocked();
3884            }
3885        }
3886        return added;
3887    }
3888
3889    @Override
3890    public boolean addPermission(PermissionInfo info) {
3891        synchronized (mPackages) {
3892            return addPermissionLocked(info, false);
3893        }
3894    }
3895
3896    @Override
3897    public boolean addPermissionAsync(PermissionInfo info) {
3898        synchronized (mPackages) {
3899            return addPermissionLocked(info, true);
3900        }
3901    }
3902
3903    @Override
3904    public void removePermission(String name) {
3905        synchronized (mPackages) {
3906            checkPermissionTreeLP(name);
3907            BasePermission bp = mSettings.mPermissions.get(name);
3908            if (bp != null) {
3909                if (bp.type != BasePermission.TYPE_DYNAMIC) {
3910                    throw new SecurityException(
3911                            "Not allowed to modify non-dynamic permission "
3912                            + name);
3913                }
3914                mSettings.mPermissions.remove(name);
3915                mSettings.writeLPr();
3916            }
3917        }
3918    }
3919
3920    private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(PackageParser.Package pkg,
3921            BasePermission bp) {
3922        int index = pkg.requestedPermissions.indexOf(bp.name);
3923        if (index == -1) {
3924            throw new SecurityException("Package " + pkg.packageName
3925                    + " has not requested permission " + bp.name);
3926        }
3927        if (!bp.isRuntime() && !bp.isDevelopment()) {
3928            throw new SecurityException("Permission " + bp.name
3929                    + " is not a changeable permission type");
3930        }
3931    }
3932
3933    @Override
3934    public void grantRuntimePermission(String packageName, String name, final int userId) {
3935        if (!sUserManager.exists(userId)) {
3936            Log.e(TAG, "No such user:" + userId);
3937            return;
3938        }
3939
3940        mContext.enforceCallingOrSelfPermission(
3941                android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
3942                "grantRuntimePermission");
3943
3944        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3945                true /* requireFullPermission */, true /* checkShell */,
3946                "grantRuntimePermission");
3947
3948        final int uid;
3949        final SettingBase sb;
3950
3951        synchronized (mPackages) {
3952            final PackageParser.Package pkg = mPackages.get(packageName);
3953            if (pkg == null) {
3954                throw new IllegalArgumentException("Unknown package: " + packageName);
3955            }
3956
3957            final BasePermission bp = mSettings.mPermissions.get(name);
3958            if (bp == null) {
3959                throw new IllegalArgumentException("Unknown permission: " + name);
3960            }
3961
3962            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
3963
3964            // If a permission review is required for legacy apps we represent
3965            // their permissions as always granted runtime ones since we need
3966            // to keep the review required permission flag per user while an
3967            // install permission's state is shared across all users.
3968            if (Build.PERMISSIONS_REVIEW_REQUIRED
3969                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
3970                    && bp.isRuntime()) {
3971                return;
3972            }
3973
3974            uid = UserHandle.getUid(userId, pkg.applicationInfo.uid);
3975            sb = (SettingBase) pkg.mExtras;
3976            if (sb == null) {
3977                throw new IllegalArgumentException("Unknown package: " + packageName);
3978            }
3979
3980            final PermissionsState permissionsState = sb.getPermissionsState();
3981
3982            final int flags = permissionsState.getPermissionFlags(name, userId);
3983            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
3984                throw new SecurityException("Cannot grant system fixed permission "
3985                        + name + " for package " + packageName);
3986            }
3987
3988            if (bp.isDevelopment()) {
3989                // Development permissions must be handled specially, since they are not
3990                // normal runtime permissions.  For now they apply to all users.
3991                if (permissionsState.grantInstallPermission(bp) !=
3992                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
3993                    scheduleWriteSettingsLocked();
3994                }
3995                return;
3996            }
3997
3998            if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
3999                Slog.w(TAG, "Cannot grant runtime permission to a legacy app");
4000                return;
4001            }
4002
4003            final int result = permissionsState.grantRuntimePermission(bp, userId);
4004            switch (result) {
4005                case PermissionsState.PERMISSION_OPERATION_FAILURE: {
4006                    return;
4007                }
4008
4009                case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
4010                    final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
4011                    mHandler.post(new Runnable() {
4012                        @Override
4013                        public void run() {
4014                            killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED);
4015                        }
4016                    });
4017                }
4018                break;
4019            }
4020
4021            mOnPermissionChangeListeners.onPermissionsChanged(uid);
4022
4023            // Not critical if that is lost - app has to request again.
4024            mSettings.writeRuntimePermissionsForUserLPr(userId, false);
4025        }
4026
4027        // Only need to do this if user is initialized. Otherwise it's a new user
4028        // and there are no processes running as the user yet and there's no need
4029        // to make an expensive call to remount processes for the changed permissions.
4030        if (READ_EXTERNAL_STORAGE.equals(name)
4031                || WRITE_EXTERNAL_STORAGE.equals(name)) {
4032            final long token = Binder.clearCallingIdentity();
4033            try {
4034                if (sUserManager.isInitialized(userId)) {
4035                    MountServiceInternal mountServiceInternal = LocalServices.getService(
4036                            MountServiceInternal.class);
4037                    mountServiceInternal.onExternalStoragePolicyChanged(uid, packageName);
4038                }
4039            } finally {
4040                Binder.restoreCallingIdentity(token);
4041            }
4042        }
4043    }
4044
4045    @Override
4046    public void revokeRuntimePermission(String packageName, String name, int userId) {
4047        if (!sUserManager.exists(userId)) {
4048            Log.e(TAG, "No such user:" + userId);
4049            return;
4050        }
4051
4052        mContext.enforceCallingOrSelfPermission(
4053                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
4054                "revokeRuntimePermission");
4055
4056        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4057                true /* requireFullPermission */, true /* checkShell */,
4058                "revokeRuntimePermission");
4059
4060        final int appId;
4061
4062        synchronized (mPackages) {
4063            final PackageParser.Package pkg = mPackages.get(packageName);
4064            if (pkg == null) {
4065                throw new IllegalArgumentException("Unknown package: " + packageName);
4066            }
4067
4068            final BasePermission bp = mSettings.mPermissions.get(name);
4069            if (bp == null) {
4070                throw new IllegalArgumentException("Unknown permission: " + name);
4071            }
4072
4073            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
4074
4075            // If a permission review is required for legacy apps we represent
4076            // their permissions as always granted runtime ones since we need
4077            // to keep the review required permission flag per user while an
4078            // install permission's state is shared across all users.
4079            if (Build.PERMISSIONS_REVIEW_REQUIRED
4080                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
4081                    && bp.isRuntime()) {
4082                return;
4083            }
4084
4085            SettingBase sb = (SettingBase) pkg.mExtras;
4086            if (sb == null) {
4087                throw new IllegalArgumentException("Unknown package: " + packageName);
4088            }
4089
4090            final PermissionsState permissionsState = sb.getPermissionsState();
4091
4092            final int flags = permissionsState.getPermissionFlags(name, userId);
4093            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
4094                throw new SecurityException("Cannot revoke system fixed permission "
4095                        + name + " for package " + packageName);
4096            }
4097
4098            if (bp.isDevelopment()) {
4099                // Development permissions must be handled specially, since they are not
4100                // normal runtime permissions.  For now they apply to all users.
4101                if (permissionsState.revokeInstallPermission(bp) !=
4102                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
4103                    scheduleWriteSettingsLocked();
4104                }
4105                return;
4106            }
4107
4108            if (permissionsState.revokeRuntimePermission(bp, userId) ==
4109                    PermissionsState.PERMISSION_OPERATION_FAILURE) {
4110                return;
4111            }
4112
4113            mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid);
4114
4115            // Critical, after this call app should never have the permission.
4116            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
4117
4118            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
4119        }
4120
4121        killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
4122    }
4123
4124    @Override
4125    public void resetRuntimePermissions() {
4126        mContext.enforceCallingOrSelfPermission(
4127                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
4128                "revokeRuntimePermission");
4129
4130        int callingUid = Binder.getCallingUid();
4131        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
4132            mContext.enforceCallingOrSelfPermission(
4133                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
4134                    "resetRuntimePermissions");
4135        }
4136
4137        synchronized (mPackages) {
4138            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL);
4139            for (int userId : UserManagerService.getInstance().getUserIds()) {
4140                final int packageCount = mPackages.size();
4141                for (int i = 0; i < packageCount; i++) {
4142                    PackageParser.Package pkg = mPackages.valueAt(i);
4143                    if (!(pkg.mExtras instanceof PackageSetting)) {
4144                        continue;
4145                    }
4146                    PackageSetting ps = (PackageSetting) pkg.mExtras;
4147                    resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
4148                }
4149            }
4150        }
4151    }
4152
4153    @Override
4154    public int getPermissionFlags(String name, String packageName, int userId) {
4155        if (!sUserManager.exists(userId)) {
4156            return 0;
4157        }
4158
4159        enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags");
4160
4161        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4162                true /* requireFullPermission */, false /* checkShell */,
4163                "getPermissionFlags");
4164
4165        synchronized (mPackages) {
4166            final PackageParser.Package pkg = mPackages.get(packageName);
4167            if (pkg == null) {
4168                return 0;
4169            }
4170
4171            final BasePermission bp = mSettings.mPermissions.get(name);
4172            if (bp == null) {
4173                return 0;
4174            }
4175
4176            SettingBase sb = (SettingBase) pkg.mExtras;
4177            if (sb == null) {
4178                return 0;
4179            }
4180
4181            PermissionsState permissionsState = sb.getPermissionsState();
4182            return permissionsState.getPermissionFlags(name, userId);
4183        }
4184    }
4185
4186    @Override
4187    public void updatePermissionFlags(String name, String packageName, int flagMask,
4188            int flagValues, int userId) {
4189        if (!sUserManager.exists(userId)) {
4190            return;
4191        }
4192
4193        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags");
4194
4195        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4196                true /* requireFullPermission */, true /* checkShell */,
4197                "updatePermissionFlags");
4198
4199        // Only the system can change these flags and nothing else.
4200        if (getCallingUid() != Process.SYSTEM_UID) {
4201            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4202            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4203            flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
4204            flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
4205            flagValues &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
4206        }
4207
4208        synchronized (mPackages) {
4209            final PackageParser.Package pkg = mPackages.get(packageName);
4210            if (pkg == null) {
4211                throw new IllegalArgumentException("Unknown package: " + packageName);
4212            }
4213
4214            final BasePermission bp = mSettings.mPermissions.get(name);
4215            if (bp == null) {
4216                throw new IllegalArgumentException("Unknown permission: " + name);
4217            }
4218
4219            SettingBase sb = (SettingBase) pkg.mExtras;
4220            if (sb == null) {
4221                throw new IllegalArgumentException("Unknown package: " + packageName);
4222            }
4223
4224            PermissionsState permissionsState = sb.getPermissionsState();
4225
4226            boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null;
4227
4228            if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) {
4229                // Install and runtime permissions are stored in different places,
4230                // so figure out what permission changed and persist the change.
4231                if (permissionsState.getInstallPermissionState(name) != null) {
4232                    scheduleWriteSettingsLocked();
4233                } else if (permissionsState.getRuntimePermissionState(name, userId) != null
4234                        || hadState) {
4235                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
4236                }
4237            }
4238        }
4239    }
4240
4241    /**
4242     * Update the permission flags for all packages and runtime permissions of a user in order
4243     * to allow device or profile owner to remove POLICY_FIXED.
4244     */
4245    @Override
4246    public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) {
4247        if (!sUserManager.exists(userId)) {
4248            return;
4249        }
4250
4251        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps");
4252
4253        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4254                true /* requireFullPermission */, true /* checkShell */,
4255                "updatePermissionFlagsForAllApps");
4256
4257        // Only the system can change system fixed flags.
4258        if (getCallingUid() != Process.SYSTEM_UID) {
4259            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4260            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4261        }
4262
4263        synchronized (mPackages) {
4264            boolean changed = false;
4265            final int packageCount = mPackages.size();
4266            for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) {
4267                final PackageParser.Package pkg = mPackages.valueAt(pkgIndex);
4268                SettingBase sb = (SettingBase) pkg.mExtras;
4269                if (sb == null) {
4270                    continue;
4271                }
4272                PermissionsState permissionsState = sb.getPermissionsState();
4273                changed |= permissionsState.updatePermissionFlagsForAllPermissions(
4274                        userId, flagMask, flagValues);
4275            }
4276            if (changed) {
4277                mSettings.writeRuntimePermissionsForUserLPr(userId, false);
4278            }
4279        }
4280    }
4281
4282    private void enforceGrantRevokeRuntimePermissionPermissions(String message) {
4283        if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS)
4284                != PackageManager.PERMISSION_GRANTED
4285            && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS)
4286                != PackageManager.PERMISSION_GRANTED) {
4287            throw new SecurityException(message + " requires "
4288                    + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or "
4289                    + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS);
4290        }
4291    }
4292
4293    @Override
4294    public boolean shouldShowRequestPermissionRationale(String permissionName,
4295            String packageName, int userId) {
4296        if (UserHandle.getCallingUserId() != userId) {
4297            mContext.enforceCallingPermission(
4298                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
4299                    "canShowRequestPermissionRationale for user " + userId);
4300        }
4301
4302        final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId);
4303        if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) {
4304            return false;
4305        }
4306
4307        if (checkPermission(permissionName, packageName, userId)
4308                == PackageManager.PERMISSION_GRANTED) {
4309            return false;
4310        }
4311
4312        final int flags;
4313
4314        final long identity = Binder.clearCallingIdentity();
4315        try {
4316            flags = getPermissionFlags(permissionName,
4317                    packageName, userId);
4318        } finally {
4319            Binder.restoreCallingIdentity(identity);
4320        }
4321
4322        final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
4323                | PackageManager.FLAG_PERMISSION_POLICY_FIXED
4324                | PackageManager.FLAG_PERMISSION_USER_FIXED;
4325
4326        if ((flags & fixedFlags) != 0) {
4327            return false;
4328        }
4329
4330        return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0;
4331    }
4332
4333    @Override
4334    public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
4335        mContext.enforceCallingOrSelfPermission(
4336                Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS,
4337                "addOnPermissionsChangeListener");
4338
4339        synchronized (mPackages) {
4340            mOnPermissionChangeListeners.addListenerLocked(listener);
4341        }
4342    }
4343
4344    @Override
4345    public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
4346        synchronized (mPackages) {
4347            mOnPermissionChangeListeners.removeListenerLocked(listener);
4348        }
4349    }
4350
4351    @Override
4352    public boolean isProtectedBroadcast(String actionName) {
4353        synchronized (mPackages) {
4354            if (mProtectedBroadcasts.contains(actionName)) {
4355                return true;
4356            } else if (actionName != null) {
4357                // TODO: remove these terrible hacks
4358                if (actionName.startsWith("android.net.netmon.lingerExpired")
4359                        || actionName.startsWith("com.android.server.sip.SipWakeupTimer")
4360                        || actionName.startsWith("com.android.internal.telephony.data-reconnect")
4361                        || actionName.startsWith("android.net.netmon.launchCaptivePortalApp")) {
4362                    return true;
4363                }
4364            }
4365        }
4366        return false;
4367    }
4368
4369    @Override
4370    public int checkSignatures(String pkg1, String pkg2) {
4371        synchronized (mPackages) {
4372            final PackageParser.Package p1 = mPackages.get(pkg1);
4373            final PackageParser.Package p2 = mPackages.get(pkg2);
4374            if (p1 == null || p1.mExtras == null
4375                    || p2 == null || p2.mExtras == null) {
4376                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4377            }
4378            return compareSignatures(p1.mSignatures, p2.mSignatures);
4379        }
4380    }
4381
4382    @Override
4383    public int checkUidSignatures(int uid1, int uid2) {
4384        // Map to base uids.
4385        uid1 = UserHandle.getAppId(uid1);
4386        uid2 = UserHandle.getAppId(uid2);
4387        // reader
4388        synchronized (mPackages) {
4389            Signature[] s1;
4390            Signature[] s2;
4391            Object obj = mSettings.getUserIdLPr(uid1);
4392            if (obj != null) {
4393                if (obj instanceof SharedUserSetting) {
4394                    s1 = ((SharedUserSetting)obj).signatures.mSignatures;
4395                } else if (obj instanceof PackageSetting) {
4396                    s1 = ((PackageSetting)obj).signatures.mSignatures;
4397                } else {
4398                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4399                }
4400            } else {
4401                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4402            }
4403            obj = mSettings.getUserIdLPr(uid2);
4404            if (obj != null) {
4405                if (obj instanceof SharedUserSetting) {
4406                    s2 = ((SharedUserSetting)obj).signatures.mSignatures;
4407                } else if (obj instanceof PackageSetting) {
4408                    s2 = ((PackageSetting)obj).signatures.mSignatures;
4409                } else {
4410                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4411                }
4412            } else {
4413                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4414            }
4415            return compareSignatures(s1, s2);
4416        }
4417    }
4418
4419    /**
4420     * This method should typically only be used when granting or revoking
4421     * permissions, since the app may immediately restart after this call.
4422     * <p>
4423     * If you're doing surgery on app code/data, use {@link PackageFreezer} to
4424     * guard your work against the app being relaunched.
4425     */
4426    private void killUid(int appId, int userId, String reason) {
4427        final long identity = Binder.clearCallingIdentity();
4428        try {
4429            IActivityManager am = ActivityManagerNative.getDefault();
4430            if (am != null) {
4431                try {
4432                    am.killUid(appId, userId, reason);
4433                } catch (RemoteException e) {
4434                    /* ignore - same process */
4435                }
4436            }
4437        } finally {
4438            Binder.restoreCallingIdentity(identity);
4439        }
4440    }
4441
4442    /**
4443     * Compares two sets of signatures. Returns:
4444     * <br />
4445     * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null,
4446     * <br />
4447     * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null,
4448     * <br />
4449     * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null,
4450     * <br />
4451     * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical,
4452     * <br />
4453     * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ.
4454     */
4455    static int compareSignatures(Signature[] s1, Signature[] s2) {
4456        if (s1 == null) {
4457            return s2 == null
4458                    ? PackageManager.SIGNATURE_NEITHER_SIGNED
4459                    : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
4460        }
4461
4462        if (s2 == null) {
4463            return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
4464        }
4465
4466        if (s1.length != s2.length) {
4467            return PackageManager.SIGNATURE_NO_MATCH;
4468        }
4469
4470        // Since both signature sets are of size 1, we can compare without HashSets.
4471        if (s1.length == 1) {
4472            return s1[0].equals(s2[0]) ?
4473                    PackageManager.SIGNATURE_MATCH :
4474                    PackageManager.SIGNATURE_NO_MATCH;
4475        }
4476
4477        ArraySet<Signature> set1 = new ArraySet<Signature>();
4478        for (Signature sig : s1) {
4479            set1.add(sig);
4480        }
4481        ArraySet<Signature> set2 = new ArraySet<Signature>();
4482        for (Signature sig : s2) {
4483            set2.add(sig);
4484        }
4485        // Make sure s2 contains all signatures in s1.
4486        if (set1.equals(set2)) {
4487            return PackageManager.SIGNATURE_MATCH;
4488        }
4489        return PackageManager.SIGNATURE_NO_MATCH;
4490    }
4491
4492    /**
4493     * If the database version for this type of package (internal storage or
4494     * external storage) is less than the version where package signatures
4495     * were updated, return true.
4496     */
4497    private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
4498        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
4499        return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY;
4500    }
4501
4502    /**
4503     * Used for backward compatibility to make sure any packages with
4504     * certificate chains get upgraded to the new style. {@code existingSigs}
4505     * will be in the old format (since they were stored on disk from before the
4506     * system upgrade) and {@code scannedSigs} will be in the newer format.
4507     */
4508    private int compareSignaturesCompat(PackageSignatures existingSigs,
4509            PackageParser.Package scannedPkg) {
4510        if (!isCompatSignatureUpdateNeeded(scannedPkg)) {
4511            return PackageManager.SIGNATURE_NO_MATCH;
4512        }
4513
4514        ArraySet<Signature> existingSet = new ArraySet<Signature>();
4515        for (Signature sig : existingSigs.mSignatures) {
4516            existingSet.add(sig);
4517        }
4518        ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>();
4519        for (Signature sig : scannedPkg.mSignatures) {
4520            try {
4521                Signature[] chainSignatures = sig.getChainSignatures();
4522                for (Signature chainSig : chainSignatures) {
4523                    scannedCompatSet.add(chainSig);
4524                }
4525            } catch (CertificateEncodingException e) {
4526                scannedCompatSet.add(sig);
4527            }
4528        }
4529        /*
4530         * Make sure the expanded scanned set contains all signatures in the
4531         * existing one.
4532         */
4533        if (scannedCompatSet.equals(existingSet)) {
4534            // Migrate the old signatures to the new scheme.
4535            existingSigs.assignSignatures(scannedPkg.mSignatures);
4536            // The new KeySets will be re-added later in the scanning process.
4537            synchronized (mPackages) {
4538                mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName);
4539            }
4540            return PackageManager.SIGNATURE_MATCH;
4541        }
4542        return PackageManager.SIGNATURE_NO_MATCH;
4543    }
4544
4545    private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
4546        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
4547        return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER;
4548    }
4549
4550    private int compareSignaturesRecover(PackageSignatures existingSigs,
4551            PackageParser.Package scannedPkg) {
4552        if (!isRecoverSignatureUpdateNeeded(scannedPkg)) {
4553            return PackageManager.SIGNATURE_NO_MATCH;
4554        }
4555
4556        String msg = null;
4557        try {
4558            if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) {
4559                logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for "
4560                        + scannedPkg.packageName);
4561                return PackageManager.SIGNATURE_MATCH;
4562            }
4563        } catch (CertificateException e) {
4564            msg = e.getMessage();
4565        }
4566
4567        logCriticalInfo(Log.INFO,
4568                "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg);
4569        return PackageManager.SIGNATURE_NO_MATCH;
4570    }
4571
4572    @Override
4573    public List<String> getAllPackages() {
4574        synchronized (mPackages) {
4575            return new ArrayList<String>(mPackages.keySet());
4576        }
4577    }
4578
4579    @Override
4580    public String[] getPackagesForUid(int uid) {
4581        final int userId = UserHandle.getUserId(uid);
4582        uid = UserHandle.getAppId(uid);
4583        // reader
4584        synchronized (mPackages) {
4585            Object obj = mSettings.getUserIdLPr(uid);
4586            if (obj instanceof SharedUserSetting) {
4587                final SharedUserSetting sus = (SharedUserSetting) obj;
4588                final int N = sus.packages.size();
4589                String[] res = new String[N];
4590                final Iterator<PackageSetting> it = sus.packages.iterator();
4591                int i = 0;
4592                while (it.hasNext()) {
4593                    PackageSetting ps = it.next();
4594                    if (ps.getInstalled(userId)) {
4595                        res[i++] = ps.name;
4596                    } else {
4597                        res = ArrayUtils.removeElement(String.class, res, res[i]);
4598                    }
4599                }
4600                return res;
4601            } else if (obj instanceof PackageSetting) {
4602                final PackageSetting ps = (PackageSetting) obj;
4603                return new String[] { ps.name };
4604            }
4605        }
4606        return null;
4607    }
4608
4609    @Override
4610    public String getNameForUid(int uid) {
4611        // reader
4612        synchronized (mPackages) {
4613            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4614            if (obj instanceof SharedUserSetting) {
4615                final SharedUserSetting sus = (SharedUserSetting) obj;
4616                return sus.name + ":" + sus.userId;
4617            } else if (obj instanceof PackageSetting) {
4618                final PackageSetting ps = (PackageSetting) obj;
4619                return ps.name;
4620            }
4621        }
4622        return null;
4623    }
4624
4625    @Override
4626    public int getUidForSharedUser(String sharedUserName) {
4627        if(sharedUserName == null) {
4628            return -1;
4629        }
4630        // reader
4631        synchronized (mPackages) {
4632            final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false);
4633            if (suid == null) {
4634                return -1;
4635            }
4636            return suid.userId;
4637        }
4638    }
4639
4640    @Override
4641    public int getFlagsForUid(int uid) {
4642        synchronized (mPackages) {
4643            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4644            if (obj instanceof SharedUserSetting) {
4645                final SharedUserSetting sus = (SharedUserSetting) obj;
4646                return sus.pkgFlags;
4647            } else if (obj instanceof PackageSetting) {
4648                final PackageSetting ps = (PackageSetting) obj;
4649                return ps.pkgFlags;
4650            }
4651        }
4652        return 0;
4653    }
4654
4655    @Override
4656    public int getPrivateFlagsForUid(int uid) {
4657        synchronized (mPackages) {
4658            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4659            if (obj instanceof SharedUserSetting) {
4660                final SharedUserSetting sus = (SharedUserSetting) obj;
4661                return sus.pkgPrivateFlags;
4662            } else if (obj instanceof PackageSetting) {
4663                final PackageSetting ps = (PackageSetting) obj;
4664                return ps.pkgPrivateFlags;
4665            }
4666        }
4667        return 0;
4668    }
4669
4670    @Override
4671    public boolean isUidPrivileged(int uid) {
4672        uid = UserHandle.getAppId(uid);
4673        // reader
4674        synchronized (mPackages) {
4675            Object obj = mSettings.getUserIdLPr(uid);
4676            if (obj instanceof SharedUserSetting) {
4677                final SharedUserSetting sus = (SharedUserSetting) obj;
4678                final Iterator<PackageSetting> it = sus.packages.iterator();
4679                while (it.hasNext()) {
4680                    if (it.next().isPrivileged()) {
4681                        return true;
4682                    }
4683                }
4684            } else if (obj instanceof PackageSetting) {
4685                final PackageSetting ps = (PackageSetting) obj;
4686                return ps.isPrivileged();
4687            }
4688        }
4689        return false;
4690    }
4691
4692    @Override
4693    public String[] getAppOpPermissionPackages(String permissionName) {
4694        synchronized (mPackages) {
4695            ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName);
4696            if (pkgs == null) {
4697                return null;
4698            }
4699            return pkgs.toArray(new String[pkgs.size()]);
4700        }
4701    }
4702
4703    @Override
4704    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
4705            int flags, int userId) {
4706        try {
4707            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveIntent");
4708
4709            if (!sUserManager.exists(userId)) return null;
4710            flags = updateFlagsForResolve(flags, userId, intent);
4711            enforceCrossUserPermission(Binder.getCallingUid(), userId,
4712                    false /*requireFullPermission*/, false /*checkShell*/, "resolve intent");
4713
4714            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
4715            final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType,
4716                    flags, userId);
4717            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
4718
4719            final ResolveInfo bestChoice =
4720                    chooseBestActivity(intent, resolvedType, flags, query, userId);
4721
4722            if (isEphemeralAllowed(intent, query, userId)) {
4723                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveEphemeral");
4724                final EphemeralResolveInfo ai =
4725                        getEphemeralResolveInfo(intent, resolvedType, userId);
4726                if (ai != null) {
4727                    if (DEBUG_EPHEMERAL) {
4728                        Slog.v(TAG, "Returning an EphemeralResolveInfo");
4729                    }
4730                    bestChoice.ephemeralInstaller = mEphemeralInstallerInfo;
4731                    bestChoice.ephemeralResolveInfo = ai;
4732                }
4733                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
4734            }
4735            return bestChoice;
4736        } finally {
4737            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
4738        }
4739    }
4740
4741    @Override
4742    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
4743            IntentFilter filter, int match, ComponentName activity) {
4744        final int userId = UserHandle.getCallingUserId();
4745        if (DEBUG_PREFERRED) {
4746            Log.v(TAG, "setLastChosenActivity intent=" + intent
4747                + " resolvedType=" + resolvedType
4748                + " flags=" + flags
4749                + " filter=" + filter
4750                + " match=" + match
4751                + " activity=" + activity);
4752            filter.dump(new PrintStreamPrinter(System.out), "    ");
4753        }
4754        intent.setComponent(null);
4755        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
4756                userId);
4757        // Find any earlier preferred or last chosen entries and nuke them
4758        findPreferredActivity(intent, resolvedType,
4759                flags, query, 0, false, true, false, userId);
4760        // Add the new activity as the last chosen for this filter
4761        addPreferredActivityInternal(filter, match, null, activity, false, userId,
4762                "Setting last chosen");
4763    }
4764
4765    @Override
4766    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
4767        final int userId = UserHandle.getCallingUserId();
4768        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
4769        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
4770                userId);
4771        return findPreferredActivity(intent, resolvedType, flags, query, 0,
4772                false, false, false, userId);
4773    }
4774
4775
4776    private boolean isEphemeralAllowed(
4777            Intent intent, List<ResolveInfo> resolvedActivites, int userId) {
4778        // Short circuit and return early if possible.
4779        if (DISABLE_EPHEMERAL_APPS) {
4780            return false;
4781        }
4782        final int callingUser = UserHandle.getCallingUserId();
4783        if (callingUser != UserHandle.USER_SYSTEM) {
4784            return false;
4785        }
4786        if (mEphemeralResolverConnection == null) {
4787            return false;
4788        }
4789        if (intent.getComponent() != null) {
4790            return false;
4791        }
4792        if (intent.getPackage() != null) {
4793            return false;
4794        }
4795        final boolean isWebUri = hasWebURI(intent);
4796        if (!isWebUri) {
4797            return false;
4798        }
4799        // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution.
4800        synchronized (mPackages) {
4801            final int count = resolvedActivites.size();
4802            for (int n = 0; n < count; n++) {
4803                ResolveInfo info = resolvedActivites.get(n);
4804                String packageName = info.activityInfo.packageName;
4805                PackageSetting ps = mSettings.mPackages.get(packageName);
4806                if (ps != null) {
4807                    // Try to get the status from User settings first
4808                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
4809                    int status = (int) (packedStatus >> 32);
4810                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS
4811                            || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
4812                        if (DEBUG_EPHEMERAL) {
4813                            Slog.v(TAG, "DENY ephemeral apps;"
4814                                + " pkg: " + packageName + ", status: " + status);
4815                        }
4816                        return false;
4817                    }
4818                }
4819            }
4820        }
4821        // We've exhausted all ways to deny ephemeral application; let the system look for them.
4822        return true;
4823    }
4824
4825    private EphemeralResolveInfo getEphemeralResolveInfo(Intent intent, String resolvedType,
4826            int userId) {
4827        MessageDigest digest = null;
4828        try {
4829            digest = MessageDigest.getInstance(EphemeralResolveInfo.SHA_ALGORITHM);
4830        } catch (NoSuchAlgorithmException e) {
4831            // If we can't create a digest, ignore ephemeral apps.
4832            return null;
4833        }
4834
4835        final byte[] hostBytes = intent.getData().getHost().getBytes();
4836        final byte[] digestBytes = digest.digest(hostBytes);
4837        int shaPrefix =
4838                digestBytes[0] << 24
4839                | digestBytes[1] << 16
4840                | digestBytes[2] << 8
4841                | digestBytes[3] << 0;
4842        final List<EphemeralResolveInfo> ephemeralResolveInfoList =
4843                mEphemeralResolverConnection.getEphemeralResolveInfoList(shaPrefix);
4844        if (ephemeralResolveInfoList == null || ephemeralResolveInfoList.size() == 0) {
4845            // No hash prefix match; there are no ephemeral apps for this domain.
4846            return null;
4847        }
4848        for (int i = ephemeralResolveInfoList.size() - 1; i >= 0; --i) {
4849            EphemeralResolveInfo ephemeralApplication = ephemeralResolveInfoList.get(i);
4850            if (!Arrays.equals(digestBytes, ephemeralApplication.getDigestBytes())) {
4851                continue;
4852            }
4853            final List<IntentFilter> filters = ephemeralApplication.getFilters();
4854            // No filters; this should never happen.
4855            if (filters.isEmpty()) {
4856                continue;
4857            }
4858            // We have a domain match; resolve the filters to see if anything matches.
4859            final EphemeralIntentResolver ephemeralResolver = new EphemeralIntentResolver();
4860            for (int j = filters.size() - 1; j >= 0; --j) {
4861                final EphemeralResolveIntentInfo intentInfo =
4862                        new EphemeralResolveIntentInfo(filters.get(j), ephemeralApplication);
4863                ephemeralResolver.addFilter(intentInfo);
4864            }
4865            List<EphemeralResolveInfo> matchedResolveInfoList = ephemeralResolver.queryIntent(
4866                    intent, resolvedType, false /*defaultOnly*/, userId);
4867            if (!matchedResolveInfoList.isEmpty()) {
4868                return matchedResolveInfoList.get(0);
4869            }
4870        }
4871        // Hash or filter mis-match; no ephemeral apps for this domain.
4872        return null;
4873    }
4874
4875    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
4876            int flags, List<ResolveInfo> query, int userId) {
4877        if (query != null) {
4878            final int N = query.size();
4879            if (N == 1) {
4880                return query.get(0);
4881            } else if (N > 1) {
4882                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
4883                // If there is more than one activity with the same priority,
4884                // then let the user decide between them.
4885                ResolveInfo r0 = query.get(0);
4886                ResolveInfo r1 = query.get(1);
4887                if (DEBUG_INTENT_MATCHING || debug) {
4888                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
4889                            + r1.activityInfo.name + "=" + r1.priority);
4890                }
4891                // If the first activity has a higher priority, or a different
4892                // default, then it is always desirable to pick it.
4893                if (r0.priority != r1.priority
4894                        || r0.preferredOrder != r1.preferredOrder
4895                        || r0.isDefault != r1.isDefault) {
4896                    return query.get(0);
4897                }
4898                // If we have saved a preference for a preferred activity for
4899                // this Intent, use that.
4900                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
4901                        flags, query, r0.priority, true, false, debug, userId);
4902                if (ri != null) {
4903                    return ri;
4904                }
4905                ri = new ResolveInfo(mResolveInfo);
4906                ri.activityInfo = new ActivityInfo(ri.activityInfo);
4907                ri.activityInfo.labelRes = ResolverActivity.getLabelRes(intent.getAction());
4908                // If all of the options come from the same package, show the application's
4909                // label and icon instead of the generic resolver's.
4910                // Some calls like Intent.resolveActivityInfo query the ResolveInfo from here
4911                // and then throw away the ResolveInfo itself, meaning that the caller loses
4912                // the resolvePackageName. Therefore the activityInfo.labelRes above provides
4913                // a fallback for this case; we only set the target package's resources on
4914                // the ResolveInfo, not the ActivityInfo.
4915                final String intentPackage = intent.getPackage();
4916                if (!TextUtils.isEmpty(intentPackage) && allHavePackage(query, intentPackage)) {
4917                    final ApplicationInfo appi = query.get(0).activityInfo.applicationInfo;
4918                    ri.resolvePackageName = intentPackage;
4919                    if (userNeedsBadging(userId)) {
4920                        ri.noResourceId = true;
4921                    } else {
4922                        ri.icon = appi.icon;
4923                    }
4924                    ri.iconResourceId = appi.icon;
4925                    ri.labelRes = appi.labelRes;
4926                }
4927                ri.activityInfo.applicationInfo = new ApplicationInfo(
4928                        ri.activityInfo.applicationInfo);
4929                if (userId != 0) {
4930                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
4931                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
4932                }
4933                // Make sure that the resolver is displayable in car mode
4934                if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle();
4935                ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true);
4936                return ri;
4937            }
4938        }
4939        return null;
4940    }
4941
4942    /**
4943     * Return true if the given list is not empty and all of its contents have
4944     * an activityInfo with the given package name.
4945     */
4946    private boolean allHavePackage(List<ResolveInfo> list, String packageName) {
4947        if (ArrayUtils.isEmpty(list)) {
4948            return false;
4949        }
4950        for (int i = 0, N = list.size(); i < N; i++) {
4951            final ResolveInfo ri = list.get(i);
4952            final ActivityInfo ai = ri != null ? ri.activityInfo : null;
4953            if (ai == null || !packageName.equals(ai.packageName)) {
4954                return false;
4955            }
4956        }
4957        return true;
4958    }
4959
4960    private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
4961            int flags, List<ResolveInfo> query, boolean debug, int userId) {
4962        final int N = query.size();
4963        PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
4964                .get(userId);
4965        // Get the list of persistent preferred activities that handle the intent
4966        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
4967        List<PersistentPreferredActivity> pprefs = ppir != null
4968                ? ppir.queryIntent(intent, resolvedType,
4969                        (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
4970                : null;
4971        if (pprefs != null && pprefs.size() > 0) {
4972            final int M = pprefs.size();
4973            for (int i=0; i<M; i++) {
4974                final PersistentPreferredActivity ppa = pprefs.get(i);
4975                if (DEBUG_PREFERRED || debug) {
4976                    Slog.v(TAG, "Checking PersistentPreferredActivity ds="
4977                            + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
4978                            + "\n  component=" + ppa.mComponent);
4979                    ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4980                }
4981                final ActivityInfo ai = getActivityInfo(ppa.mComponent,
4982                        flags | MATCH_DISABLED_COMPONENTS, userId);
4983                if (DEBUG_PREFERRED || debug) {
4984                    Slog.v(TAG, "Found persistent preferred activity:");
4985                    if (ai != null) {
4986                        ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4987                    } else {
4988                        Slog.v(TAG, "  null");
4989                    }
4990                }
4991                if (ai == null) {
4992                    // This previously registered persistent preferred activity
4993                    // component is no longer known. Ignore it and do NOT remove it.
4994                    continue;
4995                }
4996                for (int j=0; j<N; j++) {
4997                    final ResolveInfo ri = query.get(j);
4998                    if (!ri.activityInfo.applicationInfo.packageName
4999                            .equals(ai.applicationInfo.packageName)) {
5000                        continue;
5001                    }
5002                    if (!ri.activityInfo.name.equals(ai.name)) {
5003                        continue;
5004                    }
5005                    //  Found a persistent preference that can handle the intent.
5006                    if (DEBUG_PREFERRED || debug) {
5007                        Slog.v(TAG, "Returning persistent preferred activity: " +
5008                                ri.activityInfo.packageName + "/" + ri.activityInfo.name);
5009                    }
5010                    return ri;
5011                }
5012            }
5013        }
5014        return null;
5015    }
5016
5017    // TODO: handle preferred activities missing while user has amnesia
5018    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
5019            List<ResolveInfo> query, int priority, boolean always,
5020            boolean removeMatches, boolean debug, int userId) {
5021        if (!sUserManager.exists(userId)) return null;
5022        flags = updateFlagsForResolve(flags, userId, intent);
5023        // writer
5024        synchronized (mPackages) {
5025            if (intent.getSelector() != null) {
5026                intent = intent.getSelector();
5027            }
5028            if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
5029
5030            // Try to find a matching persistent preferred activity.
5031            ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
5032                    debug, userId);
5033
5034            // If a persistent preferred activity matched, use it.
5035            if (pri != null) {
5036                return pri;
5037            }
5038
5039            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
5040            // Get the list of preferred activities that handle the intent
5041            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
5042            List<PreferredActivity> prefs = pir != null
5043                    ? pir.queryIntent(intent, resolvedType,
5044                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
5045                    : null;
5046            if (prefs != null && prefs.size() > 0) {
5047                boolean changed = false;
5048                try {
5049                    // First figure out how good the original match set is.
5050                    // We will only allow preferred activities that came
5051                    // from the same match quality.
5052                    int match = 0;
5053
5054                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
5055
5056                    final int N = query.size();
5057                    for (int j=0; j<N; j++) {
5058                        final ResolveInfo ri = query.get(j);
5059                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
5060                                + ": 0x" + Integer.toHexString(match));
5061                        if (ri.match > match) {
5062                            match = ri.match;
5063                        }
5064                    }
5065
5066                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
5067                            + Integer.toHexString(match));
5068
5069                    match &= IntentFilter.MATCH_CATEGORY_MASK;
5070                    final int M = prefs.size();
5071                    for (int i=0; i<M; i++) {
5072                        final PreferredActivity pa = prefs.get(i);
5073                        if (DEBUG_PREFERRED || debug) {
5074                            Slog.v(TAG, "Checking PreferredActivity ds="
5075                                    + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
5076                                    + "\n  component=" + pa.mPref.mComponent);
5077                            pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
5078                        }
5079                        if (pa.mPref.mMatch != match) {
5080                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
5081                                    + Integer.toHexString(pa.mPref.mMatch));
5082                            continue;
5083                        }
5084                        // If it's not an "always" type preferred activity and that's what we're
5085                        // looking for, skip it.
5086                        if (always && !pa.mPref.mAlways) {
5087                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
5088                            continue;
5089                        }
5090                        final ActivityInfo ai = getActivityInfo(
5091                                pa.mPref.mComponent, flags | MATCH_DISABLED_COMPONENTS
5092                                        | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
5093                                userId);
5094                        if (DEBUG_PREFERRED || debug) {
5095                            Slog.v(TAG, "Found preferred activity:");
5096                            if (ai != null) {
5097                                ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
5098                            } else {
5099                                Slog.v(TAG, "  null");
5100                            }
5101                        }
5102                        if (ai == null) {
5103                            // This previously registered preferred activity
5104                            // component is no longer known.  Most likely an update
5105                            // to the app was installed and in the new version this
5106                            // component no longer exists.  Clean it up by removing
5107                            // it from the preferred activities list, and skip it.
5108                            Slog.w(TAG, "Removing dangling preferred activity: "
5109                                    + pa.mPref.mComponent);
5110                            pir.removeFilter(pa);
5111                            changed = true;
5112                            continue;
5113                        }
5114                        for (int j=0; j<N; j++) {
5115                            final ResolveInfo ri = query.get(j);
5116                            if (!ri.activityInfo.applicationInfo.packageName
5117                                    .equals(ai.applicationInfo.packageName)) {
5118                                continue;
5119                            }
5120                            if (!ri.activityInfo.name.equals(ai.name)) {
5121                                continue;
5122                            }
5123
5124                            if (removeMatches) {
5125                                pir.removeFilter(pa);
5126                                changed = true;
5127                                if (DEBUG_PREFERRED) {
5128                                    Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
5129                                }
5130                                break;
5131                            }
5132
5133                            // Okay we found a previously set preferred or last chosen app.
5134                            // If the result set is different from when this
5135                            // was created, we need to clear it and re-ask the
5136                            // user their preference, if we're looking for an "always" type entry.
5137                            if (always && !pa.mPref.sameSet(query)) {
5138                                Slog.i(TAG, "Result set changed, dropping preferred activity for "
5139                                        + intent + " type " + resolvedType);
5140                                if (DEBUG_PREFERRED) {
5141                                    Slog.v(TAG, "Removing preferred activity since set changed "
5142                                            + pa.mPref.mComponent);
5143                                }
5144                                pir.removeFilter(pa);
5145                                // Re-add the filter as a "last chosen" entry (!always)
5146                                PreferredActivity lastChosen = new PreferredActivity(
5147                                        pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
5148                                pir.addFilter(lastChosen);
5149                                changed = true;
5150                                return null;
5151                            }
5152
5153                            // Yay! Either the set matched or we're looking for the last chosen
5154                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
5155                                    + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
5156                            return ri;
5157                        }
5158                    }
5159                } finally {
5160                    if (changed) {
5161                        if (DEBUG_PREFERRED) {
5162                            Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions");
5163                        }
5164                        scheduleWritePackageRestrictionsLocked(userId);
5165                    }
5166                }
5167            }
5168        }
5169        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
5170        return null;
5171    }
5172
5173    /*
5174     * Returns if intent can be forwarded from the sourceUserId to the targetUserId
5175     */
5176    @Override
5177    public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
5178            int targetUserId) {
5179        mContext.enforceCallingOrSelfPermission(
5180                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
5181        List<CrossProfileIntentFilter> matches =
5182                getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
5183        if (matches != null) {
5184            int size = matches.size();
5185            for (int i = 0; i < size; i++) {
5186                if (matches.get(i).getTargetUserId() == targetUserId) return true;
5187            }
5188        }
5189        if (hasWebURI(intent)) {
5190            // cross-profile app linking works only towards the parent.
5191            final UserInfo parent = getProfileParent(sourceUserId);
5192            synchronized(mPackages) {
5193                int flags = updateFlagsForResolve(0, parent.id, intent);
5194                CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr(
5195                        intent, resolvedType, flags, sourceUserId, parent.id);
5196                return xpDomainInfo != null;
5197            }
5198        }
5199        return false;
5200    }
5201
5202    private UserInfo getProfileParent(int userId) {
5203        final long identity = Binder.clearCallingIdentity();
5204        try {
5205            return sUserManager.getProfileParent(userId);
5206        } finally {
5207            Binder.restoreCallingIdentity(identity);
5208        }
5209    }
5210
5211    private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
5212            String resolvedType, int userId) {
5213        CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
5214        if (resolver != null) {
5215            return resolver.queryIntent(intent, resolvedType, false, userId);
5216        }
5217        return null;
5218    }
5219
5220    @Override
5221    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivities(Intent intent,
5222            String resolvedType, int flags, int userId) {
5223        try {
5224            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
5225
5226            return new ParceledListSlice<>(
5227                    queryIntentActivitiesInternal(intent, resolvedType, flags, userId));
5228        } finally {
5229            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
5230        }
5231    }
5232
5233    private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent,
5234            String resolvedType, int flags, int userId) {
5235        if (!sUserManager.exists(userId)) return Collections.emptyList();
5236        flags = updateFlagsForResolve(flags, userId, intent);
5237        enforceCrossUserPermission(Binder.getCallingUid(), userId,
5238                false /* requireFullPermission */, false /* checkShell */,
5239                "query intent activities");
5240        ComponentName comp = intent.getComponent();
5241        if (comp == null) {
5242            if (intent.getSelector() != null) {
5243                intent = intent.getSelector();
5244                comp = intent.getComponent();
5245            }
5246        }
5247
5248        if (comp != null) {
5249            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5250            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
5251            if (ai != null) {
5252                final ResolveInfo ri = new ResolveInfo();
5253                ri.activityInfo = ai;
5254                list.add(ri);
5255            }
5256            return list;
5257        }
5258
5259        // reader
5260        synchronized (mPackages) {
5261            final String pkgName = intent.getPackage();
5262            if (pkgName == null) {
5263                List<CrossProfileIntentFilter> matchingFilters =
5264                        getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
5265                // Check for results that need to skip the current profile.
5266                ResolveInfo xpResolveInfo  = querySkipCurrentProfileIntents(matchingFilters, intent,
5267                        resolvedType, flags, userId);
5268                if (xpResolveInfo != null) {
5269                    List<ResolveInfo> result = new ArrayList<ResolveInfo>(1);
5270                    result.add(xpResolveInfo);
5271                    return filterIfNotSystemUser(result, userId);
5272                }
5273
5274                // Check for results in the current profile.
5275                List<ResolveInfo> result = mActivities.queryIntent(
5276                        intent, resolvedType, flags, userId);
5277                result = filterIfNotSystemUser(result, userId);
5278
5279                // Check for cross profile results.
5280                boolean hasNonNegativePriorityResult = hasNonNegativePriority(result);
5281                xpResolveInfo = queryCrossProfileIntents(
5282                        matchingFilters, intent, resolvedType, flags, userId,
5283                        hasNonNegativePriorityResult);
5284                if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
5285                    boolean isVisibleToUser = filterIfNotSystemUser(
5286                            Collections.singletonList(xpResolveInfo), userId).size() > 0;
5287                    if (isVisibleToUser) {
5288                        result.add(xpResolveInfo);
5289                        Collections.sort(result, mResolvePrioritySorter);
5290                    }
5291                }
5292                if (hasWebURI(intent)) {
5293                    CrossProfileDomainInfo xpDomainInfo = null;
5294                    final UserInfo parent = getProfileParent(userId);
5295                    if (parent != null) {
5296                        xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType,
5297                                flags, userId, parent.id);
5298                    }
5299                    if (xpDomainInfo != null) {
5300                        if (xpResolveInfo != null) {
5301                            // If we didn't remove it, the cross-profile ResolveInfo would be twice
5302                            // in the result.
5303                            result.remove(xpResolveInfo);
5304                        }
5305                        if (result.size() == 0) {
5306                            result.add(xpDomainInfo.resolveInfo);
5307                            return result;
5308                        }
5309                    } else if (result.size() <= 1) {
5310                        return result;
5311                    }
5312                    result = filterCandidatesWithDomainPreferredActivitiesLPr(intent, flags, result,
5313                            xpDomainInfo, userId);
5314                    Collections.sort(result, mResolvePrioritySorter);
5315                }
5316                return result;
5317            }
5318            final PackageParser.Package pkg = mPackages.get(pkgName);
5319            if (pkg != null) {
5320                return filterIfNotSystemUser(
5321                        mActivities.queryIntentForPackage(
5322                                intent, resolvedType, flags, pkg.activities, userId),
5323                        userId);
5324            }
5325            return new ArrayList<ResolveInfo>();
5326        }
5327    }
5328
5329    private static class CrossProfileDomainInfo {
5330        /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */
5331        ResolveInfo resolveInfo;
5332        /* Best domain verification status of the activities found in the other profile */
5333        int bestDomainVerificationStatus;
5334    }
5335
5336    private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent,
5337            String resolvedType, int flags, int sourceUserId, int parentUserId) {
5338        if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING,
5339                sourceUserId)) {
5340            return null;
5341        }
5342        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
5343                resolvedType, flags, parentUserId);
5344
5345        if (resultTargetUser == null || resultTargetUser.isEmpty()) {
5346            return null;
5347        }
5348        CrossProfileDomainInfo result = null;
5349        int size = resultTargetUser.size();
5350        for (int i = 0; i < size; i++) {
5351            ResolveInfo riTargetUser = resultTargetUser.get(i);
5352            // Intent filter verification is only for filters that specify a host. So don't return
5353            // those that handle all web uris.
5354            if (riTargetUser.handleAllWebDataURI) {
5355                continue;
5356            }
5357            String packageName = riTargetUser.activityInfo.packageName;
5358            PackageSetting ps = mSettings.mPackages.get(packageName);
5359            if (ps == null) {
5360                continue;
5361            }
5362            long verificationState = getDomainVerificationStatusLPr(ps, parentUserId);
5363            int status = (int)(verificationState >> 32);
5364            if (result == null) {
5365                result = new CrossProfileDomainInfo();
5366                result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(),
5367                        sourceUserId, parentUserId);
5368                result.bestDomainVerificationStatus = status;
5369            } else {
5370                result.bestDomainVerificationStatus = bestDomainVerificationStatus(status,
5371                        result.bestDomainVerificationStatus);
5372            }
5373        }
5374        // Don't consider matches with status NEVER across profiles.
5375        if (result != null && result.bestDomainVerificationStatus
5376                == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5377            return null;
5378        }
5379        return result;
5380    }
5381
5382    /**
5383     * Verification statuses are ordered from the worse to the best, except for
5384     * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse.
5385     */
5386    private int bestDomainVerificationStatus(int status1, int status2) {
5387        if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5388            return status2;
5389        }
5390        if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5391            return status1;
5392        }
5393        return (int) MathUtils.max(status1, status2);
5394    }
5395
5396    private boolean isUserEnabled(int userId) {
5397        long callingId = Binder.clearCallingIdentity();
5398        try {
5399            UserInfo userInfo = sUserManager.getUserInfo(userId);
5400            return userInfo != null && userInfo.isEnabled();
5401        } finally {
5402            Binder.restoreCallingIdentity(callingId);
5403        }
5404    }
5405
5406    /**
5407     * Filter out activities with systemUserOnly flag set, when current user is not System.
5408     *
5409     * @return filtered list
5410     */
5411    private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) {
5412        if (userId == UserHandle.USER_SYSTEM) {
5413            return resolveInfos;
5414        }
5415        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
5416            ResolveInfo info = resolveInfos.get(i);
5417            if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) {
5418                resolveInfos.remove(i);
5419            }
5420        }
5421        return resolveInfos;
5422    }
5423
5424    /**
5425     * @param resolveInfos list of resolve infos in descending priority order
5426     * @return if the list contains a resolve info with non-negative priority
5427     */
5428    private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) {
5429        return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0;
5430    }
5431
5432    private static boolean hasWebURI(Intent intent) {
5433        if (intent.getData() == null) {
5434            return false;
5435        }
5436        final String scheme = intent.getScheme();
5437        if (TextUtils.isEmpty(scheme)) {
5438            return false;
5439        }
5440        return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS);
5441    }
5442
5443    private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent,
5444            int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo,
5445            int userId) {
5446        final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0;
5447
5448        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
5449            Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " +
5450                    candidates.size());
5451        }
5452
5453        ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>();
5454        ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>();
5455        ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>();
5456        ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>();
5457        ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>();
5458        ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>();
5459
5460        synchronized (mPackages) {
5461            final int count = candidates.size();
5462            // First, try to use linked apps. Partition the candidates into four lists:
5463            // one for the final results, one for the "do not use ever", one for "undefined status"
5464            // and finally one for "browser app type".
5465            for (int n=0; n<count; n++) {
5466                ResolveInfo info = candidates.get(n);
5467                String packageName = info.activityInfo.packageName;
5468                PackageSetting ps = mSettings.mPackages.get(packageName);
5469                if (ps != null) {
5470                    // Add to the special match all list (Browser use case)
5471                    if (info.handleAllWebDataURI) {
5472                        matchAllList.add(info);
5473                        continue;
5474                    }
5475                    // Try to get the status from User settings first
5476                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
5477                    int status = (int)(packedStatus >> 32);
5478                    int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
5479                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
5480                        if (DEBUG_DOMAIN_VERIFICATION) {
5481                            Slog.i(TAG, "  + always: " + info.activityInfo.packageName
5482                                    + " : linkgen=" + linkGeneration);
5483                        }
5484                        // Use link-enabled generation as preferredOrder, i.e.
5485                        // prefer newly-enabled over earlier-enabled.
5486                        info.preferredOrder = linkGeneration;
5487                        alwaysList.add(info);
5488                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5489                        if (DEBUG_DOMAIN_VERIFICATION) {
5490                            Slog.i(TAG, "  + never: " + info.activityInfo.packageName);
5491                        }
5492                        neverList.add(info);
5493                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
5494                        if (DEBUG_DOMAIN_VERIFICATION) {
5495                            Slog.i(TAG, "  + always-ask: " + info.activityInfo.packageName);
5496                        }
5497                        alwaysAskList.add(info);
5498                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED ||
5499                            status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) {
5500                        if (DEBUG_DOMAIN_VERIFICATION) {
5501                            Slog.i(TAG, "  + ask: " + info.activityInfo.packageName);
5502                        }
5503                        undefinedList.add(info);
5504                    }
5505                }
5506            }
5507
5508            // We'll want to include browser possibilities in a few cases
5509            boolean includeBrowser = false;
5510
5511            // First try to add the "always" resolution(s) for the current user, if any
5512            if (alwaysList.size() > 0) {
5513                result.addAll(alwaysList);
5514            } else {
5515                // Add all undefined apps as we want them to appear in the disambiguation dialog.
5516                result.addAll(undefinedList);
5517                // Maybe add one for the other profile.
5518                if (xpDomainInfo != null && (
5519                        xpDomainInfo.bestDomainVerificationStatus
5520                        != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) {
5521                    result.add(xpDomainInfo.resolveInfo);
5522                }
5523                includeBrowser = true;
5524            }
5525
5526            // The presence of any 'always ask' alternatives means we'll also offer browsers.
5527            // If there were 'always' entries their preferred order has been set, so we also
5528            // back that off to make the alternatives equivalent
5529            if (alwaysAskList.size() > 0) {
5530                for (ResolveInfo i : result) {
5531                    i.preferredOrder = 0;
5532                }
5533                result.addAll(alwaysAskList);
5534                includeBrowser = true;
5535            }
5536
5537            if (includeBrowser) {
5538                // Also add browsers (all of them or only the default one)
5539                if (DEBUG_DOMAIN_VERIFICATION) {
5540                    Slog.v(TAG, "   ...including browsers in candidate set");
5541                }
5542                if ((matchFlags & MATCH_ALL) != 0) {
5543                    result.addAll(matchAllList);
5544                } else {
5545                    // Browser/generic handling case.  If there's a default browser, go straight
5546                    // to that (but only if there is no other higher-priority match).
5547                    final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
5548                    int maxMatchPrio = 0;
5549                    ResolveInfo defaultBrowserMatch = null;
5550                    final int numCandidates = matchAllList.size();
5551                    for (int n = 0; n < numCandidates; n++) {
5552                        ResolveInfo info = matchAllList.get(n);
5553                        // track the highest overall match priority...
5554                        if (info.priority > maxMatchPrio) {
5555                            maxMatchPrio = info.priority;
5556                        }
5557                        // ...and the highest-priority default browser match
5558                        if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) {
5559                            if (defaultBrowserMatch == null
5560                                    || (defaultBrowserMatch.priority < info.priority)) {
5561                                if (debug) {
5562                                    Slog.v(TAG, "Considering default browser match " + info);
5563                                }
5564                                defaultBrowserMatch = info;
5565                            }
5566                        }
5567                    }
5568                    if (defaultBrowserMatch != null
5569                            && defaultBrowserMatch.priority >= maxMatchPrio
5570                            && !TextUtils.isEmpty(defaultBrowserPackageName))
5571                    {
5572                        if (debug) {
5573                            Slog.v(TAG, "Default browser match " + defaultBrowserMatch);
5574                        }
5575                        result.add(defaultBrowserMatch);
5576                    } else {
5577                        result.addAll(matchAllList);
5578                    }
5579                }
5580
5581                // If there is nothing selected, add all candidates and remove the ones that the user
5582                // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state
5583                if (result.size() == 0) {
5584                    result.addAll(candidates);
5585                    result.removeAll(neverList);
5586                }
5587            }
5588        }
5589        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
5590            Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " +
5591                    result.size());
5592            for (ResolveInfo info : result) {
5593                Slog.v(TAG, "  + " + info.activityInfo);
5594            }
5595        }
5596        return result;
5597    }
5598
5599    // Returns a packed value as a long:
5600    //
5601    // high 'int'-sized word: link status: undefined/ask/never/always.
5602    // low 'int'-sized word: relative priority among 'always' results.
5603    private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) {
5604        long result = ps.getDomainVerificationStatusForUser(userId);
5605        // if none available, get the master status
5606        if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
5607            if (ps.getIntentFilterVerificationInfo() != null) {
5608                result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32;
5609            }
5610        }
5611        return result;
5612    }
5613
5614    private ResolveInfo querySkipCurrentProfileIntents(
5615            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
5616            int flags, int sourceUserId) {
5617        if (matchingFilters != null) {
5618            int size = matchingFilters.size();
5619            for (int i = 0; i < size; i ++) {
5620                CrossProfileIntentFilter filter = matchingFilters.get(i);
5621                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
5622                    // Checking if there are activities in the target user that can handle the
5623                    // intent.
5624                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
5625                            resolvedType, flags, sourceUserId);
5626                    if (resolveInfo != null) {
5627                        return resolveInfo;
5628                    }
5629                }
5630            }
5631        }
5632        return null;
5633    }
5634
5635    // Return matching ResolveInfo in target user if any.
5636    private ResolveInfo queryCrossProfileIntents(
5637            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
5638            int flags, int sourceUserId, boolean matchInCurrentProfile) {
5639        if (matchingFilters != null) {
5640            // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
5641            // match the same intent. For performance reasons, it is better not to
5642            // run queryIntent twice for the same userId
5643            SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
5644            int size = matchingFilters.size();
5645            for (int i = 0; i < size; i++) {
5646                CrossProfileIntentFilter filter = matchingFilters.get(i);
5647                int targetUserId = filter.getTargetUserId();
5648                boolean skipCurrentProfile =
5649                        (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0;
5650                boolean skipCurrentProfileIfNoMatchFound =
5651                        (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0;
5652                if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId)
5653                        && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) {
5654                    // Checking if there are activities in the target user that can handle the
5655                    // intent.
5656                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
5657                            resolvedType, flags, sourceUserId);
5658                    if (resolveInfo != null) return resolveInfo;
5659                    alreadyTriedUserIds.put(targetUserId, true);
5660                }
5661            }
5662        }
5663        return null;
5664    }
5665
5666    /**
5667     * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that
5668     * will forward the intent to the filter's target user.
5669     * Otherwise, returns null.
5670     */
5671    private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent,
5672            String resolvedType, int flags, int sourceUserId) {
5673        int targetUserId = filter.getTargetUserId();
5674        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
5675                resolvedType, flags, targetUserId);
5676        if (resultTargetUser != null && isUserEnabled(targetUserId)) {
5677            // If all the matches in the target profile are suspended, return null.
5678            for (int i = resultTargetUser.size() - 1; i >= 0; i--) {
5679                if ((resultTargetUser.get(i).activityInfo.applicationInfo.flags
5680                        & ApplicationInfo.FLAG_SUSPENDED) == 0) {
5681                    return createForwardingResolveInfoUnchecked(filter, sourceUserId,
5682                            targetUserId);
5683                }
5684            }
5685        }
5686        return null;
5687    }
5688
5689    private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter,
5690            int sourceUserId, int targetUserId) {
5691        ResolveInfo forwardingResolveInfo = new ResolveInfo();
5692        long ident = Binder.clearCallingIdentity();
5693        boolean targetIsProfile;
5694        try {
5695            targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile();
5696        } finally {
5697            Binder.restoreCallingIdentity(ident);
5698        }
5699        String className;
5700        if (targetIsProfile) {
5701            className = FORWARD_INTENT_TO_MANAGED_PROFILE;
5702        } else {
5703            className = FORWARD_INTENT_TO_PARENT;
5704        }
5705        ComponentName forwardingActivityComponentName = new ComponentName(
5706                mAndroidApplication.packageName, className);
5707        ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
5708                sourceUserId);
5709        if (!targetIsProfile) {
5710            forwardingActivityInfo.showUserIcon = targetUserId;
5711            forwardingResolveInfo.noResourceId = true;
5712        }
5713        forwardingResolveInfo.activityInfo = forwardingActivityInfo;
5714        forwardingResolveInfo.priority = 0;
5715        forwardingResolveInfo.preferredOrder = 0;
5716        forwardingResolveInfo.match = 0;
5717        forwardingResolveInfo.isDefault = true;
5718        forwardingResolveInfo.filter = filter;
5719        forwardingResolveInfo.targetUserId = targetUserId;
5720        return forwardingResolveInfo;
5721    }
5722
5723    @Override
5724    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
5725            Intent[] specifics, String[] specificTypes, Intent intent,
5726            String resolvedType, int flags, int userId) {
5727        return new ParceledListSlice<>(queryIntentActivityOptionsInternal(caller, specifics,
5728                specificTypes, intent, resolvedType, flags, userId));
5729    }
5730
5731    private @NonNull List<ResolveInfo> queryIntentActivityOptionsInternal(ComponentName caller,
5732            Intent[] specifics, String[] specificTypes, Intent intent,
5733            String resolvedType, int flags, int userId) {
5734        if (!sUserManager.exists(userId)) return Collections.emptyList();
5735        flags = updateFlagsForResolve(flags, userId, intent);
5736        enforceCrossUserPermission(Binder.getCallingUid(), userId,
5737                false /* requireFullPermission */, false /* checkShell */,
5738                "query intent activity options");
5739        final String resultsAction = intent.getAction();
5740
5741        final List<ResolveInfo> results = queryIntentActivitiesInternal(intent, resolvedType, flags
5742                | PackageManager.GET_RESOLVED_FILTER, userId);
5743
5744        if (DEBUG_INTENT_MATCHING) {
5745            Log.v(TAG, "Query " + intent + ": " + results);
5746        }
5747
5748        int specificsPos = 0;
5749        int N;
5750
5751        // todo: note that the algorithm used here is O(N^2).  This
5752        // isn't a problem in our current environment, but if we start running
5753        // into situations where we have more than 5 or 10 matches then this
5754        // should probably be changed to something smarter...
5755
5756        // First we go through and resolve each of the specific items
5757        // that were supplied, taking care of removing any corresponding
5758        // duplicate items in the generic resolve list.
5759        if (specifics != null) {
5760            for (int i=0; i<specifics.length; i++) {
5761                final Intent sintent = specifics[i];
5762                if (sintent == null) {
5763                    continue;
5764                }
5765
5766                if (DEBUG_INTENT_MATCHING) {
5767                    Log.v(TAG, "Specific #" + i + ": " + sintent);
5768                }
5769
5770                String action = sintent.getAction();
5771                if (resultsAction != null && resultsAction.equals(action)) {
5772                    // If this action was explicitly requested, then don't
5773                    // remove things that have it.
5774                    action = null;
5775                }
5776
5777                ResolveInfo ri = null;
5778                ActivityInfo ai = null;
5779
5780                ComponentName comp = sintent.getComponent();
5781                if (comp == null) {
5782                    ri = resolveIntent(
5783                        sintent,
5784                        specificTypes != null ? specificTypes[i] : null,
5785                            flags, userId);
5786                    if (ri == null) {
5787                        continue;
5788                    }
5789                    if (ri == mResolveInfo) {
5790                        // ACK!  Must do something better with this.
5791                    }
5792                    ai = ri.activityInfo;
5793                    comp = new ComponentName(ai.applicationInfo.packageName,
5794                            ai.name);
5795                } else {
5796                    ai = getActivityInfo(comp, flags, userId);
5797                    if (ai == null) {
5798                        continue;
5799                    }
5800                }
5801
5802                // Look for any generic query activities that are duplicates
5803                // of this specific one, and remove them from the results.
5804                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
5805                N = results.size();
5806                int j;
5807                for (j=specificsPos; j<N; j++) {
5808                    ResolveInfo sri = results.get(j);
5809                    if ((sri.activityInfo.name.equals(comp.getClassName())
5810                            && sri.activityInfo.applicationInfo.packageName.equals(
5811                                    comp.getPackageName()))
5812                        || (action != null && sri.filter.matchAction(action))) {
5813                        results.remove(j);
5814                        if (DEBUG_INTENT_MATCHING) Log.v(
5815                            TAG, "Removing duplicate item from " + j
5816                            + " due to specific " + specificsPos);
5817                        if (ri == null) {
5818                            ri = sri;
5819                        }
5820                        j--;
5821                        N--;
5822                    }
5823                }
5824
5825                // Add this specific item to its proper place.
5826                if (ri == null) {
5827                    ri = new ResolveInfo();
5828                    ri.activityInfo = ai;
5829                }
5830                results.add(specificsPos, ri);
5831                ri.specificIndex = i;
5832                specificsPos++;
5833            }
5834        }
5835
5836        // Now we go through the remaining generic results and remove any
5837        // duplicate actions that are found here.
5838        N = results.size();
5839        for (int i=specificsPos; i<N-1; i++) {
5840            final ResolveInfo rii = results.get(i);
5841            if (rii.filter == null) {
5842                continue;
5843            }
5844
5845            // Iterate over all of the actions of this result's intent
5846            // filter...  typically this should be just one.
5847            final Iterator<String> it = rii.filter.actionsIterator();
5848            if (it == null) {
5849                continue;
5850            }
5851            while (it.hasNext()) {
5852                final String action = it.next();
5853                if (resultsAction != null && resultsAction.equals(action)) {
5854                    // If this action was explicitly requested, then don't
5855                    // remove things that have it.
5856                    continue;
5857                }
5858                for (int j=i+1; j<N; j++) {
5859                    final ResolveInfo rij = results.get(j);
5860                    if (rij.filter != null && rij.filter.hasAction(action)) {
5861                        results.remove(j);
5862                        if (DEBUG_INTENT_MATCHING) Log.v(
5863                            TAG, "Removing duplicate item from " + j
5864                            + " due to action " + action + " at " + i);
5865                        j--;
5866                        N--;
5867                    }
5868                }
5869            }
5870
5871            // If the caller didn't request filter information, drop it now
5872            // so we don't have to marshall/unmarshall it.
5873            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
5874                rii.filter = null;
5875            }
5876        }
5877
5878        // Filter out the caller activity if so requested.
5879        if (caller != null) {
5880            N = results.size();
5881            for (int i=0; i<N; i++) {
5882                ActivityInfo ainfo = results.get(i).activityInfo;
5883                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
5884                        && caller.getClassName().equals(ainfo.name)) {
5885                    results.remove(i);
5886                    break;
5887                }
5888            }
5889        }
5890
5891        // If the caller didn't request filter information,
5892        // drop them now so we don't have to
5893        // marshall/unmarshall it.
5894        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
5895            N = results.size();
5896            for (int i=0; i<N; i++) {
5897                results.get(i).filter = null;
5898            }
5899        }
5900
5901        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
5902        return results;
5903    }
5904
5905    @Override
5906    public @NonNull ParceledListSlice<ResolveInfo> queryIntentReceivers(Intent intent,
5907            String resolvedType, int flags, int userId) {
5908        return new ParceledListSlice<>(
5909                queryIntentReceiversInternal(intent, resolvedType, flags, userId));
5910    }
5911
5912    private @NonNull List<ResolveInfo> queryIntentReceiversInternal(Intent intent,
5913            String resolvedType, int flags, int userId) {
5914        if (!sUserManager.exists(userId)) return Collections.emptyList();
5915        flags = updateFlagsForResolve(flags, userId, intent);
5916        ComponentName comp = intent.getComponent();
5917        if (comp == null) {
5918            if (intent.getSelector() != null) {
5919                intent = intent.getSelector();
5920                comp = intent.getComponent();
5921            }
5922        }
5923        if (comp != null) {
5924            List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5925            ActivityInfo ai = getReceiverInfo(comp, flags, userId);
5926            if (ai != null) {
5927                ResolveInfo ri = new ResolveInfo();
5928                ri.activityInfo = ai;
5929                list.add(ri);
5930            }
5931            return list;
5932        }
5933
5934        // reader
5935        synchronized (mPackages) {
5936            String pkgName = intent.getPackage();
5937            if (pkgName == null) {
5938                return mReceivers.queryIntent(intent, resolvedType, flags, userId);
5939            }
5940            final PackageParser.Package pkg = mPackages.get(pkgName);
5941            if (pkg != null) {
5942                return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers,
5943                        userId);
5944            }
5945            return Collections.emptyList();
5946        }
5947    }
5948
5949    @Override
5950    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
5951        if (!sUserManager.exists(userId)) return null;
5952        flags = updateFlagsForResolve(flags, userId, intent);
5953        List<ResolveInfo> query = queryIntentServicesInternal(intent, resolvedType, flags, userId);
5954        if (query != null) {
5955            if (query.size() >= 1) {
5956                // If there is more than one service with the same priority,
5957                // just arbitrarily pick the first one.
5958                return query.get(0);
5959            }
5960        }
5961        return null;
5962    }
5963
5964    @Override
5965    public @NonNull ParceledListSlice<ResolveInfo> queryIntentServices(Intent intent,
5966            String resolvedType, int flags, int userId) {
5967        return new ParceledListSlice<>(
5968                queryIntentServicesInternal(intent, resolvedType, flags, userId));
5969    }
5970
5971    private @NonNull List<ResolveInfo> queryIntentServicesInternal(Intent intent,
5972            String resolvedType, int flags, int userId) {
5973        if (!sUserManager.exists(userId)) return Collections.emptyList();
5974        flags = updateFlagsForResolve(flags, userId, intent);
5975        ComponentName comp = intent.getComponent();
5976        if (comp == null) {
5977            if (intent.getSelector() != null) {
5978                intent = intent.getSelector();
5979                comp = intent.getComponent();
5980            }
5981        }
5982        if (comp != null) {
5983            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5984            final ServiceInfo si = getServiceInfo(comp, flags, userId);
5985            if (si != null) {
5986                final ResolveInfo ri = new ResolveInfo();
5987                ri.serviceInfo = si;
5988                list.add(ri);
5989            }
5990            return list;
5991        }
5992
5993        // reader
5994        synchronized (mPackages) {
5995            String pkgName = intent.getPackage();
5996            if (pkgName == null) {
5997                return mServices.queryIntent(intent, resolvedType, flags, userId);
5998            }
5999            final PackageParser.Package pkg = mPackages.get(pkgName);
6000            if (pkg != null) {
6001                return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
6002                        userId);
6003            }
6004            return Collections.emptyList();
6005        }
6006    }
6007
6008    @Override
6009    public @NonNull ParceledListSlice<ResolveInfo> queryIntentContentProviders(Intent intent,
6010            String resolvedType, int flags, int userId) {
6011        return new ParceledListSlice<>(
6012                queryIntentContentProvidersInternal(intent, resolvedType, flags, userId));
6013    }
6014
6015    private @NonNull List<ResolveInfo> queryIntentContentProvidersInternal(
6016            Intent intent, String resolvedType, int flags, int userId) {
6017        if (!sUserManager.exists(userId)) return Collections.emptyList();
6018        flags = updateFlagsForResolve(flags, userId, intent);
6019        ComponentName comp = intent.getComponent();
6020        if (comp == null) {
6021            if (intent.getSelector() != null) {
6022                intent = intent.getSelector();
6023                comp = intent.getComponent();
6024            }
6025        }
6026        if (comp != null) {
6027            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
6028            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
6029            if (pi != null) {
6030                final ResolveInfo ri = new ResolveInfo();
6031                ri.providerInfo = pi;
6032                list.add(ri);
6033            }
6034            return list;
6035        }
6036
6037        // reader
6038        synchronized (mPackages) {
6039            String pkgName = intent.getPackage();
6040            if (pkgName == null) {
6041                return mProviders.queryIntent(intent, resolvedType, flags, userId);
6042            }
6043            final PackageParser.Package pkg = mPackages.get(pkgName);
6044            if (pkg != null) {
6045                return mProviders.queryIntentForPackage(
6046                        intent, resolvedType, flags, pkg.providers, userId);
6047            }
6048            return Collections.emptyList();
6049        }
6050    }
6051
6052    @Override
6053    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
6054        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
6055        flags = updateFlagsForPackage(flags, userId, null);
6056        final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0;
6057        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6058                true /* requireFullPermission */, false /* checkShell */,
6059                "get installed packages");
6060
6061        // writer
6062        synchronized (mPackages) {
6063            ArrayList<PackageInfo> list;
6064            if (listUninstalled) {
6065                list = new ArrayList<PackageInfo>(mSettings.mPackages.size());
6066                for (PackageSetting ps : mSettings.mPackages.values()) {
6067                    final PackageInfo pi;
6068                    if (ps.pkg != null) {
6069                        pi = generatePackageInfo(ps, flags, userId);
6070                    } else {
6071                        pi = generatePackageInfo(ps, flags, userId);
6072                    }
6073                    if (pi != null) {
6074                        list.add(pi);
6075                    }
6076                }
6077            } else {
6078                list = new ArrayList<PackageInfo>(mPackages.size());
6079                for (PackageParser.Package p : mPackages.values()) {
6080                    final PackageInfo pi =
6081                            generatePackageInfo((PackageSetting)p.mExtras, flags, userId);
6082                    if (pi != null) {
6083                        list.add(pi);
6084                    }
6085                }
6086            }
6087
6088            return new ParceledListSlice<PackageInfo>(list);
6089        }
6090    }
6091
6092    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
6093            String[] permissions, boolean[] tmp, int flags, int userId) {
6094        int numMatch = 0;
6095        final PermissionsState permissionsState = ps.getPermissionsState();
6096        for (int i=0; i<permissions.length; i++) {
6097            final String permission = permissions[i];
6098            if (permissionsState.hasPermission(permission, userId)) {
6099                tmp[i] = true;
6100                numMatch++;
6101            } else {
6102                tmp[i] = false;
6103            }
6104        }
6105        if (numMatch == 0) {
6106            return;
6107        }
6108        final PackageInfo pi;
6109        if (ps.pkg != null) {
6110            pi = generatePackageInfo(ps, flags, userId);
6111        } else {
6112            pi = generatePackageInfo(ps, flags, userId);
6113        }
6114        // The above might return null in cases of uninstalled apps or install-state
6115        // skew across users/profiles.
6116        if (pi != null) {
6117            if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
6118                if (numMatch == permissions.length) {
6119                    pi.requestedPermissions = permissions;
6120                } else {
6121                    pi.requestedPermissions = new String[numMatch];
6122                    numMatch = 0;
6123                    for (int i=0; i<permissions.length; i++) {
6124                        if (tmp[i]) {
6125                            pi.requestedPermissions[numMatch] = permissions[i];
6126                            numMatch++;
6127                        }
6128                    }
6129                }
6130            }
6131            list.add(pi);
6132        }
6133    }
6134
6135    @Override
6136    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
6137            String[] permissions, int flags, int userId) {
6138        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
6139        flags = updateFlagsForPackage(flags, userId, permissions);
6140        final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0;
6141
6142        // writer
6143        synchronized (mPackages) {
6144            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
6145            boolean[] tmpBools = new boolean[permissions.length];
6146            if (listUninstalled) {
6147                for (PackageSetting ps : mSettings.mPackages.values()) {
6148                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId);
6149                }
6150            } else {
6151                for (PackageParser.Package pkg : mPackages.values()) {
6152                    PackageSetting ps = (PackageSetting)pkg.mExtras;
6153                    if (ps != null) {
6154                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
6155                                userId);
6156                    }
6157                }
6158            }
6159
6160            return new ParceledListSlice<PackageInfo>(list);
6161        }
6162    }
6163
6164    @Override
6165    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
6166        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
6167        flags = updateFlagsForApplication(flags, userId, null);
6168        final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0;
6169
6170        // writer
6171        synchronized (mPackages) {
6172            ArrayList<ApplicationInfo> list;
6173            if (listUninstalled) {
6174                list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size());
6175                for (PackageSetting ps : mSettings.mPackages.values()) {
6176                    ApplicationInfo ai;
6177                    if (ps.pkg != null) {
6178                        ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
6179                                ps.readUserState(userId), userId);
6180                    } else {
6181                        ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId);
6182                    }
6183                    if (ai != null) {
6184                        list.add(ai);
6185                    }
6186                }
6187            } else {
6188                list = new ArrayList<ApplicationInfo>(mPackages.size());
6189                for (PackageParser.Package p : mPackages.values()) {
6190                    if (p.mExtras != null) {
6191                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
6192                                ((PackageSetting)p.mExtras).readUserState(userId), userId);
6193                        if (ai != null) {
6194                            list.add(ai);
6195                        }
6196                    }
6197                }
6198            }
6199
6200            return new ParceledListSlice<ApplicationInfo>(list);
6201        }
6202    }
6203
6204    @Override
6205    public ParceledListSlice<EphemeralApplicationInfo> getEphemeralApplications(int userId) {
6206        if (DISABLE_EPHEMERAL_APPS) {
6207            return null;
6208        }
6209
6210        mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS,
6211                "getEphemeralApplications");
6212        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6213                true /* requireFullPermission */, false /* checkShell */,
6214                "getEphemeralApplications");
6215        synchronized (mPackages) {
6216            List<EphemeralApplicationInfo> ephemeralApps = mEphemeralApplicationRegistry
6217                    .getEphemeralApplicationsLPw(userId);
6218            if (ephemeralApps != null) {
6219                return new ParceledListSlice<>(ephemeralApps);
6220            }
6221        }
6222        return null;
6223    }
6224
6225    @Override
6226    public boolean isEphemeralApplication(String packageName, int userId) {
6227        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6228                true /* requireFullPermission */, false /* checkShell */,
6229                "isEphemeral");
6230        if (DISABLE_EPHEMERAL_APPS) {
6231            return false;
6232        }
6233
6234        if (!isCallerSameApp(packageName)) {
6235            return false;
6236        }
6237        synchronized (mPackages) {
6238            PackageParser.Package pkg = mPackages.get(packageName);
6239            if (pkg != null) {
6240                return pkg.applicationInfo.isEphemeralApp();
6241            }
6242        }
6243        return false;
6244    }
6245
6246    @Override
6247    public byte[] getEphemeralApplicationCookie(String packageName, int userId) {
6248        if (DISABLE_EPHEMERAL_APPS) {
6249            return null;
6250        }
6251
6252        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6253                true /* requireFullPermission */, false /* checkShell */,
6254                "getCookie");
6255        if (!isCallerSameApp(packageName)) {
6256            return null;
6257        }
6258        synchronized (mPackages) {
6259            return mEphemeralApplicationRegistry.getEphemeralApplicationCookieLPw(
6260                    packageName, userId);
6261        }
6262    }
6263
6264    @Override
6265    public boolean setEphemeralApplicationCookie(String packageName, byte[] cookie, int userId) {
6266        if (DISABLE_EPHEMERAL_APPS) {
6267            return true;
6268        }
6269
6270        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6271                true /* requireFullPermission */, true /* checkShell */,
6272                "setCookie");
6273        if (!isCallerSameApp(packageName)) {
6274            return false;
6275        }
6276        synchronized (mPackages) {
6277            return mEphemeralApplicationRegistry.setEphemeralApplicationCookieLPw(
6278                    packageName, cookie, userId);
6279        }
6280    }
6281
6282    @Override
6283    public Bitmap getEphemeralApplicationIcon(String packageName, int userId) {
6284        if (DISABLE_EPHEMERAL_APPS) {
6285            return null;
6286        }
6287
6288        mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS,
6289                "getEphemeralApplicationIcon");
6290        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6291                true /* requireFullPermission */, false /* checkShell */,
6292                "getEphemeralApplicationIcon");
6293        synchronized (mPackages) {
6294            return mEphemeralApplicationRegistry.getEphemeralApplicationIconLPw(
6295                    packageName, userId);
6296        }
6297    }
6298
6299    private boolean isCallerSameApp(String packageName) {
6300        PackageParser.Package pkg = mPackages.get(packageName);
6301        return pkg != null
6302                && UserHandle.getAppId(Binder.getCallingUid()) == pkg.applicationInfo.uid;
6303    }
6304
6305    @Override
6306    public @NonNull ParceledListSlice<ApplicationInfo> getPersistentApplications(int flags) {
6307        return new ParceledListSlice<>(getPersistentApplicationsInternal(flags));
6308    }
6309
6310    private @NonNull List<ApplicationInfo> getPersistentApplicationsInternal(int flags) {
6311        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
6312
6313        // reader
6314        synchronized (mPackages) {
6315            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
6316            final int userId = UserHandle.getCallingUserId();
6317            while (i.hasNext()) {
6318                final PackageParser.Package p = i.next();
6319                if (p.applicationInfo == null) continue;
6320
6321                final boolean matchesUnaware = ((flags & MATCH_DIRECT_BOOT_UNAWARE) != 0)
6322                        && !p.applicationInfo.isDirectBootAware();
6323                final boolean matchesAware = ((flags & MATCH_DIRECT_BOOT_AWARE) != 0)
6324                        && p.applicationInfo.isDirectBootAware();
6325
6326                if ((p.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0
6327                        && (!mSafeMode || isSystemApp(p))
6328                        && (matchesUnaware || matchesAware)) {
6329                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
6330                    if (ps != null) {
6331                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
6332                                ps.readUserState(userId), userId);
6333                        if (ai != null) {
6334                            finalList.add(ai);
6335                        }
6336                    }
6337                }
6338            }
6339        }
6340
6341        return finalList;
6342    }
6343
6344    @Override
6345    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
6346        if (!sUserManager.exists(userId)) return null;
6347        flags = updateFlagsForComponent(flags, userId, name);
6348        // reader
6349        synchronized (mPackages) {
6350            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
6351            PackageSetting ps = provider != null
6352                    ? mSettings.mPackages.get(provider.owner.packageName)
6353                    : null;
6354            return ps != null
6355                    && mSettings.isEnabledAndMatchLPr(provider.info, flags, userId)
6356                    ? PackageParser.generateProviderInfo(provider, flags,
6357                            ps.readUserState(userId), userId)
6358                    : null;
6359        }
6360    }
6361
6362    /**
6363     * @deprecated
6364     */
6365    @Deprecated
6366    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
6367        // reader
6368        synchronized (mPackages) {
6369            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
6370                    .entrySet().iterator();
6371            final int userId = UserHandle.getCallingUserId();
6372            while (i.hasNext()) {
6373                Map.Entry<String, PackageParser.Provider> entry = i.next();
6374                PackageParser.Provider p = entry.getValue();
6375                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
6376
6377                if (ps != null && p.syncable
6378                        && (!mSafeMode || (p.info.applicationInfo.flags
6379                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
6380                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
6381                            ps.readUserState(userId), userId);
6382                    if (info != null) {
6383                        outNames.add(entry.getKey());
6384                        outInfo.add(info);
6385                    }
6386                }
6387            }
6388        }
6389    }
6390
6391    @Override
6392    public @NonNull ParceledListSlice<ProviderInfo> queryContentProviders(String processName,
6393            int uid, int flags) {
6394        final int userId = processName != null ? UserHandle.getUserId(uid)
6395                : UserHandle.getCallingUserId();
6396        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
6397        flags = updateFlagsForComponent(flags, userId, processName);
6398
6399        ArrayList<ProviderInfo> finalList = null;
6400        // reader
6401        synchronized (mPackages) {
6402            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
6403            while (i.hasNext()) {
6404                final PackageParser.Provider p = i.next();
6405                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
6406                if (ps != null && p.info.authority != null
6407                        && (processName == null
6408                                || (p.info.processName.equals(processName)
6409                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
6410                        && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
6411                    if (finalList == null) {
6412                        finalList = new ArrayList<ProviderInfo>(3);
6413                    }
6414                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
6415                            ps.readUserState(userId), userId);
6416                    if (info != null) {
6417                        finalList.add(info);
6418                    }
6419                }
6420            }
6421        }
6422
6423        if (finalList != null) {
6424            Collections.sort(finalList, mProviderInitOrderSorter);
6425            return new ParceledListSlice<ProviderInfo>(finalList);
6426        }
6427
6428        return ParceledListSlice.emptyList();
6429    }
6430
6431    @Override
6432    public InstrumentationInfo getInstrumentationInfo(ComponentName name, int flags) {
6433        // reader
6434        synchronized (mPackages) {
6435            final PackageParser.Instrumentation i = mInstrumentation.get(name);
6436            return PackageParser.generateInstrumentationInfo(i, flags);
6437        }
6438    }
6439
6440    @Override
6441    public @NonNull ParceledListSlice<InstrumentationInfo> queryInstrumentation(
6442            String targetPackage, int flags) {
6443        return new ParceledListSlice<>(queryInstrumentationInternal(targetPackage, flags));
6444    }
6445
6446    private @NonNull List<InstrumentationInfo> queryInstrumentationInternal(String targetPackage,
6447            int flags) {
6448        ArrayList<InstrumentationInfo> finalList = new ArrayList<InstrumentationInfo>();
6449
6450        // reader
6451        synchronized (mPackages) {
6452            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
6453            while (i.hasNext()) {
6454                final PackageParser.Instrumentation p = i.next();
6455                if (targetPackage == null
6456                        || targetPackage.equals(p.info.targetPackage)) {
6457                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
6458                            flags);
6459                    if (ii != null) {
6460                        finalList.add(ii);
6461                    }
6462                }
6463            }
6464        }
6465
6466        return finalList;
6467    }
6468
6469    private void createIdmapsForPackageLI(PackageParser.Package pkg) {
6470        ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName);
6471        if (overlays == null) {
6472            Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages");
6473            return;
6474        }
6475        for (PackageParser.Package opkg : overlays.values()) {
6476            // Not much to do if idmap fails: we already logged the error
6477            // and we certainly don't want to abort installation of pkg simply
6478            // because an overlay didn't fit properly. For these reasons,
6479            // ignore the return value of createIdmapForPackagePairLI.
6480            createIdmapForPackagePairLI(pkg, opkg);
6481        }
6482    }
6483
6484    private boolean createIdmapForPackagePairLI(PackageParser.Package pkg,
6485            PackageParser.Package opkg) {
6486        if (!opkg.mTrustedOverlay) {
6487            Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " +
6488                    opkg.baseCodePath + ": overlay not trusted");
6489            return false;
6490        }
6491        ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName);
6492        if (overlaySet == null) {
6493            Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " +
6494                    opkg.baseCodePath + " but target package has no known overlays");
6495            return false;
6496        }
6497        final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
6498        // TODO: generate idmap for split APKs
6499        try {
6500            mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid);
6501        } catch (InstallerException e) {
6502            Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and "
6503                    + opkg.baseCodePath);
6504            return false;
6505        }
6506        PackageParser.Package[] overlayArray =
6507            overlaySet.values().toArray(new PackageParser.Package[0]);
6508        Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() {
6509            public int compare(PackageParser.Package p1, PackageParser.Package p2) {
6510                return p1.mOverlayPriority - p2.mOverlayPriority;
6511            }
6512        };
6513        Arrays.sort(overlayArray, cmp);
6514
6515        pkg.applicationInfo.resourceDirs = new String[overlayArray.length];
6516        int i = 0;
6517        for (PackageParser.Package p : overlayArray) {
6518            pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath;
6519        }
6520        return true;
6521    }
6522
6523    private void scanDirTracedLI(File dir, final int parseFlags, int scanFlags, long currentTime) {
6524        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir");
6525        try {
6526            scanDirLI(dir, parseFlags, scanFlags, currentTime);
6527        } finally {
6528            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6529        }
6530    }
6531
6532    private void scanDirLI(File dir, final int parseFlags, int scanFlags, long currentTime) {
6533        final File[] files = dir.listFiles();
6534        if (ArrayUtils.isEmpty(files)) {
6535            Log.d(TAG, "No files in app dir " + dir);
6536            return;
6537        }
6538
6539        if (DEBUG_PACKAGE_SCANNING) {
6540            Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags
6541                    + " flags=0x" + Integer.toHexString(parseFlags));
6542        }
6543
6544        for (File file : files) {
6545            final boolean isPackage = (isApkFile(file) || file.isDirectory())
6546                    && !PackageInstallerService.isStageName(file.getName());
6547            if (!isPackage) {
6548                // Ignore entries which are not packages
6549                continue;
6550            }
6551            try {
6552                scanPackageTracedLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK,
6553                        scanFlags, currentTime, null);
6554            } catch (PackageManagerException e) {
6555                Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage());
6556
6557                // Delete invalid userdata apps
6558                if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
6559                        e.error == PackageManager.INSTALL_FAILED_INVALID_APK) {
6560                    logCriticalInfo(Log.WARN, "Deleting invalid package at " + file);
6561                    removeCodePathLI(file);
6562                }
6563            }
6564        }
6565    }
6566
6567    private static File getSettingsProblemFile() {
6568        File dataDir = Environment.getDataDirectory();
6569        File systemDir = new File(dataDir, "system");
6570        File fname = new File(systemDir, "uiderrors.txt");
6571        return fname;
6572    }
6573
6574    static void reportSettingsProblem(int priority, String msg) {
6575        logCriticalInfo(priority, msg);
6576    }
6577
6578    static void logCriticalInfo(int priority, String msg) {
6579        Slog.println(priority, TAG, msg);
6580        EventLogTags.writePmCriticalInfo(msg);
6581        try {
6582            File fname = getSettingsProblemFile();
6583            FileOutputStream out = new FileOutputStream(fname, true);
6584            PrintWriter pw = new FastPrintWriter(out);
6585            SimpleDateFormat formatter = new SimpleDateFormat();
6586            String dateString = formatter.format(new Date(System.currentTimeMillis()));
6587            pw.println(dateString + ": " + msg);
6588            pw.close();
6589            FileUtils.setPermissions(
6590                    fname.toString(),
6591                    FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
6592                    -1, -1);
6593        } catch (java.io.IOException e) {
6594        }
6595    }
6596
6597    private void collectCertificatesLI(PackageSetting ps, PackageParser.Package pkg, File srcFile,
6598            final int policyFlags) throws PackageManagerException {
6599        if (ps != null
6600                && ps.codePath.equals(srcFile)
6601                && ps.timeStamp == srcFile.lastModified()
6602                && !isCompatSignatureUpdateNeeded(pkg)
6603                && !isRecoverSignatureUpdateNeeded(pkg)) {
6604            long mSigningKeySetId = ps.keySetData.getProperSigningKeySet();
6605            KeySetManagerService ksms = mSettings.mKeySetManagerService;
6606            ArraySet<PublicKey> signingKs;
6607            synchronized (mPackages) {
6608                signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId);
6609            }
6610            if (ps.signatures.mSignatures != null
6611                    && ps.signatures.mSignatures.length != 0
6612                    && signingKs != null) {
6613                // Optimization: reuse the existing cached certificates
6614                // if the package appears to be unchanged.
6615                pkg.mSignatures = ps.signatures.mSignatures;
6616                pkg.mSigningKeys = signingKs;
6617                return;
6618            }
6619
6620            Slog.w(TAG, "PackageSetting for " + ps.name
6621                    + " is missing signatures.  Collecting certs again to recover them.");
6622        } else {
6623            Log.i(TAG, srcFile.toString() + " changed; collecting certs");
6624        }
6625
6626        try {
6627            PackageParser.collectCertificates(pkg, policyFlags);
6628        } catch (PackageParserException e) {
6629            throw PackageManagerException.from(e);
6630        }
6631    }
6632
6633    /**
6634     *  Traces a package scan.
6635     *  @see #scanPackageLI(File, int, int, long, UserHandle)
6636     */
6637    private PackageParser.Package scanPackageTracedLI(File scanFile, final int parseFlags,
6638            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
6639        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage");
6640        try {
6641            return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user);
6642        } finally {
6643            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6644        }
6645    }
6646
6647    /**
6648     *  Scans a package and returns the newly parsed package.
6649     *  Returns {@code null} in case of errors and the error code is stored in mLastScanError
6650     */
6651    private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags,
6652            long currentTime, UserHandle user) throws PackageManagerException {
6653        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
6654        PackageParser pp = new PackageParser();
6655        pp.setSeparateProcesses(mSeparateProcesses);
6656        pp.setOnlyCoreApps(mOnlyCore);
6657        pp.setDisplayMetrics(mMetrics);
6658
6659        if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) {
6660            parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY;
6661        }
6662
6663        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
6664        final PackageParser.Package pkg;
6665        try {
6666            pkg = pp.parsePackage(scanFile, parseFlags);
6667        } catch (PackageParserException e) {
6668            throw PackageManagerException.from(e);
6669        } finally {
6670            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6671        }
6672
6673        return scanPackageLI(pkg, scanFile, parseFlags, scanFlags, currentTime, user);
6674    }
6675
6676    /**
6677     *  Scans a package and returns the newly parsed package.
6678     *  @throws PackageManagerException on a parse error.
6679     */
6680    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, File scanFile,
6681            final int policyFlags, int scanFlags, long currentTime, UserHandle user)
6682            throws PackageManagerException {
6683        // If the package has children and this is the first dive in the function
6684        // we scan the package with the SCAN_CHECK_ONLY flag set to see whether all
6685        // packages (parent and children) would be successfully scanned before the
6686        // actual scan since scanning mutates internal state and we want to atomically
6687        // install the package and its children.
6688        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
6689            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
6690                scanFlags |= SCAN_CHECK_ONLY;
6691            }
6692        } else {
6693            scanFlags &= ~SCAN_CHECK_ONLY;
6694        }
6695
6696        // Scan the parent
6697        PackageParser.Package scannedPkg = scanPackageInternalLI(pkg, scanFile, policyFlags,
6698                scanFlags, currentTime, user);
6699
6700        // Scan the children
6701        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
6702        for (int i = 0; i < childCount; i++) {
6703            PackageParser.Package childPackage = pkg.childPackages.get(i);
6704            scanPackageInternalLI(childPackage, scanFile, policyFlags, scanFlags,
6705                    currentTime, user);
6706        }
6707
6708
6709        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
6710            return scanPackageLI(pkg, scanFile, policyFlags, scanFlags, currentTime, user);
6711        }
6712
6713        return scannedPkg;
6714    }
6715
6716    /**
6717     *  Scans a package and returns the newly parsed package.
6718     *  @throws PackageManagerException on a parse error.
6719     */
6720    private PackageParser.Package scanPackageInternalLI(PackageParser.Package pkg, File scanFile,
6721            int policyFlags, int scanFlags, long currentTime, UserHandle user)
6722            throws PackageManagerException {
6723        PackageSetting ps = null;
6724        PackageSetting updatedPkg;
6725        // reader
6726        synchronized (mPackages) {
6727            // Look to see if we already know about this package.
6728            String oldName = mSettings.mRenamedPackages.get(pkg.packageName);
6729            if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
6730                // This package has been renamed to its original name.  Let's
6731                // use that.
6732                ps = mSettings.peekPackageLPr(oldName);
6733            }
6734            // If there was no original package, see one for the real package name.
6735            if (ps == null) {
6736                ps = mSettings.peekPackageLPr(pkg.packageName);
6737            }
6738            // Check to see if this package could be hiding/updating a system
6739            // package.  Must look for it either under the original or real
6740            // package name depending on our state.
6741            updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName);
6742            if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg);
6743
6744            // If this is a package we don't know about on the system partition, we
6745            // may need to remove disabled child packages on the system partition
6746            // or may need to not add child packages if the parent apk is updated
6747            // on the data partition and no longer defines this child package.
6748            if ((policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) {
6749                // If this is a parent package for an updated system app and this system
6750                // app got an OTA update which no longer defines some of the child packages
6751                // we have to prune them from the disabled system packages.
6752                PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName);
6753                if (disabledPs != null) {
6754                    final int scannedChildCount = (pkg.childPackages != null)
6755                            ? pkg.childPackages.size() : 0;
6756                    final int disabledChildCount = disabledPs.childPackageNames != null
6757                            ? disabledPs.childPackageNames.size() : 0;
6758                    for (int i = 0; i < disabledChildCount; i++) {
6759                        String disabledChildPackageName = disabledPs.childPackageNames.get(i);
6760                        boolean disabledPackageAvailable = false;
6761                        for (int j = 0; j < scannedChildCount; j++) {
6762                            PackageParser.Package childPkg = pkg.childPackages.get(j);
6763                            if (childPkg.packageName.equals(disabledChildPackageName)) {
6764                                disabledPackageAvailable = true;
6765                                break;
6766                            }
6767                         }
6768                         if (!disabledPackageAvailable) {
6769                             mSettings.removeDisabledSystemPackageLPw(disabledChildPackageName);
6770                         }
6771                    }
6772                }
6773            }
6774        }
6775
6776        boolean updatedPkgBetter = false;
6777        // First check if this is a system package that may involve an update
6778        if (updatedPkg != null && (policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) {
6779            // If new package is not located in "/system/priv-app" (e.g. due to an OTA),
6780            // it needs to drop FLAG_PRIVILEGED.
6781            if (locationIsPrivileged(scanFile)) {
6782                updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
6783            } else {
6784                updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
6785            }
6786
6787            if (ps != null && !ps.codePath.equals(scanFile)) {
6788                // The path has changed from what was last scanned...  check the
6789                // version of the new path against what we have stored to determine
6790                // what to do.
6791                if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath);
6792                if (pkg.mVersionCode <= ps.versionCode) {
6793                    // The system package has been updated and the code path does not match
6794                    // Ignore entry. Skip it.
6795                    if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile
6796                            + " ignored: updated version " + ps.versionCode
6797                            + " better than this " + pkg.mVersionCode);
6798                    if (!updatedPkg.codePath.equals(scanFile)) {
6799                        Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg "
6800                                + ps.name + " changing from " + updatedPkg.codePathString
6801                                + " to " + scanFile);
6802                        updatedPkg.codePath = scanFile;
6803                        updatedPkg.codePathString = scanFile.toString();
6804                        updatedPkg.resourcePath = scanFile;
6805                        updatedPkg.resourcePathString = scanFile.toString();
6806                    }
6807                    updatedPkg.pkg = pkg;
6808                    updatedPkg.versionCode = pkg.mVersionCode;
6809
6810                    // Update the disabled system child packages to point to the package too.
6811                    final int childCount = updatedPkg.childPackageNames != null
6812                            ? updatedPkg.childPackageNames.size() : 0;
6813                    for (int i = 0; i < childCount; i++) {
6814                        String childPackageName = updatedPkg.childPackageNames.get(i);
6815                        PackageSetting updatedChildPkg = mSettings.getDisabledSystemPkgLPr(
6816                                childPackageName);
6817                        if (updatedChildPkg != null) {
6818                            updatedChildPkg.pkg = pkg;
6819                            updatedChildPkg.versionCode = pkg.mVersionCode;
6820                        }
6821                    }
6822
6823                    throw new PackageManagerException(Log.WARN, "Package " + ps.name + " at "
6824                            + scanFile + " ignored: updated version " + ps.versionCode
6825                            + " better than this " + pkg.mVersionCode);
6826                } else {
6827                    // The current app on the system partition is better than
6828                    // what we have updated to on the data partition; switch
6829                    // back to the system partition version.
6830                    // At this point, its safely assumed that package installation for
6831                    // apps in system partition will go through. If not there won't be a working
6832                    // version of the app
6833                    // writer
6834                    synchronized (mPackages) {
6835                        // Just remove the loaded entries from package lists.
6836                        mPackages.remove(ps.name);
6837                    }
6838
6839                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
6840                            + " reverting from " + ps.codePathString
6841                            + ": new version " + pkg.mVersionCode
6842                            + " better than installed " + ps.versionCode);
6843
6844                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
6845                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
6846                    synchronized (mInstallLock) {
6847                        args.cleanUpResourcesLI();
6848                    }
6849                    synchronized (mPackages) {
6850                        mSettings.enableSystemPackageLPw(ps.name);
6851                    }
6852                    updatedPkgBetter = true;
6853                }
6854            }
6855        }
6856
6857        if (updatedPkg != null) {
6858            // An updated system app will not have the PARSE_IS_SYSTEM flag set
6859            // initially
6860            policyFlags |= PackageParser.PARSE_IS_SYSTEM;
6861
6862            // An updated privileged app will not have the PARSE_IS_PRIVILEGED
6863            // flag set initially
6864            if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
6865                policyFlags |= PackageParser.PARSE_IS_PRIVILEGED;
6866            }
6867        }
6868
6869        // Verify certificates against what was last scanned
6870        collectCertificatesLI(ps, pkg, scanFile, policyFlags);
6871
6872        /*
6873         * A new system app appeared, but we already had a non-system one of the
6874         * same name installed earlier.
6875         */
6876        boolean shouldHideSystemApp = false;
6877        if (updatedPkg == null && ps != null
6878                && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) {
6879            /*
6880             * Check to make sure the signatures match first. If they don't,
6881             * wipe the installed application and its data.
6882             */
6883            if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures)
6884                    != PackageManager.SIGNATURE_MATCH) {
6885                logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but"
6886                        + " signatures don't match existing userdata copy; removing");
6887                try (PackageFreezer freezer = freezePackage(pkg.packageName,
6888                        "scanPackageInternalLI")) {
6889                    deletePackageLIF(pkg.packageName, null, true, null, 0, null, false, null);
6890                }
6891                ps = null;
6892            } else {
6893                /*
6894                 * If the newly-added system app is an older version than the
6895                 * already installed version, hide it. It will be scanned later
6896                 * and re-added like an update.
6897                 */
6898                if (pkg.mVersionCode <= ps.versionCode) {
6899                    shouldHideSystemApp = true;
6900                    logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile
6901                            + " but new version " + pkg.mVersionCode + " better than installed "
6902                            + ps.versionCode + "; hiding system");
6903                } else {
6904                    /*
6905                     * The newly found system app is a newer version that the
6906                     * one previously installed. Simply remove the
6907                     * already-installed application and replace it with our own
6908                     * while keeping the application data.
6909                     */
6910                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
6911                            + " reverting from " + ps.codePathString + ": new version "
6912                            + pkg.mVersionCode + " better than installed " + ps.versionCode);
6913                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
6914                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
6915                    synchronized (mInstallLock) {
6916                        args.cleanUpResourcesLI();
6917                    }
6918                }
6919            }
6920        }
6921
6922        // The apk is forward locked (not public) if its code and resources
6923        // are kept in different files. (except for app in either system or
6924        // vendor path).
6925        // TODO grab this value from PackageSettings
6926        if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
6927            if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
6928                policyFlags |= PackageParser.PARSE_FORWARD_LOCK;
6929            }
6930        }
6931
6932        // TODO: extend to support forward-locked splits
6933        String resourcePath = null;
6934        String baseResourcePath = null;
6935        if ((policyFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) {
6936            if (ps != null && ps.resourcePathString != null) {
6937                resourcePath = ps.resourcePathString;
6938                baseResourcePath = ps.resourcePathString;
6939            } else {
6940                // Should not happen at all. Just log an error.
6941                Slog.e(TAG, "Resource path not set for package " + pkg.packageName);
6942            }
6943        } else {
6944            resourcePath = pkg.codePath;
6945            baseResourcePath = pkg.baseCodePath;
6946        }
6947
6948        // Set application objects path explicitly.
6949        pkg.setApplicationVolumeUuid(pkg.volumeUuid);
6950        pkg.setApplicationInfoCodePath(pkg.codePath);
6951        pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
6952        pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
6953        pkg.setApplicationInfoResourcePath(resourcePath);
6954        pkg.setApplicationInfoBaseResourcePath(baseResourcePath);
6955        pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
6956
6957        // Note that we invoke the following method only if we are about to unpack an application
6958        PackageParser.Package scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags
6959                | SCAN_UPDATE_SIGNATURE, currentTime, user);
6960
6961        /*
6962         * If the system app should be overridden by a previously installed
6963         * data, hide the system app now and let the /data/app scan pick it up
6964         * again.
6965         */
6966        if (shouldHideSystemApp) {
6967            synchronized (mPackages) {
6968                mSettings.disableSystemPackageLPw(pkg.packageName, true);
6969            }
6970        }
6971
6972        return scannedPkg;
6973    }
6974
6975    private static String fixProcessName(String defProcessName,
6976            String processName, int uid) {
6977        if (processName == null) {
6978            return defProcessName;
6979        }
6980        return processName;
6981    }
6982
6983    private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg)
6984            throws PackageManagerException {
6985        if (pkgSetting.signatures.mSignatures != null) {
6986            // Already existing package. Make sure signatures match
6987            boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures)
6988                    == PackageManager.SIGNATURE_MATCH;
6989            if (!match) {
6990                match = compareSignaturesCompat(pkgSetting.signatures, pkg)
6991                        == PackageManager.SIGNATURE_MATCH;
6992            }
6993            if (!match) {
6994                match = compareSignaturesRecover(pkgSetting.signatures, pkg)
6995                        == PackageManager.SIGNATURE_MATCH;
6996            }
6997            if (!match) {
6998                throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
6999                        + pkg.packageName + " signatures do not match the "
7000                        + "previously installed version; ignoring!");
7001            }
7002        }
7003
7004        // Check for shared user signatures
7005        if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
7006            // Already existing package. Make sure signatures match
7007            boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
7008                    pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
7009            if (!match) {
7010                match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg)
7011                        == PackageManager.SIGNATURE_MATCH;
7012            }
7013            if (!match) {
7014                match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg)
7015                        == PackageManager.SIGNATURE_MATCH;
7016            }
7017            if (!match) {
7018                throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
7019                        "Package " + pkg.packageName
7020                        + " has no signatures that match those in shared user "
7021                        + pkgSetting.sharedUser.name + "; ignoring!");
7022            }
7023        }
7024    }
7025
7026    /**
7027     * Enforces that only the system UID or root's UID can call a method exposed
7028     * via Binder.
7029     *
7030     * @param message used as message if SecurityException is thrown
7031     * @throws SecurityException if the caller is not system or root
7032     */
7033    private static final void enforceSystemOrRoot(String message) {
7034        final int uid = Binder.getCallingUid();
7035        if (uid != Process.SYSTEM_UID && uid != 0) {
7036            throw new SecurityException(message);
7037        }
7038    }
7039
7040    @Override
7041    public void performFstrimIfNeeded() {
7042        enforceSystemOrRoot("Only the system can request fstrim");
7043
7044        // Before everything else, see whether we need to fstrim.
7045        try {
7046            IMountService ms = PackageHelper.getMountService();
7047            if (ms != null) {
7048                final boolean isUpgrade = isUpgrade();
7049                boolean doTrim = isUpgrade;
7050                if (doTrim) {
7051                    Slog.w(TAG, "Running disk maintenance immediately due to system update");
7052                } else {
7053                    final long interval = android.provider.Settings.Global.getLong(
7054                            mContext.getContentResolver(),
7055                            android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL,
7056                            DEFAULT_MANDATORY_FSTRIM_INTERVAL);
7057                    if (interval > 0) {
7058                        final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance();
7059                        if (timeSinceLast > interval) {
7060                            doTrim = true;
7061                            Slog.w(TAG, "No disk maintenance in " + timeSinceLast
7062                                    + "; running immediately");
7063                        }
7064                    }
7065                }
7066                if (doTrim) {
7067                    if (!isFirstBoot()) {
7068                        try {
7069                            ActivityManagerNative.getDefault().showBootMessage(
7070                                    mContext.getResources().getString(
7071                                            R.string.android_upgrading_fstrim), true);
7072                        } catch (RemoteException e) {
7073                        }
7074                    }
7075                    ms.runMaintenance();
7076                }
7077            } else {
7078                Slog.e(TAG, "Mount service unavailable!");
7079            }
7080        } catch (RemoteException e) {
7081            // Can't happen; MountService is local
7082        }
7083    }
7084
7085    @Override
7086    public void updatePackagesIfNeeded() {
7087        enforceSystemOrRoot("Only the system can request package update");
7088
7089        // We need to re-extract after an OTA.
7090        boolean causeUpgrade = isUpgrade();
7091
7092        // First boot or factory reset.
7093        // Note: we also handle devices that are upgrading to N right now as if it is their
7094        //       first boot, as they do not have profile data.
7095        boolean causeFirstBoot = isFirstBoot() || mIsPreNUpgrade;
7096
7097        // We need to re-extract after a pruned cache, as AoT-ed files will be out of date.
7098        boolean causePrunedCache = VMRuntime.didPruneDalvikCache();
7099
7100        if (!causeUpgrade && !causeFirstBoot && !causePrunedCache) {
7101            return;
7102        }
7103
7104        List<PackageParser.Package> pkgs;
7105        synchronized (mPackages) {
7106            pkgs = PackageManagerServiceUtils.getPackagesForDexopt(mPackages.values(), this);
7107        }
7108
7109        final long startTime = System.nanoTime();
7110        final int[] stats = performDexOptUpgrade(pkgs, mIsPreNUpgrade /* showDialog */,
7111                    getCompilerFilterForReason(causeFirstBoot ? REASON_FIRST_BOOT : REASON_BOOT));
7112
7113        final int elapsedTimeSeconds =
7114                (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - startTime);
7115
7116        MetricsLogger.histogram(mContext, "opt_dialog_num_dexopted", stats[0]);
7117        MetricsLogger.histogram(mContext, "opt_dialog_num_skipped", stats[1]);
7118        MetricsLogger.histogram(mContext, "opt_dialog_num_failed", stats[2]);
7119        MetricsLogger.histogram(mContext, "opt_dialog_num_total", getOptimizablePackages().size());
7120        MetricsLogger.histogram(mContext, "opt_dialog_time_s", elapsedTimeSeconds);
7121    }
7122
7123    /**
7124     * Performs dexopt on the set of packages in {@code packages} and returns an int array
7125     * containing statistics about the invocation. The array consists of three elements,
7126     * which are (in order) {@code numberOfPackagesOptimized}, {@code numberOfPackagesSkipped}
7127     * and {@code numberOfPackagesFailed}.
7128     */
7129    private int[] performDexOptUpgrade(List<PackageParser.Package> pkgs, boolean showDialog,
7130            String compilerFilter) {
7131
7132        int numberOfPackagesVisited = 0;
7133        int numberOfPackagesOptimized = 0;
7134        int numberOfPackagesSkipped = 0;
7135        int numberOfPackagesFailed = 0;
7136        final int numberOfPackagesToDexopt = pkgs.size();
7137
7138        for (PackageParser.Package pkg : pkgs) {
7139            numberOfPackagesVisited++;
7140
7141            if (!PackageDexOptimizer.canOptimizePackage(pkg)) {
7142                if (DEBUG_DEXOPT) {
7143                    Log.i(TAG, "Skipping update of of non-optimizable app " + pkg.packageName);
7144                }
7145                numberOfPackagesSkipped++;
7146                continue;
7147            }
7148
7149            if (DEBUG_DEXOPT) {
7150                Log.i(TAG, "Updating app " + numberOfPackagesVisited + " of " +
7151                        numberOfPackagesToDexopt + ": " + pkg.packageName);
7152            }
7153
7154            if (showDialog) {
7155                try {
7156                    ActivityManagerNative.getDefault().showBootMessage(
7157                            mContext.getResources().getString(R.string.android_upgrading_apk,
7158                                    numberOfPackagesVisited, numberOfPackagesToDexopt), true);
7159                } catch (RemoteException e) {
7160                }
7161            }
7162
7163            // If the OTA updates a system app which was previously preopted to a non-preopted state
7164            // the app might end up being verified at runtime. That's because by default the apps
7165            // are verify-profile but for preopted apps there's no profile.
7166            // Do a hacky check to ensure that if we have no profiles (a reasonable indication
7167            // that before the OTA the app was preopted) the app gets compiled with a non-profile
7168            // filter (by default interpret-only).
7169            // Note that at this stage unused apps are already filtered.
7170            if (isSystemApp(pkg) &&
7171                    DexFile.isProfileGuidedCompilerFilter(compilerFilter) &&
7172                    !Environment.getReferenceProfile(pkg.packageName).exists()) {
7173                compilerFilter = getNonProfileGuidedCompilerFilter(compilerFilter);
7174            }
7175
7176            // checkProfiles is false to avoid merging profiles during boot which
7177            // might interfere with background compilation (b/28612421).
7178            // Unfortunately this will also means that "pm.dexopt.boot=speed-profile" will
7179            // behave differently than "pm.dexopt.bg-dexopt=speed-profile" but that's a
7180            // trade-off worth doing to save boot time work.
7181            int dexOptStatus = performDexOptTraced(pkg.packageName,
7182                    false /* checkProfiles */,
7183                    compilerFilter,
7184                    false /* force */);
7185            switch (dexOptStatus) {
7186                case PackageDexOptimizer.DEX_OPT_PERFORMED:
7187                    numberOfPackagesOptimized++;
7188                    break;
7189                case PackageDexOptimizer.DEX_OPT_SKIPPED:
7190                    numberOfPackagesSkipped++;
7191                    break;
7192                case PackageDexOptimizer.DEX_OPT_FAILED:
7193                    numberOfPackagesFailed++;
7194                    break;
7195                default:
7196                    Log.e(TAG, "Unexpected dexopt return code " + dexOptStatus);
7197                    break;
7198            }
7199        }
7200
7201        return new int[] { numberOfPackagesOptimized, numberOfPackagesSkipped,
7202                numberOfPackagesFailed };
7203    }
7204
7205    @Override
7206    public void notifyPackageUse(String packageName, int reason) {
7207        synchronized (mPackages) {
7208            PackageParser.Package p = mPackages.get(packageName);
7209            if (p == null) {
7210                return;
7211            }
7212            p.mLastPackageUsageTimeInMills[reason] = System.currentTimeMillis();
7213        }
7214    }
7215
7216    // TODO: this is not used nor needed. Delete it.
7217    @Override
7218    public boolean performDexOptIfNeeded(String packageName) {
7219        int dexOptStatus = performDexOptTraced(packageName,
7220                false /* checkProfiles */, getFullCompilerFilter(), false /* force */);
7221        return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
7222    }
7223
7224    @Override
7225    public boolean performDexOpt(String packageName,
7226            boolean checkProfiles, int compileReason, boolean force) {
7227        int dexOptStatus = performDexOptTraced(packageName, checkProfiles,
7228                getCompilerFilterForReason(compileReason), force);
7229        return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
7230    }
7231
7232    @Override
7233    public boolean performDexOptMode(String packageName,
7234            boolean checkProfiles, String targetCompilerFilter, boolean force) {
7235        int dexOptStatus = performDexOptTraced(packageName, checkProfiles,
7236                targetCompilerFilter, force);
7237        return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
7238    }
7239
7240    private int performDexOptTraced(String packageName,
7241                boolean checkProfiles, String targetCompilerFilter, boolean force) {
7242        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
7243        try {
7244            return performDexOptInternal(packageName, checkProfiles,
7245                    targetCompilerFilter, force);
7246        } finally {
7247            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7248        }
7249    }
7250
7251    // Run dexopt on a given package. Returns true if dexopt did not fail, i.e.
7252    // if the package can now be considered up to date for the given filter.
7253    private int performDexOptInternal(String packageName,
7254                boolean checkProfiles, String targetCompilerFilter, boolean force) {
7255        PackageParser.Package p;
7256        synchronized (mPackages) {
7257            p = mPackages.get(packageName);
7258            if (p == null) {
7259                // Package could not be found. Report failure.
7260                return PackageDexOptimizer.DEX_OPT_FAILED;
7261            }
7262            mPackageUsage.maybeWriteAsync(mPackages);
7263            mCompilerStats.maybeWriteAsync();
7264        }
7265        long callingId = Binder.clearCallingIdentity();
7266        try {
7267            synchronized (mInstallLock) {
7268                return performDexOptInternalWithDependenciesLI(p, checkProfiles,
7269                        targetCompilerFilter, force);
7270            }
7271        } finally {
7272            Binder.restoreCallingIdentity(callingId);
7273        }
7274    }
7275
7276    public ArraySet<String> getOptimizablePackages() {
7277        ArraySet<String> pkgs = new ArraySet<String>();
7278        synchronized (mPackages) {
7279            for (PackageParser.Package p : mPackages.values()) {
7280                if (PackageDexOptimizer.canOptimizePackage(p)) {
7281                    pkgs.add(p.packageName);
7282                }
7283            }
7284        }
7285        return pkgs;
7286    }
7287
7288    private int performDexOptInternalWithDependenciesLI(PackageParser.Package p,
7289            boolean checkProfiles, String targetCompilerFilter,
7290            boolean force) {
7291        // Select the dex optimizer based on the force parameter.
7292        // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to
7293        //       allocate an object here.
7294        PackageDexOptimizer pdo = force
7295                ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer)
7296                : mPackageDexOptimizer;
7297
7298        // Optimize all dependencies first. Note: we ignore the return value and march on
7299        // on errors.
7300        Collection<PackageParser.Package> deps = findSharedNonSystemLibraries(p);
7301        final String[] instructionSets = getAppDexInstructionSets(p.applicationInfo);
7302        if (!deps.isEmpty()) {
7303            for (PackageParser.Package depPackage : deps) {
7304                // TODO: Analyze and investigate if we (should) profile libraries.
7305                // Currently this will do a full compilation of the library by default.
7306                pdo.performDexOpt(depPackage, null /* sharedLibraries */, instructionSets,
7307                        false /* checkProfiles */,
7308                        getCompilerFilterForReason(REASON_NON_SYSTEM_LIBRARY),
7309                        getOrCreateCompilerPackageStats(depPackage));
7310            }
7311        }
7312        return pdo.performDexOpt(p, p.usesLibraryFiles, instructionSets, checkProfiles,
7313                targetCompilerFilter, getOrCreateCompilerPackageStats(p));
7314    }
7315
7316    Collection<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package p) {
7317        if (p.usesLibraries != null || p.usesOptionalLibraries != null) {
7318            ArrayList<PackageParser.Package> retValue = new ArrayList<>();
7319            Set<String> collectedNames = new HashSet<>();
7320            findSharedNonSystemLibrariesRecursive(p, retValue, collectedNames);
7321
7322            retValue.remove(p);
7323
7324            return retValue;
7325        } else {
7326            return Collections.emptyList();
7327        }
7328    }
7329
7330    private void findSharedNonSystemLibrariesRecursive(PackageParser.Package p,
7331            Collection<PackageParser.Package> collected, Set<String> collectedNames) {
7332        if (!collectedNames.contains(p.packageName)) {
7333            collectedNames.add(p.packageName);
7334            collected.add(p);
7335
7336            if (p.usesLibraries != null) {
7337                findSharedNonSystemLibrariesRecursive(p.usesLibraries, collected, collectedNames);
7338            }
7339            if (p.usesOptionalLibraries != null) {
7340                findSharedNonSystemLibrariesRecursive(p.usesOptionalLibraries, collected,
7341                        collectedNames);
7342            }
7343        }
7344    }
7345
7346    private void findSharedNonSystemLibrariesRecursive(Collection<String> libs,
7347            Collection<PackageParser.Package> collected, Set<String> collectedNames) {
7348        for (String libName : libs) {
7349            PackageParser.Package libPkg = findSharedNonSystemLibrary(libName);
7350            if (libPkg != null) {
7351                findSharedNonSystemLibrariesRecursive(libPkg, collected, collectedNames);
7352            }
7353        }
7354    }
7355
7356    private PackageParser.Package findSharedNonSystemLibrary(String libName) {
7357        synchronized (mPackages) {
7358            PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName);
7359            if (lib != null && lib.apk != null) {
7360                return mPackages.get(lib.apk);
7361            }
7362        }
7363        return null;
7364    }
7365
7366    public void shutdown() {
7367        mPackageUsage.writeNow(mPackages);
7368        mCompilerStats.writeNow();
7369    }
7370
7371    @Override
7372    public void dumpProfiles(String packageName) {
7373        PackageParser.Package pkg;
7374        synchronized (mPackages) {
7375            pkg = mPackages.get(packageName);
7376            if (pkg == null) {
7377                throw new IllegalArgumentException("Unknown package: " + packageName);
7378            }
7379        }
7380        /* Only the shell, root, or the app user should be able to dump profiles. */
7381        int callingUid = Binder.getCallingUid();
7382        if (callingUid != Process.SHELL_UID &&
7383            callingUid != Process.ROOT_UID &&
7384            callingUid != pkg.applicationInfo.uid) {
7385            throw new SecurityException("dumpProfiles");
7386        }
7387
7388        synchronized (mInstallLock) {
7389            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dump profiles");
7390            final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
7391            try {
7392                List<String> allCodePaths = pkg.getAllCodePathsExcludingResourceOnly();
7393                String gid = Integer.toString(sharedGid);
7394                String codePaths = TextUtils.join(";", allCodePaths);
7395                mInstaller.dumpProfiles(gid, packageName, codePaths);
7396            } catch (InstallerException e) {
7397                Slog.w(TAG, "Failed to dump profiles", e);
7398            }
7399            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7400        }
7401    }
7402
7403    @Override
7404    public void forceDexOpt(String packageName) {
7405        enforceSystemOrRoot("forceDexOpt");
7406
7407        PackageParser.Package pkg;
7408        synchronized (mPackages) {
7409            pkg = mPackages.get(packageName);
7410            if (pkg == null) {
7411                throw new IllegalArgumentException("Unknown package: " + packageName);
7412            }
7413        }
7414
7415        synchronized (mInstallLock) {
7416            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
7417
7418            // Whoever is calling forceDexOpt wants a fully compiled package.
7419            // Don't use profiles since that may cause compilation to be skipped.
7420            final int res = performDexOptInternalWithDependenciesLI(pkg,
7421                    false /* checkProfiles */, getCompilerFilterForReason(REASON_FORCED_DEXOPT),
7422                    true /* force */);
7423
7424            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7425            if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) {
7426                throw new IllegalStateException("Failed to dexopt: " + res);
7427            }
7428        }
7429    }
7430
7431    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
7432        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
7433            Slog.w(TAG, "Unable to update from " + oldPkg.name
7434                    + " to " + newPkg.packageName
7435                    + ": old package not in system partition");
7436            return false;
7437        } else if (mPackages.get(oldPkg.name) != null) {
7438            Slog.w(TAG, "Unable to update from " + oldPkg.name
7439                    + " to " + newPkg.packageName
7440                    + ": old package still exists");
7441            return false;
7442        }
7443        return true;
7444    }
7445
7446    void removeCodePathLI(File codePath) {
7447        if (codePath.isDirectory()) {
7448            try {
7449                mInstaller.rmPackageDir(codePath.getAbsolutePath());
7450            } catch (InstallerException e) {
7451                Slog.w(TAG, "Failed to remove code path", e);
7452            }
7453        } else {
7454            codePath.delete();
7455        }
7456    }
7457
7458    private int[] resolveUserIds(int userId) {
7459        return (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() : new int[] { userId };
7460    }
7461
7462    private void clearAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
7463        if (pkg == null) {
7464            Slog.wtf(TAG, "Package was null!", new Throwable());
7465            return;
7466        }
7467        clearAppDataLeafLIF(pkg, userId, flags);
7468        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7469        for (int i = 0; i < childCount; i++) {
7470            clearAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
7471        }
7472    }
7473
7474    private void clearAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
7475        final PackageSetting ps;
7476        synchronized (mPackages) {
7477            ps = mSettings.mPackages.get(pkg.packageName);
7478        }
7479        for (int realUserId : resolveUserIds(userId)) {
7480            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
7481            try {
7482                mInstaller.clearAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
7483                        ceDataInode);
7484            } catch (InstallerException e) {
7485                Slog.w(TAG, String.valueOf(e));
7486            }
7487        }
7488    }
7489
7490    private void destroyAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
7491        if (pkg == null) {
7492            Slog.wtf(TAG, "Package was null!", new Throwable());
7493            return;
7494        }
7495        destroyAppDataLeafLIF(pkg, userId, flags);
7496        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7497        for (int i = 0; i < childCount; i++) {
7498            destroyAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
7499        }
7500    }
7501
7502    private void destroyAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
7503        final PackageSetting ps;
7504        synchronized (mPackages) {
7505            ps = mSettings.mPackages.get(pkg.packageName);
7506        }
7507        for (int realUserId : resolveUserIds(userId)) {
7508            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
7509            try {
7510                mInstaller.destroyAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
7511                        ceDataInode);
7512            } catch (InstallerException e) {
7513                Slog.w(TAG, String.valueOf(e));
7514            }
7515        }
7516    }
7517
7518    private void destroyAppProfilesLIF(PackageParser.Package pkg, int userId) {
7519        if (pkg == null) {
7520            Slog.wtf(TAG, "Package was null!", new Throwable());
7521            return;
7522        }
7523        destroyAppProfilesLeafLIF(pkg);
7524        destroyAppReferenceProfileLeafLIF(pkg, userId, true /* removeBaseMarker */);
7525        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7526        for (int i = 0; i < childCount; i++) {
7527            destroyAppProfilesLeafLIF(pkg.childPackages.get(i));
7528            destroyAppReferenceProfileLeafLIF(pkg.childPackages.get(i), userId,
7529                    true /* removeBaseMarker */);
7530        }
7531    }
7532
7533    private void destroyAppReferenceProfileLeafLIF(PackageParser.Package pkg, int userId,
7534            boolean removeBaseMarker) {
7535        if (pkg.isForwardLocked()) {
7536            return;
7537        }
7538
7539        for (String path : pkg.getAllCodePathsExcludingResourceOnly()) {
7540            try {
7541                path = PackageManagerServiceUtils.realpath(new File(path));
7542            } catch (IOException e) {
7543                // TODO: Should we return early here ?
7544                Slog.w(TAG, "Failed to get canonical path", e);
7545                continue;
7546            }
7547
7548            final String useMarker = path.replace('/', '@');
7549            for (int realUserId : resolveUserIds(userId)) {
7550                File profileDir = Environment.getDataProfilesDeForeignDexDirectory(realUserId);
7551                if (removeBaseMarker) {
7552                    File foreignUseMark = new File(profileDir, useMarker);
7553                    if (foreignUseMark.exists()) {
7554                        if (!foreignUseMark.delete()) {
7555                            Slog.w(TAG, "Unable to delete foreign user mark for package: "
7556                                    + pkg.packageName);
7557                        }
7558                    }
7559                }
7560
7561                File[] markers = profileDir.listFiles();
7562                if (markers != null) {
7563                    final String searchString = "@" + pkg.packageName + "@";
7564                    // We also delete all markers that contain the package name we're
7565                    // uninstalling. These are associated with secondary dex-files belonging
7566                    // to the package. Reconstructing the path of these dex files is messy
7567                    // in general.
7568                    for (File marker : markers) {
7569                        if (marker.getName().indexOf(searchString) > 0) {
7570                            if (!marker.delete()) {
7571                                Slog.w(TAG, "Unable to delete foreign user mark for package: "
7572                                    + pkg.packageName);
7573                            }
7574                        }
7575                    }
7576                }
7577            }
7578        }
7579    }
7580
7581    private void destroyAppProfilesLeafLIF(PackageParser.Package pkg) {
7582        try {
7583            mInstaller.destroyAppProfiles(pkg.packageName);
7584        } catch (InstallerException e) {
7585            Slog.w(TAG, String.valueOf(e));
7586        }
7587    }
7588
7589    private void clearAppProfilesLIF(PackageParser.Package pkg, int userId) {
7590        if (pkg == null) {
7591            Slog.wtf(TAG, "Package was null!", new Throwable());
7592            return;
7593        }
7594        clearAppProfilesLeafLIF(pkg);
7595        // We don't remove the base foreign use marker when clearing profiles because
7596        // we will rename it when the app is updated. Unlike the actual profile contents,
7597        // the foreign use marker is good across installs.
7598        destroyAppReferenceProfileLeafLIF(pkg, userId, false /* removeBaseMarker */);
7599        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7600        for (int i = 0; i < childCount; i++) {
7601            clearAppProfilesLeafLIF(pkg.childPackages.get(i));
7602        }
7603    }
7604
7605    private void clearAppProfilesLeafLIF(PackageParser.Package pkg) {
7606        try {
7607            mInstaller.clearAppProfiles(pkg.packageName);
7608        } catch (InstallerException e) {
7609            Slog.w(TAG, String.valueOf(e));
7610        }
7611    }
7612
7613    private void setInstallAndUpdateTime(PackageParser.Package pkg, long firstInstallTime,
7614            long lastUpdateTime) {
7615        // Set parent install/update time
7616        PackageSetting ps = (PackageSetting) pkg.mExtras;
7617        if (ps != null) {
7618            ps.firstInstallTime = firstInstallTime;
7619            ps.lastUpdateTime = lastUpdateTime;
7620        }
7621        // Set children install/update time
7622        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7623        for (int i = 0; i < childCount; i++) {
7624            PackageParser.Package childPkg = pkg.childPackages.get(i);
7625            ps = (PackageSetting) childPkg.mExtras;
7626            if (ps != null) {
7627                ps.firstInstallTime = firstInstallTime;
7628                ps.lastUpdateTime = lastUpdateTime;
7629            }
7630        }
7631    }
7632
7633    private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file,
7634            PackageParser.Package changingLib) {
7635        if (file.path != null) {
7636            usesLibraryFiles.add(file.path);
7637            return;
7638        }
7639        PackageParser.Package p = mPackages.get(file.apk);
7640        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
7641            // If we are doing this while in the middle of updating a library apk,
7642            // then we need to make sure to use that new apk for determining the
7643            // dependencies here.  (We haven't yet finished committing the new apk
7644            // to the package manager state.)
7645            if (p == null || p.packageName.equals(changingLib.packageName)) {
7646                p = changingLib;
7647            }
7648        }
7649        if (p != null) {
7650            usesLibraryFiles.addAll(p.getAllCodePaths());
7651        }
7652    }
7653
7654    private void updateSharedLibrariesLPw(PackageParser.Package pkg,
7655            PackageParser.Package changingLib) throws PackageManagerException {
7656        if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) {
7657            final ArraySet<String> usesLibraryFiles = new ArraySet<>();
7658            int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0;
7659            for (int i=0; i<N; i++) {
7660                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i));
7661                if (file == null) {
7662                    throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
7663                            "Package " + pkg.packageName + " requires unavailable shared library "
7664                            + pkg.usesLibraries.get(i) + "; failing!");
7665                }
7666                addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
7667            }
7668            N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0;
7669            for (int i=0; i<N; i++) {
7670                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i));
7671                if (file == null) {
7672                    Slog.w(TAG, "Package " + pkg.packageName
7673                            + " desires unavailable shared library "
7674                            + pkg.usesOptionalLibraries.get(i) + "; ignoring!");
7675                } else {
7676                    addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
7677                }
7678            }
7679            N = usesLibraryFiles.size();
7680            if (N > 0) {
7681                pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]);
7682            } else {
7683                pkg.usesLibraryFiles = null;
7684            }
7685        }
7686    }
7687
7688    private static boolean hasString(List<String> list, List<String> which) {
7689        if (list == null) {
7690            return false;
7691        }
7692        for (int i=list.size()-1; i>=0; i--) {
7693            for (int j=which.size()-1; j>=0; j--) {
7694                if (which.get(j).equals(list.get(i))) {
7695                    return true;
7696                }
7697            }
7698        }
7699        return false;
7700    }
7701
7702    private void updateAllSharedLibrariesLPw() {
7703        for (PackageParser.Package pkg : mPackages.values()) {
7704            try {
7705                updateSharedLibrariesLPw(pkg, null);
7706            } catch (PackageManagerException e) {
7707                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
7708            }
7709        }
7710    }
7711
7712    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
7713            PackageParser.Package changingPkg) {
7714        ArrayList<PackageParser.Package> res = null;
7715        for (PackageParser.Package pkg : mPackages.values()) {
7716            if (hasString(pkg.usesLibraries, changingPkg.libraryNames)
7717                    || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) {
7718                if (res == null) {
7719                    res = new ArrayList<PackageParser.Package>();
7720                }
7721                res.add(pkg);
7722                try {
7723                    updateSharedLibrariesLPw(pkg, changingPkg);
7724                } catch (PackageManagerException e) {
7725                    Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
7726                }
7727            }
7728        }
7729        return res;
7730    }
7731
7732    /**
7733     * Derive the value of the {@code cpuAbiOverride} based on the provided
7734     * value and an optional stored value from the package settings.
7735     */
7736    private static String deriveAbiOverride(String abiOverride, PackageSetting settings) {
7737        String cpuAbiOverride = null;
7738
7739        if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) {
7740            cpuAbiOverride = null;
7741        } else if (abiOverride != null) {
7742            cpuAbiOverride = abiOverride;
7743        } else if (settings != null) {
7744            cpuAbiOverride = settings.cpuAbiOverrideString;
7745        }
7746
7747        return cpuAbiOverride;
7748    }
7749
7750    private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg,
7751            final int policyFlags, int scanFlags, long currentTime, UserHandle user)
7752                    throws PackageManagerException {
7753        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage");
7754        // If the package has children and this is the first dive in the function
7755        // we recursively scan the package with the SCAN_CHECK_ONLY flag set to see
7756        // whether all packages (parent and children) would be successfully scanned
7757        // before the actual scan since scanning mutates internal state and we want
7758        // to atomically install the package and its children.
7759        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
7760            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
7761                scanFlags |= SCAN_CHECK_ONLY;
7762            }
7763        } else {
7764            scanFlags &= ~SCAN_CHECK_ONLY;
7765        }
7766
7767        final PackageParser.Package scannedPkg;
7768        try {
7769            // Scan the parent
7770            scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags, currentTime, user);
7771            // Scan the children
7772            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7773            for (int i = 0; i < childCount; i++) {
7774                PackageParser.Package childPkg = pkg.childPackages.get(i);
7775                scanPackageLI(childPkg, policyFlags,
7776                        scanFlags, currentTime, user);
7777            }
7778        } finally {
7779            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7780        }
7781
7782        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
7783            return scanPackageTracedLI(pkg, policyFlags, scanFlags, currentTime, user);
7784        }
7785
7786        return scannedPkg;
7787    }
7788
7789    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, final int policyFlags,
7790            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
7791        boolean success = false;
7792        try {
7793            final PackageParser.Package res = scanPackageDirtyLI(pkg, policyFlags, scanFlags,
7794                    currentTime, user);
7795            success = true;
7796            return res;
7797        } finally {
7798            if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
7799                // DELETE_DATA_ON_FAILURES is only used by frozen paths
7800                destroyAppDataLIF(pkg, UserHandle.USER_ALL,
7801                        StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
7802                destroyAppProfilesLIF(pkg, UserHandle.USER_ALL);
7803            }
7804        }
7805    }
7806
7807    /**
7808     * Returns {@code true} if the given file contains code. Otherwise {@code false}.
7809     */
7810    private static boolean apkHasCode(String fileName) {
7811        StrictJarFile jarFile = null;
7812        try {
7813            jarFile = new StrictJarFile(fileName,
7814                    false /*verify*/, false /*signatureSchemeRollbackProtectionsEnforced*/);
7815            return jarFile.findEntry("classes.dex") != null;
7816        } catch (IOException ignore) {
7817        } finally {
7818            try {
7819                jarFile.close();
7820            } catch (IOException ignore) {}
7821        }
7822        return false;
7823    }
7824
7825    /**
7826     * Enforces code policy for the package. This ensures that if an APK has
7827     * declared hasCode="true" in its manifest that the APK actually contains
7828     * code.
7829     *
7830     * @throws PackageManagerException If bytecode could not be found when it should exist
7831     */
7832    private static void enforceCodePolicy(PackageParser.Package pkg)
7833            throws PackageManagerException {
7834        final boolean shouldHaveCode =
7835                (pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) != 0;
7836        if (shouldHaveCode && !apkHasCode(pkg.baseCodePath)) {
7837            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
7838                    "Package " + pkg.baseCodePath + " code is missing");
7839        }
7840
7841        if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
7842            for (int i = 0; i < pkg.splitCodePaths.length; i++) {
7843                final boolean splitShouldHaveCode =
7844                        (pkg.splitFlags[i] & ApplicationInfo.FLAG_HAS_CODE) != 0;
7845                if (splitShouldHaveCode && !apkHasCode(pkg.splitCodePaths[i])) {
7846                    throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
7847                            "Package " + pkg.splitCodePaths[i] + " code is missing");
7848                }
7849            }
7850        }
7851    }
7852
7853    private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg,
7854            final int policyFlags, final int scanFlags, long currentTime, UserHandle user)
7855            throws PackageManagerException {
7856        final File scanFile = new File(pkg.codePath);
7857        if (pkg.applicationInfo.getCodePath() == null ||
7858                pkg.applicationInfo.getResourcePath() == null) {
7859            // Bail out. The resource and code paths haven't been set.
7860            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
7861                    "Code and resource paths haven't been set correctly");
7862        }
7863
7864        // Apply policy
7865        if ((policyFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
7866            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
7867            if (pkg.applicationInfo.isDirectBootAware()) {
7868                // we're direct boot aware; set for all components
7869                for (PackageParser.Service s : pkg.services) {
7870                    s.info.encryptionAware = s.info.directBootAware = true;
7871                }
7872                for (PackageParser.Provider p : pkg.providers) {
7873                    p.info.encryptionAware = p.info.directBootAware = true;
7874                }
7875                for (PackageParser.Activity a : pkg.activities) {
7876                    a.info.encryptionAware = a.info.directBootAware = true;
7877                }
7878                for (PackageParser.Activity r : pkg.receivers) {
7879                    r.info.encryptionAware = r.info.directBootAware = true;
7880                }
7881            }
7882        } else {
7883            // Only allow system apps to be flagged as core apps.
7884            pkg.coreApp = false;
7885            // clear flags not applicable to regular apps
7886            pkg.applicationInfo.privateFlags &=
7887                    ~ApplicationInfo.PRIVATE_FLAG_DEFAULT_TO_DEVICE_PROTECTED_STORAGE;
7888            pkg.applicationInfo.privateFlags &=
7889                    ~ApplicationInfo.PRIVATE_FLAG_DIRECT_BOOT_AWARE;
7890        }
7891        pkg.mTrustedOverlay = (policyFlags&PackageParser.PARSE_TRUSTED_OVERLAY) != 0;
7892
7893        if ((policyFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) {
7894            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
7895        }
7896
7897        if ((policyFlags & PackageParser.PARSE_ENFORCE_CODE) != 0) {
7898            enforceCodePolicy(pkg);
7899        }
7900
7901        if (mCustomResolverComponentName != null &&
7902                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
7903            setUpCustomResolverActivity(pkg);
7904        }
7905
7906        if (pkg.packageName.equals("android")) {
7907            synchronized (mPackages) {
7908                if (mAndroidApplication != null) {
7909                    Slog.w(TAG, "*************************************************");
7910                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
7911                    Slog.w(TAG, " file=" + scanFile);
7912                    Slog.w(TAG, "*************************************************");
7913                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
7914                            "Core android package being redefined.  Skipping.");
7915                }
7916
7917                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
7918                    // Set up information for our fall-back user intent resolution activity.
7919                    mPlatformPackage = pkg;
7920                    pkg.mVersionCode = mSdkVersion;
7921                    mAndroidApplication = pkg.applicationInfo;
7922
7923                    if (!mResolverReplaced) {
7924                        mResolveActivity.applicationInfo = mAndroidApplication;
7925                        mResolveActivity.name = ResolverActivity.class.getName();
7926                        mResolveActivity.packageName = mAndroidApplication.packageName;
7927                        mResolveActivity.processName = "system:ui";
7928                        mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
7929                        mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
7930                        mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
7931                        mResolveActivity.theme = R.style.Theme_Material_Dialog_Alert;
7932                        mResolveActivity.exported = true;
7933                        mResolveActivity.enabled = true;
7934                        mResolveActivity.resizeMode = ActivityInfo.RESIZE_MODE_RESIZEABLE;
7935                        mResolveActivity.configChanges = ActivityInfo.CONFIG_SCREEN_SIZE
7936                                | ActivityInfo.CONFIG_SMALLEST_SCREEN_SIZE
7937                                | ActivityInfo.CONFIG_SCREEN_LAYOUT
7938                                | ActivityInfo.CONFIG_ORIENTATION
7939                                | ActivityInfo.CONFIG_KEYBOARD
7940                                | ActivityInfo.CONFIG_KEYBOARD_HIDDEN;
7941                        mResolveInfo.activityInfo = mResolveActivity;
7942                        mResolveInfo.priority = 0;
7943                        mResolveInfo.preferredOrder = 0;
7944                        mResolveInfo.match = 0;
7945                        mResolveComponentName = new ComponentName(
7946                                mAndroidApplication.packageName, mResolveActivity.name);
7947                    }
7948                }
7949            }
7950        }
7951
7952        if (DEBUG_PACKAGE_SCANNING) {
7953            if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
7954                Log.d(TAG, "Scanning package " + pkg.packageName);
7955        }
7956
7957        synchronized (mPackages) {
7958            if (mPackages.containsKey(pkg.packageName)
7959                    || mSharedLibraries.containsKey(pkg.packageName)) {
7960                throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
7961                        "Application package " + pkg.packageName
7962                                + " already installed.  Skipping duplicate.");
7963            }
7964
7965            // If we're only installing presumed-existing packages, require that the
7966            // scanned APK is both already known and at the path previously established
7967            // for it.  Previously unknown packages we pick up normally, but if we have an
7968            // a priori expectation about this package's install presence, enforce it.
7969            // With a singular exception for new system packages. When an OTA contains
7970            // a new system package, we allow the codepath to change from a system location
7971            // to the user-installed location. If we don't allow this change, any newer,
7972            // user-installed version of the application will be ignored.
7973            if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) {
7974                if (mExpectingBetter.containsKey(pkg.packageName)) {
7975                    logCriticalInfo(Log.WARN,
7976                            "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName);
7977                } else {
7978                    PackageSetting known = mSettings.peekPackageLPr(pkg.packageName);
7979                    if (known != null) {
7980                        if (DEBUG_PACKAGE_SCANNING) {
7981                            Log.d(TAG, "Examining " + pkg.codePath
7982                                    + " and requiring known paths " + known.codePathString
7983                                    + " & " + known.resourcePathString);
7984                        }
7985                        if (!pkg.applicationInfo.getCodePath().equals(known.codePathString)
7986                                || !pkg.applicationInfo.getResourcePath().equals(
7987                                known.resourcePathString)) {
7988                            throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED,
7989                                    "Application package " + pkg.packageName
7990                                            + " found at " + pkg.applicationInfo.getCodePath()
7991                                            + " but expected at " + known.codePathString
7992                                            + "; ignoring.");
7993                        }
7994                    }
7995                }
7996            }
7997        }
7998
7999        // Initialize package source and resource directories
8000        File destCodeFile = new File(pkg.applicationInfo.getCodePath());
8001        File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
8002
8003        SharedUserSetting suid = null;
8004        PackageSetting pkgSetting = null;
8005
8006        if (!isSystemApp(pkg)) {
8007            // Only system apps can use these features.
8008            pkg.mOriginalPackages = null;
8009            pkg.mRealPackage = null;
8010            pkg.mAdoptPermissions = null;
8011        }
8012
8013        // Getting the package setting may have a side-effect, so if we
8014        // are only checking if scan would succeed, stash a copy of the
8015        // old setting to restore at the end.
8016        PackageSetting nonMutatedPs = null;
8017
8018        // writer
8019        synchronized (mPackages) {
8020            if (pkg.mSharedUserId != null) {
8021                suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true);
8022                if (suid == null) {
8023                    throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
8024                            "Creating application package " + pkg.packageName
8025                            + " for shared user failed");
8026                }
8027                if (DEBUG_PACKAGE_SCANNING) {
8028                    if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
8029                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId
8030                                + "): packages=" + suid.packages);
8031                }
8032            }
8033
8034            // Check if we are renaming from an original package name.
8035            PackageSetting origPackage = null;
8036            String realName = null;
8037            if (pkg.mOriginalPackages != null) {
8038                // This package may need to be renamed to a previously
8039                // installed name.  Let's check on that...
8040                final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage);
8041                if (pkg.mOriginalPackages.contains(renamed)) {
8042                    // This package had originally been installed as the
8043                    // original name, and we have already taken care of
8044                    // transitioning to the new one.  Just update the new
8045                    // one to continue using the old name.
8046                    realName = pkg.mRealPackage;
8047                    if (!pkg.packageName.equals(renamed)) {
8048                        // Callers into this function may have already taken
8049                        // care of renaming the package; only do it here if
8050                        // it is not already done.
8051                        pkg.setPackageName(renamed);
8052                    }
8053
8054                } else {
8055                    for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
8056                        if ((origPackage = mSettings.peekPackageLPr(
8057                                pkg.mOriginalPackages.get(i))) != null) {
8058                            // We do have the package already installed under its
8059                            // original name...  should we use it?
8060                            if (!verifyPackageUpdateLPr(origPackage, pkg)) {
8061                                // New package is not compatible with original.
8062                                origPackage = null;
8063                                continue;
8064                            } else if (origPackage.sharedUser != null) {
8065                                // Make sure uid is compatible between packages.
8066                                if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
8067                                    Slog.w(TAG, "Unable to migrate data from " + origPackage.name
8068                                            + " to " + pkg.packageName + ": old uid "
8069                                            + origPackage.sharedUser.name
8070                                            + " differs from " + pkg.mSharedUserId);
8071                                    origPackage = null;
8072                                    continue;
8073                                }
8074                                // TODO: Add case when shared user id is added [b/28144775]
8075                            } else {
8076                                if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
8077                                        + pkg.packageName + " to old name " + origPackage.name);
8078                            }
8079                            break;
8080                        }
8081                    }
8082                }
8083            }
8084
8085            if (mTransferedPackages.contains(pkg.packageName)) {
8086                Slog.w(TAG, "Package " + pkg.packageName
8087                        + " was transferred to another, but its .apk remains");
8088            }
8089
8090            // See comments in nonMutatedPs declaration
8091            if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
8092                PackageSetting foundPs = mSettings.peekPackageLPr(pkg.packageName);
8093                if (foundPs != null) {
8094                    nonMutatedPs = new PackageSetting(foundPs);
8095                }
8096            }
8097
8098            // Just create the setting, don't add it yet. For already existing packages
8099            // the PkgSetting exists already and doesn't have to be created.
8100            pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile,
8101                    destResourceFile, pkg.applicationInfo.nativeLibraryRootDir,
8102                    pkg.applicationInfo.primaryCpuAbi,
8103                    pkg.applicationInfo.secondaryCpuAbi,
8104                    pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags,
8105                    user, false);
8106            if (pkgSetting == null) {
8107                throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
8108                        "Creating application package " + pkg.packageName + " failed");
8109            }
8110
8111            if (pkgSetting.origPackage != null) {
8112                // If we are first transitioning from an original package,
8113                // fix up the new package's name now.  We need to do this after
8114                // looking up the package under its new name, so getPackageLP
8115                // can take care of fiddling things correctly.
8116                pkg.setPackageName(origPackage.name);
8117
8118                // File a report about this.
8119                String msg = "New package " + pkgSetting.realName
8120                        + " renamed to replace old package " + pkgSetting.name;
8121                reportSettingsProblem(Log.WARN, msg);
8122
8123                // Make a note of it.
8124                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
8125                    mTransferedPackages.add(origPackage.name);
8126                }
8127
8128                // No longer need to retain this.
8129                pkgSetting.origPackage = null;
8130            }
8131
8132            if ((scanFlags & SCAN_CHECK_ONLY) == 0 && realName != null) {
8133                // Make a note of it.
8134                mTransferedPackages.add(pkg.packageName);
8135            }
8136
8137            if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) {
8138                pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
8139            }
8140
8141            if ((policyFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
8142                // Check all shared libraries and map to their actual file path.
8143                // We only do this here for apps not on a system dir, because those
8144                // are the only ones that can fail an install due to this.  We
8145                // will take care of the system apps by updating all of their
8146                // library paths after the scan is done.
8147                updateSharedLibrariesLPw(pkg, null);
8148            }
8149
8150            if (mFoundPolicyFile) {
8151                SELinuxMMAC.assignSeinfoValue(pkg);
8152            }
8153
8154            pkg.applicationInfo.uid = pkgSetting.appId;
8155            pkg.mExtras = pkgSetting;
8156            if (shouldCheckUpgradeKeySetLP(pkgSetting, scanFlags)) {
8157                if (checkUpgradeKeySetLP(pkgSetting, pkg)) {
8158                    // We just determined the app is signed correctly, so bring
8159                    // over the latest parsed certs.
8160                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
8161                } else {
8162                    if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
8163                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
8164                                "Package " + pkg.packageName + " upgrade keys do not match the "
8165                                + "previously installed version");
8166                    } else {
8167                        pkgSetting.signatures.mSignatures = pkg.mSignatures;
8168                        String msg = "System package " + pkg.packageName
8169                            + " signature changed; retaining data.";
8170                        reportSettingsProblem(Log.WARN, msg);
8171                    }
8172                }
8173            } else {
8174                try {
8175                    verifySignaturesLP(pkgSetting, pkg);
8176                    // We just determined the app is signed correctly, so bring
8177                    // over the latest parsed certs.
8178                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
8179                } catch (PackageManagerException e) {
8180                    if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
8181                        throw e;
8182                    }
8183                    // The signature has changed, but this package is in the system
8184                    // image...  let's recover!
8185                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
8186                    // However...  if this package is part of a shared user, but it
8187                    // doesn't match the signature of the shared user, let's fail.
8188                    // What this means is that you can't change the signatures
8189                    // associated with an overall shared user, which doesn't seem all
8190                    // that unreasonable.
8191                    if (pkgSetting.sharedUser != null) {
8192                        if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
8193                                              pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
8194                            throw new PackageManagerException(
8195                                    INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
8196                                            "Signature mismatch for shared user: "
8197                                            + pkgSetting.sharedUser);
8198                        }
8199                    }
8200                    // File a report about this.
8201                    String msg = "System package " + pkg.packageName
8202                        + " signature changed; retaining data.";
8203                    reportSettingsProblem(Log.WARN, msg);
8204                }
8205            }
8206            // Verify that this new package doesn't have any content providers
8207            // that conflict with existing packages.  Only do this if the
8208            // package isn't already installed, since we don't want to break
8209            // things that are installed.
8210            if ((scanFlags & SCAN_NEW_INSTALL) != 0) {
8211                final int N = pkg.providers.size();
8212                int i;
8213                for (i=0; i<N; i++) {
8214                    PackageParser.Provider p = pkg.providers.get(i);
8215                    if (p.info.authority != null) {
8216                        String names[] = p.info.authority.split(";");
8217                        for (int j = 0; j < names.length; j++) {
8218                            if (mProvidersByAuthority.containsKey(names[j])) {
8219                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
8220                                final String otherPackageName =
8221                                        ((other != null && other.getComponentName() != null) ?
8222                                                other.getComponentName().getPackageName() : "?");
8223                                throw new PackageManagerException(
8224                                        INSTALL_FAILED_CONFLICTING_PROVIDER,
8225                                                "Can't install because provider name " + names[j]
8226                                                + " (in package " + pkg.applicationInfo.packageName
8227                                                + ") is already used by " + otherPackageName);
8228                            }
8229                        }
8230                    }
8231                }
8232            }
8233
8234            if ((scanFlags & SCAN_CHECK_ONLY) == 0 && pkg.mAdoptPermissions != null) {
8235                // This package wants to adopt ownership of permissions from
8236                // another package.
8237                for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
8238                    final String origName = pkg.mAdoptPermissions.get(i);
8239                    final PackageSetting orig = mSettings.peekPackageLPr(origName);
8240                    if (orig != null) {
8241                        if (verifyPackageUpdateLPr(orig, pkg)) {
8242                            Slog.i(TAG, "Adopting permissions from " + origName + " to "
8243                                    + pkg.packageName);
8244                            mSettings.transferPermissionsLPw(origName, pkg.packageName);
8245                        }
8246                    }
8247                }
8248            }
8249        }
8250
8251        final String pkgName = pkg.packageName;
8252
8253        final long scanFileTime = scanFile.lastModified();
8254        final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0;
8255        pkg.applicationInfo.processName = fixProcessName(
8256                pkg.applicationInfo.packageName,
8257                pkg.applicationInfo.processName,
8258                pkg.applicationInfo.uid);
8259
8260        if (pkg != mPlatformPackage) {
8261            // Get all of our default paths setup
8262            pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM);
8263        }
8264
8265        final String path = scanFile.getPath();
8266        final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
8267
8268        if ((scanFlags & SCAN_NEW_INSTALL) == 0) {
8269            derivePackageAbi(pkg, scanFile, cpuAbiOverride, true /* extract libs */);
8270
8271            // Some system apps still use directory structure for native libraries
8272            // in which case we might end up not detecting abi solely based on apk
8273            // structure. Try to detect abi based on directory structure.
8274            if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() &&
8275                    pkg.applicationInfo.primaryCpuAbi == null) {
8276                setBundledAppAbisAndRoots(pkg, pkgSetting);
8277                setNativeLibraryPaths(pkg);
8278            }
8279
8280        } else {
8281            if ((scanFlags & SCAN_MOVE) != 0) {
8282                // We haven't run dex-opt for this move (since we've moved the compiled output too)
8283                // but we already have this packages package info in the PackageSetting. We just
8284                // use that and derive the native library path based on the new codepath.
8285                pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString;
8286                pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString;
8287            }
8288
8289            // Set native library paths again. For moves, the path will be updated based on the
8290            // ABIs we've determined above. For non-moves, the path will be updated based on the
8291            // ABIs we determined during compilation, but the path will depend on the final
8292            // package path (after the rename away from the stage path).
8293            setNativeLibraryPaths(pkg);
8294        }
8295
8296        // This is a special case for the "system" package, where the ABI is
8297        // dictated by the zygote configuration (and init.rc). We should keep track
8298        // of this ABI so that we can deal with "normal" applications that run under
8299        // the same UID correctly.
8300        if (mPlatformPackage == pkg) {
8301            pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
8302                    Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
8303        }
8304
8305        // If there's a mismatch between the abi-override in the package setting
8306        // and the abiOverride specified for the install. Warn about this because we
8307        // would've already compiled the app without taking the package setting into
8308        // account.
8309        if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) {
8310            if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) {
8311                Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride +
8312                        " for package " + pkg.packageName);
8313            }
8314        }
8315
8316        pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
8317        pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
8318        pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
8319
8320        // Copy the derived override back to the parsed package, so that we can
8321        // update the package settings accordingly.
8322        pkg.cpuAbiOverride = cpuAbiOverride;
8323
8324        if (DEBUG_ABI_SELECTION) {
8325            Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName
8326                    + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
8327                    + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
8328        }
8329
8330        // Push the derived path down into PackageSettings so we know what to
8331        // clean up at uninstall time.
8332        pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
8333
8334        if (DEBUG_ABI_SELECTION) {
8335            Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
8336                    " primary=" + pkg.applicationInfo.primaryCpuAbi +
8337                    " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
8338        }
8339
8340        if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
8341            // We don't do this here during boot because we can do it all
8342            // at once after scanning all existing packages.
8343            //
8344            // We also do this *before* we perform dexopt on this package, so that
8345            // we can avoid redundant dexopts, and also to make sure we've got the
8346            // code and package path correct.
8347            adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages,
8348                    pkg, true /* boot complete */);
8349        }
8350
8351        if (mFactoryTest && pkg.requestedPermissions.contains(
8352                android.Manifest.permission.FACTORY_TEST)) {
8353            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
8354        }
8355
8356        ArrayList<PackageParser.Package> clientLibPkgs = null;
8357
8358        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
8359            if (nonMutatedPs != null) {
8360                synchronized (mPackages) {
8361                    mSettings.mPackages.put(nonMutatedPs.name, nonMutatedPs);
8362                }
8363            }
8364            return pkg;
8365        }
8366
8367        // Only privileged apps and updated privileged apps can add child packages.
8368        if (pkg.childPackages != null && !pkg.childPackages.isEmpty()) {
8369            if ((policyFlags & PARSE_IS_PRIVILEGED) == 0) {
8370                throw new PackageManagerException("Only privileged apps and updated "
8371                        + "privileged apps can add child packages. Ignoring package "
8372                        + pkg.packageName);
8373            }
8374            final int childCount = pkg.childPackages.size();
8375            for (int i = 0; i < childCount; i++) {
8376                PackageParser.Package childPkg = pkg.childPackages.get(i);
8377                if (mSettings.hasOtherDisabledSystemPkgWithChildLPr(pkg.packageName,
8378                        childPkg.packageName)) {
8379                    throw new PackageManagerException("Cannot override a child package of "
8380                            + "another disabled system app. Ignoring package " + pkg.packageName);
8381                }
8382            }
8383        }
8384
8385        // writer
8386        synchronized (mPackages) {
8387            if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
8388                // Only system apps can add new shared libraries.
8389                if (pkg.libraryNames != null) {
8390                    for (int i=0; i<pkg.libraryNames.size(); i++) {
8391                        String name = pkg.libraryNames.get(i);
8392                        boolean allowed = false;
8393                        if (pkg.isUpdatedSystemApp()) {
8394                            // New library entries can only be added through the
8395                            // system image.  This is important to get rid of a lot
8396                            // of nasty edge cases: for example if we allowed a non-
8397                            // system update of the app to add a library, then uninstalling
8398                            // the update would make the library go away, and assumptions
8399                            // we made such as through app install filtering would now
8400                            // have allowed apps on the device which aren't compatible
8401                            // with it.  Better to just have the restriction here, be
8402                            // conservative, and create many fewer cases that can negatively
8403                            // impact the user experience.
8404                            final PackageSetting sysPs = mSettings
8405                                    .getDisabledSystemPkgLPr(pkg.packageName);
8406                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
8407                                for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) {
8408                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
8409                                        allowed = true;
8410                                        break;
8411                                    }
8412                                }
8413                            }
8414                        } else {
8415                            allowed = true;
8416                        }
8417                        if (allowed) {
8418                            if (!mSharedLibraries.containsKey(name)) {
8419                                mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName));
8420                            } else if (!name.equals(pkg.packageName)) {
8421                                Slog.w(TAG, "Package " + pkg.packageName + " library "
8422                                        + name + " already exists; skipping");
8423                            }
8424                        } else {
8425                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
8426                                    + name + " that is not declared on system image; skipping");
8427                        }
8428                    }
8429                    if ((scanFlags & SCAN_BOOTING) == 0) {
8430                        // If we are not booting, we need to update any applications
8431                        // that are clients of our shared library.  If we are booting,
8432                        // this will all be done once the scan is complete.
8433                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
8434                    }
8435                }
8436            }
8437        }
8438
8439        if ((scanFlags & SCAN_BOOTING) != 0) {
8440            // No apps can run during boot scan, so they don't need to be frozen
8441        } else if ((scanFlags & SCAN_DONT_KILL_APP) != 0) {
8442            // Caller asked to not kill app, so it's probably not frozen
8443        } else if ((scanFlags & SCAN_IGNORE_FROZEN) != 0) {
8444            // Caller asked us to ignore frozen check for some reason; they
8445            // probably didn't know the package name
8446        } else {
8447            // We're doing major surgery on this package, so it better be frozen
8448            // right now to keep it from launching
8449            checkPackageFrozen(pkgName);
8450        }
8451
8452        // Also need to kill any apps that are dependent on the library.
8453        if (clientLibPkgs != null) {
8454            for (int i=0; i<clientLibPkgs.size(); i++) {
8455                PackageParser.Package clientPkg = clientLibPkgs.get(i);
8456                killApplication(clientPkg.applicationInfo.packageName,
8457                        clientPkg.applicationInfo.uid, "update lib");
8458            }
8459        }
8460
8461        // Make sure we're not adding any bogus keyset info
8462        KeySetManagerService ksms = mSettings.mKeySetManagerService;
8463        ksms.assertScannedPackageValid(pkg);
8464
8465        // writer
8466        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
8467
8468        boolean createIdmapFailed = false;
8469        synchronized (mPackages) {
8470            // We don't expect installation to fail beyond this point
8471
8472            if (pkgSetting.pkg != null) {
8473                // Note that |user| might be null during the initial boot scan. If a codePath
8474                // for an app has changed during a boot scan, it's due to an app update that's
8475                // part of the system partition and marker changes must be applied to all users.
8476                maybeRenameForeignDexMarkers(pkgSetting.pkg, pkg,
8477                    (user != null) ? user : UserHandle.ALL);
8478            }
8479
8480            // Add the new setting to mSettings
8481            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
8482            // Add the new setting to mPackages
8483            mPackages.put(pkg.applicationInfo.packageName, pkg);
8484            // Make sure we don't accidentally delete its data.
8485            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
8486            while (iter.hasNext()) {
8487                PackageCleanItem item = iter.next();
8488                if (pkgName.equals(item.packageName)) {
8489                    iter.remove();
8490                }
8491            }
8492
8493            // Take care of first install / last update times.
8494            if (currentTime != 0) {
8495                if (pkgSetting.firstInstallTime == 0) {
8496                    pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
8497                } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) {
8498                    pkgSetting.lastUpdateTime = currentTime;
8499                }
8500            } else if (pkgSetting.firstInstallTime == 0) {
8501                // We need *something*.  Take time time stamp of the file.
8502                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
8503            } else if ((policyFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
8504                if (scanFileTime != pkgSetting.timeStamp) {
8505                    // A package on the system image has changed; consider this
8506                    // to be an update.
8507                    pkgSetting.lastUpdateTime = scanFileTime;
8508                }
8509            }
8510
8511            // Add the package's KeySets to the global KeySetManagerService
8512            ksms.addScannedPackageLPw(pkg);
8513
8514            int N = pkg.providers.size();
8515            StringBuilder r = null;
8516            int i;
8517            for (i=0; i<N; i++) {
8518                PackageParser.Provider p = pkg.providers.get(i);
8519                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
8520                        p.info.processName, pkg.applicationInfo.uid);
8521                mProviders.addProvider(p);
8522                p.syncable = p.info.isSyncable;
8523                if (p.info.authority != null) {
8524                    String names[] = p.info.authority.split(";");
8525                    p.info.authority = null;
8526                    for (int j = 0; j < names.length; j++) {
8527                        if (j == 1 && p.syncable) {
8528                            // We only want the first authority for a provider to possibly be
8529                            // syncable, so if we already added this provider using a different
8530                            // authority clear the syncable flag. We copy the provider before
8531                            // changing it because the mProviders object contains a reference
8532                            // to a provider that we don't want to change.
8533                            // Only do this for the second authority since the resulting provider
8534                            // object can be the same for all future authorities for this provider.
8535                            p = new PackageParser.Provider(p);
8536                            p.syncable = false;
8537                        }
8538                        if (!mProvidersByAuthority.containsKey(names[j])) {
8539                            mProvidersByAuthority.put(names[j], p);
8540                            if (p.info.authority == null) {
8541                                p.info.authority = names[j];
8542                            } else {
8543                                p.info.authority = p.info.authority + ";" + names[j];
8544                            }
8545                            if (DEBUG_PACKAGE_SCANNING) {
8546                                if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
8547                                    Log.d(TAG, "Registered content provider: " + names[j]
8548                                            + ", className = " + p.info.name + ", isSyncable = "
8549                                            + p.info.isSyncable);
8550                            }
8551                        } else {
8552                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
8553                            Slog.w(TAG, "Skipping provider name " + names[j] +
8554                                    " (in package " + pkg.applicationInfo.packageName +
8555                                    "): name already used by "
8556                                    + ((other != null && other.getComponentName() != null)
8557                                            ? other.getComponentName().getPackageName() : "?"));
8558                        }
8559                    }
8560                }
8561                if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8562                    if (r == null) {
8563                        r = new StringBuilder(256);
8564                    } else {
8565                        r.append(' ');
8566                    }
8567                    r.append(p.info.name);
8568                }
8569            }
8570            if (r != null) {
8571                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
8572            }
8573
8574            N = pkg.services.size();
8575            r = null;
8576            for (i=0; i<N; i++) {
8577                PackageParser.Service s = pkg.services.get(i);
8578                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
8579                        s.info.processName, pkg.applicationInfo.uid);
8580                mServices.addService(s);
8581                if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8582                    if (r == null) {
8583                        r = new StringBuilder(256);
8584                    } else {
8585                        r.append(' ');
8586                    }
8587                    r.append(s.info.name);
8588                }
8589            }
8590            if (r != null) {
8591                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
8592            }
8593
8594            N = pkg.receivers.size();
8595            r = null;
8596            for (i=0; i<N; i++) {
8597                PackageParser.Activity a = pkg.receivers.get(i);
8598                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
8599                        a.info.processName, pkg.applicationInfo.uid);
8600                mReceivers.addActivity(a, "receiver");
8601                if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8602                    if (r == null) {
8603                        r = new StringBuilder(256);
8604                    } else {
8605                        r.append(' ');
8606                    }
8607                    r.append(a.info.name);
8608                }
8609            }
8610            if (r != null) {
8611                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
8612            }
8613
8614            N = pkg.activities.size();
8615            r = null;
8616            for (i=0; i<N; i++) {
8617                PackageParser.Activity a = pkg.activities.get(i);
8618                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
8619                        a.info.processName, pkg.applicationInfo.uid);
8620                mActivities.addActivity(a, "activity");
8621                if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8622                    if (r == null) {
8623                        r = new StringBuilder(256);
8624                    } else {
8625                        r.append(' ');
8626                    }
8627                    r.append(a.info.name);
8628                }
8629            }
8630            if (r != null) {
8631                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
8632            }
8633
8634            N = pkg.permissionGroups.size();
8635            r = null;
8636            for (i=0; i<N; i++) {
8637                PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
8638                PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
8639                if (cur == null) {
8640                    mPermissionGroups.put(pg.info.name, pg);
8641                    if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8642                        if (r == null) {
8643                            r = new StringBuilder(256);
8644                        } else {
8645                            r.append(' ');
8646                        }
8647                        r.append(pg.info.name);
8648                    }
8649                } else {
8650                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
8651                            + pg.info.packageName + " ignored: original from "
8652                            + cur.info.packageName);
8653                    if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8654                        if (r == null) {
8655                            r = new StringBuilder(256);
8656                        } else {
8657                            r.append(' ');
8658                        }
8659                        r.append("DUP:");
8660                        r.append(pg.info.name);
8661                    }
8662                }
8663            }
8664            if (r != null) {
8665                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permission Groups: " + r);
8666            }
8667
8668            N = pkg.permissions.size();
8669            r = null;
8670            for (i=0; i<N; i++) {
8671                PackageParser.Permission p = pkg.permissions.get(i);
8672
8673                // Assume by default that we did not install this permission into the system.
8674                p.info.flags &= ~PermissionInfo.FLAG_INSTALLED;
8675
8676                // Now that permission groups have a special meaning, we ignore permission
8677                // groups for legacy apps to prevent unexpected behavior. In particular,
8678                // permissions for one app being granted to someone just becase they happen
8679                // to be in a group defined by another app (before this had no implications).
8680                if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) {
8681                    p.group = mPermissionGroups.get(p.info.group);
8682                    // Warn for a permission in an unknown group.
8683                    if (p.info.group != null && p.group == null) {
8684                        Slog.w(TAG, "Permission " + p.info.name + " from package "
8685                                + p.info.packageName + " in an unknown group " + p.info.group);
8686                    }
8687                }
8688
8689                ArrayMap<String, BasePermission> permissionMap =
8690                        p.tree ? mSettings.mPermissionTrees
8691                                : mSettings.mPermissions;
8692                BasePermission bp = permissionMap.get(p.info.name);
8693
8694                // Allow system apps to redefine non-system permissions
8695                if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) {
8696                    final boolean currentOwnerIsSystem = (bp.perm != null
8697                            && isSystemApp(bp.perm.owner));
8698                    if (isSystemApp(p.owner)) {
8699                        if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) {
8700                            // It's a built-in permission and no owner, take ownership now
8701                            bp.packageSetting = pkgSetting;
8702                            bp.perm = p;
8703                            bp.uid = pkg.applicationInfo.uid;
8704                            bp.sourcePackage = p.info.packageName;
8705                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
8706                        } else if (!currentOwnerIsSystem) {
8707                            String msg = "New decl " + p.owner + " of permission  "
8708                                    + p.info.name + " is system; overriding " + bp.sourcePackage;
8709                            reportSettingsProblem(Log.WARN, msg);
8710                            bp = null;
8711                        }
8712                    }
8713                }
8714
8715                if (bp == null) {
8716                    bp = new BasePermission(p.info.name, p.info.packageName,
8717                            BasePermission.TYPE_NORMAL);
8718                    permissionMap.put(p.info.name, bp);
8719                }
8720
8721                if (bp.perm == null) {
8722                    if (bp.sourcePackage == null
8723                            || bp.sourcePackage.equals(p.info.packageName)) {
8724                        BasePermission tree = findPermissionTreeLP(p.info.name);
8725                        if (tree == null
8726                                || tree.sourcePackage.equals(p.info.packageName)) {
8727                            bp.packageSetting = pkgSetting;
8728                            bp.perm = p;
8729                            bp.uid = pkg.applicationInfo.uid;
8730                            bp.sourcePackage = p.info.packageName;
8731                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
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(p.info.name);
8739                            }
8740                        } else {
8741                            Slog.w(TAG, "Permission " + p.info.name + " from package "
8742                                    + p.info.packageName + " ignored: base tree "
8743                                    + tree.name + " is from package "
8744                                    + tree.sourcePackage);
8745                        }
8746                    } else {
8747                        Slog.w(TAG, "Permission " + p.info.name + " from package "
8748                                + p.info.packageName + " ignored: original from "
8749                                + bp.sourcePackage);
8750                    }
8751                } else if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8752                    if (r == null) {
8753                        r = new StringBuilder(256);
8754                    } else {
8755                        r.append(' ');
8756                    }
8757                    r.append("DUP:");
8758                    r.append(p.info.name);
8759                }
8760                if (bp.perm == p) {
8761                    bp.protectionLevel = p.info.protectionLevel;
8762                }
8763            }
8764
8765            if (r != null) {
8766                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permissions: " + r);
8767            }
8768
8769            N = pkg.instrumentation.size();
8770            r = null;
8771            for (i=0; i<N; i++) {
8772                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
8773                a.info.packageName = pkg.applicationInfo.packageName;
8774                a.info.sourceDir = pkg.applicationInfo.sourceDir;
8775                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
8776                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
8777                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
8778                a.info.dataDir = pkg.applicationInfo.dataDir;
8779                a.info.deviceProtectedDataDir = pkg.applicationInfo.deviceProtectedDataDir;
8780                a.info.credentialProtectedDataDir = pkg.applicationInfo.credentialProtectedDataDir;
8781
8782                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
8783                a.info.secondaryNativeLibraryDir = pkg.applicationInfo.secondaryNativeLibraryDir;
8784                mInstrumentation.put(a.getComponentName(), a);
8785                if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8786                    if (r == null) {
8787                        r = new StringBuilder(256);
8788                    } else {
8789                        r.append(' ');
8790                    }
8791                    r.append(a.info.name);
8792                }
8793            }
8794            if (r != null) {
8795                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
8796            }
8797
8798            if (pkg.protectedBroadcasts != null) {
8799                N = pkg.protectedBroadcasts.size();
8800                for (i=0; i<N; i++) {
8801                    mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
8802                }
8803            }
8804
8805            pkgSetting.setTimeStamp(scanFileTime);
8806
8807            // Create idmap files for pairs of (packages, overlay packages).
8808            // Note: "android", ie framework-res.apk, is handled by native layers.
8809            if (pkg.mOverlayTarget != null) {
8810                // This is an overlay package.
8811                if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) {
8812                    if (!mOverlays.containsKey(pkg.mOverlayTarget)) {
8813                        mOverlays.put(pkg.mOverlayTarget,
8814                                new ArrayMap<String, PackageParser.Package>());
8815                    }
8816                    ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget);
8817                    map.put(pkg.packageName, pkg);
8818                    PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget);
8819                    if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) {
8820                        createIdmapFailed = true;
8821                    }
8822                }
8823            } else if (mOverlays.containsKey(pkg.packageName) &&
8824                    !pkg.packageName.equals("android")) {
8825                // This is a regular package, with one or more known overlay packages.
8826                createIdmapsForPackageLI(pkg);
8827            }
8828        }
8829
8830        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8831
8832        if (createIdmapFailed) {
8833            throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
8834                    "scanPackageLI failed to createIdmap");
8835        }
8836        return pkg;
8837    }
8838
8839    private void maybeRenameForeignDexMarkers(PackageParser.Package existing,
8840            PackageParser.Package update, UserHandle user) {
8841        if (existing.applicationInfo == null || update.applicationInfo == null) {
8842            // This isn't due to an app installation.
8843            return;
8844        }
8845
8846        final File oldCodePath = new File(existing.applicationInfo.getCodePath());
8847        final File newCodePath = new File(update.applicationInfo.getCodePath());
8848
8849        // The codePath hasn't changed, so there's nothing for us to do.
8850        if (Objects.equals(oldCodePath, newCodePath)) {
8851            return;
8852        }
8853
8854        File canonicalNewCodePath;
8855        try {
8856            canonicalNewCodePath = new File(PackageManagerServiceUtils.realpath(newCodePath));
8857        } catch (IOException e) {
8858            Slog.w(TAG, "Failed to get canonical path.", e);
8859            return;
8860        }
8861
8862        // This is a bit of a hack. The oldCodePath doesn't exist at this point (because
8863        // we've already renamed / deleted it) so we cannot call realpath on it. Here we assume
8864        // that the last component of the path (i.e, the name) doesn't need canonicalization
8865        // (i.e, that it isn't ".", ".." or a symbolic link). This is a valid assumption for now
8866        // but may change in the future. Hopefully this function won't exist at that point.
8867        final File canonicalOldCodePath = new File(canonicalNewCodePath.getParentFile(),
8868                oldCodePath.getName());
8869
8870        // Calculate the prefixes of the markers. These are just the paths with "/" replaced
8871        // with "@".
8872        String oldMarkerPrefix = canonicalOldCodePath.getAbsolutePath().replace('/', '@');
8873        if (!oldMarkerPrefix.endsWith("@")) {
8874            oldMarkerPrefix += "@";
8875        }
8876        String newMarkerPrefix = canonicalNewCodePath.getAbsolutePath().replace('/', '@');
8877        if (!newMarkerPrefix.endsWith("@")) {
8878            newMarkerPrefix += "@";
8879        }
8880
8881        List<String> updatedPaths = update.getAllCodePathsExcludingResourceOnly();
8882        List<String> markerSuffixes = new ArrayList<String>(updatedPaths.size());
8883        for (String updatedPath : updatedPaths) {
8884            String updatedPathName = new File(updatedPath).getName();
8885            markerSuffixes.add(updatedPathName.replace('/', '@'));
8886        }
8887
8888        for (int userId : resolveUserIds(user.getIdentifier())) {
8889            File profileDir = Environment.getDataProfilesDeForeignDexDirectory(userId);
8890
8891            for (String markerSuffix : markerSuffixes) {
8892                File oldForeignUseMark = new File(profileDir, oldMarkerPrefix + markerSuffix);
8893                File newForeignUseMark = new File(profileDir, newMarkerPrefix + markerSuffix);
8894                if (oldForeignUseMark.exists()) {
8895                    try {
8896                        Os.rename(oldForeignUseMark.getAbsolutePath(),
8897                                newForeignUseMark.getAbsolutePath());
8898                    } catch (ErrnoException e) {
8899                        Slog.w(TAG, "Failed to rename foreign use marker", e);
8900                        oldForeignUseMark.delete();
8901                    }
8902                }
8903            }
8904        }
8905    }
8906
8907    /**
8908     * Derive the ABI of a non-system package located at {@code scanFile}. This information
8909     * is derived purely on the basis of the contents of {@code scanFile} and
8910     * {@code cpuAbiOverride}.
8911     *
8912     * If {@code extractLibs} is true, native libraries are extracted from the app if required.
8913     */
8914    private void derivePackageAbi(PackageParser.Package pkg, File scanFile,
8915                                 String cpuAbiOverride, boolean extractLibs)
8916            throws PackageManagerException {
8917        // TODO: We can probably be smarter about this stuff. For installed apps,
8918        // we can calculate this information at install time once and for all. For
8919        // system apps, we can probably assume that this information doesn't change
8920        // after the first boot scan. As things stand, we do lots of unnecessary work.
8921
8922        // Give ourselves some initial paths; we'll come back for another
8923        // pass once we've determined ABI below.
8924        setNativeLibraryPaths(pkg);
8925
8926        // We would never need to extract libs for forward-locked and external packages,
8927        // since the container service will do it for us. We shouldn't attempt to
8928        // extract libs from system app when it was not updated.
8929        if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() ||
8930                (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) {
8931            extractLibs = false;
8932        }
8933
8934        final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
8935        final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
8936
8937        NativeLibraryHelper.Handle handle = null;
8938        try {
8939            handle = NativeLibraryHelper.Handle.create(pkg);
8940            // TODO(multiArch): This can be null for apps that didn't go through the
8941            // usual installation process. We can calculate it again, like we
8942            // do during install time.
8943            //
8944            // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
8945            // unnecessary.
8946            final File nativeLibraryRoot = new File(nativeLibraryRootStr);
8947
8948            // Null out the abis so that they can be recalculated.
8949            pkg.applicationInfo.primaryCpuAbi = null;
8950            pkg.applicationInfo.secondaryCpuAbi = null;
8951            if (isMultiArch(pkg.applicationInfo)) {
8952                // Warn if we've set an abiOverride for multi-lib packages..
8953                // By definition, we need to copy both 32 and 64 bit libraries for
8954                // such packages.
8955                if (pkg.cpuAbiOverride != null
8956                        && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
8957                    Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
8958                }
8959
8960                int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
8961                int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
8962                if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
8963                    if (extractLibs) {
8964                        abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
8965                                nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
8966                                useIsaSpecificSubdirs);
8967                    } else {
8968                        abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
8969                    }
8970                }
8971
8972                maybeThrowExceptionForMultiArchCopy(
8973                        "Error unpackaging 32 bit native libs for multiarch app.", abi32);
8974
8975                if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
8976                    if (extractLibs) {
8977                        abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
8978                                nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
8979                                useIsaSpecificSubdirs);
8980                    } else {
8981                        abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
8982                    }
8983                }
8984
8985                maybeThrowExceptionForMultiArchCopy(
8986                        "Error unpackaging 64 bit native libs for multiarch app.", abi64);
8987
8988                if (abi64 >= 0) {
8989                    pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
8990                }
8991
8992                if (abi32 >= 0) {
8993                    final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
8994                    if (abi64 >= 0) {
8995                        if (pkg.use32bitAbi) {
8996                            pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi;
8997                            pkg.applicationInfo.primaryCpuAbi = abi;
8998                        } else {
8999                            pkg.applicationInfo.secondaryCpuAbi = abi;
9000                        }
9001                    } else {
9002                        pkg.applicationInfo.primaryCpuAbi = abi;
9003                    }
9004                }
9005
9006            } else {
9007                String[] abiList = (cpuAbiOverride != null) ?
9008                        new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
9009
9010                // Enable gross and lame hacks for apps that are built with old
9011                // SDK tools. We must scan their APKs for renderscript bitcode and
9012                // not launch them if it's present. Don't bother checking on devices
9013                // that don't have 64 bit support.
9014                boolean needsRenderScriptOverride = false;
9015                if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
9016                        NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
9017                    abiList = Build.SUPPORTED_32_BIT_ABIS;
9018                    needsRenderScriptOverride = true;
9019                }
9020
9021                final int copyRet;
9022                if (extractLibs) {
9023                    copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
9024                            nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
9025                } else {
9026                    copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
9027                }
9028
9029                if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
9030                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
9031                            "Error unpackaging native libs for app, errorCode=" + copyRet);
9032                }
9033
9034                if (copyRet >= 0) {
9035                    pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
9036                } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
9037                    pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
9038                } else if (needsRenderScriptOverride) {
9039                    pkg.applicationInfo.primaryCpuAbi = abiList[0];
9040                }
9041            }
9042        } catch (IOException ioe) {
9043            Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
9044        } finally {
9045            IoUtils.closeQuietly(handle);
9046        }
9047
9048        // Now that we've calculated the ABIs and determined if it's an internal app,
9049        // we will go ahead and populate the nativeLibraryPath.
9050        setNativeLibraryPaths(pkg);
9051    }
9052
9053    /**
9054     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
9055     * i.e, so that all packages can be run inside a single process if required.
9056     *
9057     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
9058     * this function will either try and make the ABI for all packages in {@code packagesForUser}
9059     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
9060     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
9061     * updating a package that belongs to a shared user.
9062     *
9063     * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
9064     * adds unnecessary complexity.
9065     */
9066    private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser,
9067            PackageParser.Package scannedPackage, boolean bootComplete) {
9068        String requiredInstructionSet = null;
9069        if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
9070            requiredInstructionSet = VMRuntime.getInstructionSet(
9071                     scannedPackage.applicationInfo.primaryCpuAbi);
9072        }
9073
9074        PackageSetting requirer = null;
9075        for (PackageSetting ps : packagesForUser) {
9076            // If packagesForUser contains scannedPackage, we skip it. This will happen
9077            // when scannedPackage is an update of an existing package. Without this check,
9078            // we will never be able to change the ABI of any package belonging to a shared
9079            // user, even if it's compatible with other packages.
9080            if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
9081                if (ps.primaryCpuAbiString == null) {
9082                    continue;
9083                }
9084
9085                final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
9086                if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
9087                    // We have a mismatch between instruction sets (say arm vs arm64) warn about
9088                    // this but there's not much we can do.
9089                    String errorMessage = "Instruction set mismatch, "
9090                            + ((requirer == null) ? "[caller]" : requirer)
9091                            + " requires " + requiredInstructionSet + " whereas " + ps
9092                            + " requires " + instructionSet;
9093                    Slog.w(TAG, errorMessage);
9094                }
9095
9096                if (requiredInstructionSet == null) {
9097                    requiredInstructionSet = instructionSet;
9098                    requirer = ps;
9099                }
9100            }
9101        }
9102
9103        if (requiredInstructionSet != null) {
9104            String adjustedAbi;
9105            if (requirer != null) {
9106                // requirer != null implies that either scannedPackage was null or that scannedPackage
9107                // did not require an ABI, in which case we have to adjust scannedPackage to match
9108                // the ABI of the set (which is the same as requirer's ABI)
9109                adjustedAbi = requirer.primaryCpuAbiString;
9110                if (scannedPackage != null) {
9111                    scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
9112                }
9113            } else {
9114                // requirer == null implies that we're updating all ABIs in the set to
9115                // match scannedPackage.
9116                adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
9117            }
9118
9119            for (PackageSetting ps : packagesForUser) {
9120                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
9121                    if (ps.primaryCpuAbiString != null) {
9122                        continue;
9123                    }
9124
9125                    ps.primaryCpuAbiString = adjustedAbi;
9126                    if (ps.pkg != null && ps.pkg.applicationInfo != null &&
9127                            !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) {
9128                        ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
9129                        Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi
9130                                + " (requirer="
9131                                + (requirer == null ? "null" : requirer.pkg.packageName)
9132                                + ", scannedPackage="
9133                                + (scannedPackage != null ? scannedPackage.packageName : "null")
9134                                + ")");
9135                        try {
9136                            mInstaller.rmdex(ps.codePathString,
9137                                    getDexCodeInstructionSet(getPreferredInstructionSet()));
9138                        } catch (InstallerException ignored) {
9139                        }
9140                    }
9141                }
9142            }
9143        }
9144    }
9145
9146    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
9147        synchronized (mPackages) {
9148            mResolverReplaced = true;
9149            // Set up information for custom user intent resolution activity.
9150            mResolveActivity.applicationInfo = pkg.applicationInfo;
9151            mResolveActivity.name = mCustomResolverComponentName.getClassName();
9152            mResolveActivity.packageName = pkg.applicationInfo.packageName;
9153            mResolveActivity.processName = pkg.applicationInfo.packageName;
9154            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
9155            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
9156                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
9157            mResolveActivity.theme = 0;
9158            mResolveActivity.exported = true;
9159            mResolveActivity.enabled = true;
9160            mResolveInfo.activityInfo = mResolveActivity;
9161            mResolveInfo.priority = 0;
9162            mResolveInfo.preferredOrder = 0;
9163            mResolveInfo.match = 0;
9164            mResolveComponentName = mCustomResolverComponentName;
9165            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
9166                    mResolveComponentName);
9167        }
9168    }
9169
9170    private void setUpEphemeralInstallerActivityLP(ComponentName installerComponent) {
9171        final PackageParser.Package pkg = mPackages.get(installerComponent.getPackageName());
9172
9173        // Set up information for ephemeral installer activity
9174        mEphemeralInstallerActivity.applicationInfo = pkg.applicationInfo;
9175        mEphemeralInstallerActivity.name = mEphemeralInstallerComponent.getClassName();
9176        mEphemeralInstallerActivity.packageName = pkg.applicationInfo.packageName;
9177        mEphemeralInstallerActivity.processName = pkg.applicationInfo.packageName;
9178        mEphemeralInstallerActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
9179        mEphemeralInstallerActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
9180                ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
9181        mEphemeralInstallerActivity.theme = 0;
9182        mEphemeralInstallerActivity.exported = true;
9183        mEphemeralInstallerActivity.enabled = true;
9184        mEphemeralInstallerInfo.activityInfo = mEphemeralInstallerActivity;
9185        mEphemeralInstallerInfo.priority = 0;
9186        mEphemeralInstallerInfo.preferredOrder = 0;
9187        mEphemeralInstallerInfo.match = 0;
9188
9189        if (DEBUG_EPHEMERAL) {
9190            Slog.d(TAG, "Set ephemeral installer activity: " + mEphemeralInstallerComponent);
9191        }
9192    }
9193
9194    private static String calculateBundledApkRoot(final String codePathString) {
9195        final File codePath = new File(codePathString);
9196        final File codeRoot;
9197        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
9198            codeRoot = Environment.getRootDirectory();
9199        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
9200            codeRoot = Environment.getOemDirectory();
9201        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
9202            codeRoot = Environment.getVendorDirectory();
9203        } else {
9204            // Unrecognized code path; take its top real segment as the apk root:
9205            // e.g. /something/app/blah.apk => /something
9206            try {
9207                File f = codePath.getCanonicalFile();
9208                File parent = f.getParentFile();    // non-null because codePath is a file
9209                File tmp;
9210                while ((tmp = parent.getParentFile()) != null) {
9211                    f = parent;
9212                    parent = tmp;
9213                }
9214                codeRoot = f;
9215                Slog.w(TAG, "Unrecognized code path "
9216                        + codePath + " - using " + codeRoot);
9217            } catch (IOException e) {
9218                // Can't canonicalize the code path -- shenanigans?
9219                Slog.w(TAG, "Can't canonicalize code path " + codePath);
9220                return Environment.getRootDirectory().getPath();
9221            }
9222        }
9223        return codeRoot.getPath();
9224    }
9225
9226    /**
9227     * Derive and set the location of native libraries for the given package,
9228     * which varies depending on where and how the package was installed.
9229     */
9230    private void setNativeLibraryPaths(PackageParser.Package pkg) {
9231        final ApplicationInfo info = pkg.applicationInfo;
9232        final String codePath = pkg.codePath;
9233        final File codeFile = new File(codePath);
9234        final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp();
9235        final boolean asecApp = info.isForwardLocked() || info.isExternalAsec();
9236
9237        info.nativeLibraryRootDir = null;
9238        info.nativeLibraryRootRequiresIsa = false;
9239        info.nativeLibraryDir = null;
9240        info.secondaryNativeLibraryDir = null;
9241
9242        if (isApkFile(codeFile)) {
9243            // Monolithic install
9244            if (bundledApp) {
9245                // If "/system/lib64/apkname" exists, assume that is the per-package
9246                // native library directory to use; otherwise use "/system/lib/apkname".
9247                final String apkRoot = calculateBundledApkRoot(info.sourceDir);
9248                final boolean is64Bit = VMRuntime.is64BitInstructionSet(
9249                        getPrimaryInstructionSet(info));
9250
9251                // This is a bundled system app so choose the path based on the ABI.
9252                // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
9253                // is just the default path.
9254                final String apkName = deriveCodePathName(codePath);
9255                final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
9256                info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
9257                        apkName).getAbsolutePath();
9258
9259                if (info.secondaryCpuAbi != null) {
9260                    final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
9261                    info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
9262                            secondaryLibDir, apkName).getAbsolutePath();
9263                }
9264            } else if (asecApp) {
9265                info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
9266                        .getAbsolutePath();
9267            } else {
9268                final String apkName = deriveCodePathName(codePath);
9269                info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName)
9270                        .getAbsolutePath();
9271            }
9272
9273            info.nativeLibraryRootRequiresIsa = false;
9274            info.nativeLibraryDir = info.nativeLibraryRootDir;
9275        } else {
9276            // Cluster install
9277            info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
9278            info.nativeLibraryRootRequiresIsa = true;
9279
9280            info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
9281                    getPrimaryInstructionSet(info)).getAbsolutePath();
9282
9283            if (info.secondaryCpuAbi != null) {
9284                info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
9285                        VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
9286            }
9287        }
9288    }
9289
9290    /**
9291     * Calculate the abis and roots for a bundled app. These can uniquely
9292     * be determined from the contents of the system partition, i.e whether
9293     * it contains 64 or 32 bit shared libraries etc. We do not validate any
9294     * of this information, and instead assume that the system was built
9295     * sensibly.
9296     */
9297    private void setBundledAppAbisAndRoots(PackageParser.Package pkg,
9298                                           PackageSetting pkgSetting) {
9299        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
9300
9301        // If "/system/lib64/apkname" exists, assume that is the per-package
9302        // native library directory to use; otherwise use "/system/lib/apkname".
9303        final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
9304        setBundledAppAbi(pkg, apkRoot, apkName);
9305        // pkgSetting might be null during rescan following uninstall of updates
9306        // to a bundled app, so accommodate that possibility.  The settings in
9307        // that case will be established later from the parsed package.
9308        //
9309        // If the settings aren't null, sync them up with what we've just derived.
9310        // note that apkRoot isn't stored in the package settings.
9311        if (pkgSetting != null) {
9312            pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
9313            pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
9314        }
9315    }
9316
9317    /**
9318     * Deduces the ABI of a bundled app and sets the relevant fields on the
9319     * parsed pkg object.
9320     *
9321     * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
9322     *        under which system libraries are installed.
9323     * @param apkName the name of the installed package.
9324     */
9325    private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
9326        final File codeFile = new File(pkg.codePath);
9327
9328        final boolean has64BitLibs;
9329        final boolean has32BitLibs;
9330        if (isApkFile(codeFile)) {
9331            // Monolithic install
9332            has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
9333            has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
9334        } else {
9335            // Cluster install
9336            final File rootDir = new File(codeFile, LIB_DIR_NAME);
9337            if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
9338                    && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
9339                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
9340                has64BitLibs = (new File(rootDir, isa)).exists();
9341            } else {
9342                has64BitLibs = false;
9343            }
9344            if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
9345                    && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
9346                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
9347                has32BitLibs = (new File(rootDir, isa)).exists();
9348            } else {
9349                has32BitLibs = false;
9350            }
9351        }
9352
9353        if (has64BitLibs && !has32BitLibs) {
9354            // The package has 64 bit libs, but not 32 bit libs. Its primary
9355            // ABI should be 64 bit. We can safely assume here that the bundled
9356            // native libraries correspond to the most preferred ABI in the list.
9357
9358            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
9359            pkg.applicationInfo.secondaryCpuAbi = null;
9360        } else if (has32BitLibs && !has64BitLibs) {
9361            // The package has 32 bit libs but not 64 bit libs. Its primary
9362            // ABI should be 32 bit.
9363
9364            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
9365            pkg.applicationInfo.secondaryCpuAbi = null;
9366        } else if (has32BitLibs && has64BitLibs) {
9367            // The application has both 64 and 32 bit bundled libraries. We check
9368            // here that the app declares multiArch support, and warn if it doesn't.
9369            //
9370            // We will be lenient here and record both ABIs. The primary will be the
9371            // ABI that's higher on the list, i.e, a device that's configured to prefer
9372            // 64 bit apps will see a 64 bit primary ABI,
9373
9374            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
9375                Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch.");
9376            }
9377
9378            if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
9379                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
9380                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
9381            } else {
9382                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
9383                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
9384            }
9385        } else {
9386            pkg.applicationInfo.primaryCpuAbi = null;
9387            pkg.applicationInfo.secondaryCpuAbi = null;
9388        }
9389    }
9390
9391    private void killApplication(String pkgName, int appId, String reason) {
9392        killApplication(pkgName, appId, UserHandle.USER_ALL, reason);
9393    }
9394
9395    private void killApplication(String pkgName, int appId, int userId, String reason) {
9396        // Request the ActivityManager to kill the process(only for existing packages)
9397        // so that we do not end up in a confused state while the user is still using the older
9398        // version of the application while the new one gets installed.
9399        final long token = Binder.clearCallingIdentity();
9400        try {
9401            IActivityManager am = ActivityManagerNative.getDefault();
9402            if (am != null) {
9403                try {
9404                    am.killApplication(pkgName, appId, userId, reason);
9405                } catch (RemoteException e) {
9406                }
9407            }
9408        } finally {
9409            Binder.restoreCallingIdentity(token);
9410        }
9411    }
9412
9413    private void removePackageLI(PackageParser.Package pkg, boolean chatty) {
9414        // Remove the parent package setting
9415        PackageSetting ps = (PackageSetting) pkg.mExtras;
9416        if (ps != null) {
9417            removePackageLI(ps, chatty);
9418        }
9419        // Remove the child package setting
9420        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9421        for (int i = 0; i < childCount; i++) {
9422            PackageParser.Package childPkg = pkg.childPackages.get(i);
9423            ps = (PackageSetting) childPkg.mExtras;
9424            if (ps != null) {
9425                removePackageLI(ps, chatty);
9426            }
9427        }
9428    }
9429
9430    void removePackageLI(PackageSetting ps, boolean chatty) {
9431        if (DEBUG_INSTALL) {
9432            if (chatty)
9433                Log.d(TAG, "Removing package " + ps.name);
9434        }
9435
9436        // writer
9437        synchronized (mPackages) {
9438            mPackages.remove(ps.name);
9439            final PackageParser.Package pkg = ps.pkg;
9440            if (pkg != null) {
9441                cleanPackageDataStructuresLILPw(pkg, chatty);
9442            }
9443        }
9444    }
9445
9446    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
9447        if (DEBUG_INSTALL) {
9448            if (chatty)
9449                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
9450        }
9451
9452        // writer
9453        synchronized (mPackages) {
9454            // Remove the parent package
9455            mPackages.remove(pkg.applicationInfo.packageName);
9456            cleanPackageDataStructuresLILPw(pkg, chatty);
9457
9458            // Remove the child packages
9459            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9460            for (int i = 0; i < childCount; i++) {
9461                PackageParser.Package childPkg = pkg.childPackages.get(i);
9462                mPackages.remove(childPkg.applicationInfo.packageName);
9463                cleanPackageDataStructuresLILPw(childPkg, chatty);
9464            }
9465        }
9466    }
9467
9468    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
9469        int N = pkg.providers.size();
9470        StringBuilder r = null;
9471        int i;
9472        for (i=0; i<N; i++) {
9473            PackageParser.Provider p = pkg.providers.get(i);
9474            mProviders.removeProvider(p);
9475            if (p.info.authority == null) {
9476
9477                /* There was another ContentProvider with this authority when
9478                 * this app was installed so this authority is null,
9479                 * Ignore it as we don't have to unregister the provider.
9480                 */
9481                continue;
9482            }
9483            String names[] = p.info.authority.split(";");
9484            for (int j = 0; j < names.length; j++) {
9485                if (mProvidersByAuthority.get(names[j]) == p) {
9486                    mProvidersByAuthority.remove(names[j]);
9487                    if (DEBUG_REMOVE) {
9488                        if (chatty)
9489                            Log.d(TAG, "Unregistered content provider: " + names[j]
9490                                    + ", className = " + p.info.name + ", isSyncable = "
9491                                    + p.info.isSyncable);
9492                    }
9493                }
9494            }
9495            if (DEBUG_REMOVE && chatty) {
9496                if (r == null) {
9497                    r = new StringBuilder(256);
9498                } else {
9499                    r.append(' ');
9500                }
9501                r.append(p.info.name);
9502            }
9503        }
9504        if (r != null) {
9505            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
9506        }
9507
9508        N = pkg.services.size();
9509        r = null;
9510        for (i=0; i<N; i++) {
9511            PackageParser.Service s = pkg.services.get(i);
9512            mServices.removeService(s);
9513            if (chatty) {
9514                if (r == null) {
9515                    r = new StringBuilder(256);
9516                } else {
9517                    r.append(' ');
9518                }
9519                r.append(s.info.name);
9520            }
9521        }
9522        if (r != null) {
9523            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
9524        }
9525
9526        N = pkg.receivers.size();
9527        r = null;
9528        for (i=0; i<N; i++) {
9529            PackageParser.Activity a = pkg.receivers.get(i);
9530            mReceivers.removeActivity(a, "receiver");
9531            if (DEBUG_REMOVE && chatty) {
9532                if (r == null) {
9533                    r = new StringBuilder(256);
9534                } else {
9535                    r.append(' ');
9536                }
9537                r.append(a.info.name);
9538            }
9539        }
9540        if (r != null) {
9541            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
9542        }
9543
9544        N = pkg.activities.size();
9545        r = null;
9546        for (i=0; i<N; i++) {
9547            PackageParser.Activity a = pkg.activities.get(i);
9548            mActivities.removeActivity(a, "activity");
9549            if (DEBUG_REMOVE && chatty) {
9550                if (r == null) {
9551                    r = new StringBuilder(256);
9552                } else {
9553                    r.append(' ');
9554                }
9555                r.append(a.info.name);
9556            }
9557        }
9558        if (r != null) {
9559            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
9560        }
9561
9562        N = pkg.permissions.size();
9563        r = null;
9564        for (i=0; i<N; i++) {
9565            PackageParser.Permission p = pkg.permissions.get(i);
9566            BasePermission bp = mSettings.mPermissions.get(p.info.name);
9567            if (bp == null) {
9568                bp = mSettings.mPermissionTrees.get(p.info.name);
9569            }
9570            if (bp != null && bp.perm == p) {
9571                bp.perm = null;
9572                if (DEBUG_REMOVE && chatty) {
9573                    if (r == null) {
9574                        r = new StringBuilder(256);
9575                    } else {
9576                        r.append(' ');
9577                    }
9578                    r.append(p.info.name);
9579                }
9580            }
9581            if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
9582                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(p.info.name);
9583                if (appOpPkgs != null) {
9584                    appOpPkgs.remove(pkg.packageName);
9585                }
9586            }
9587        }
9588        if (r != null) {
9589            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
9590        }
9591
9592        N = pkg.requestedPermissions.size();
9593        r = null;
9594        for (i=0; i<N; i++) {
9595            String perm = pkg.requestedPermissions.get(i);
9596            BasePermission bp = mSettings.mPermissions.get(perm);
9597            if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
9598                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(perm);
9599                if (appOpPkgs != null) {
9600                    appOpPkgs.remove(pkg.packageName);
9601                    if (appOpPkgs.isEmpty()) {
9602                        mAppOpPermissionPackages.remove(perm);
9603                    }
9604                }
9605            }
9606        }
9607        if (r != null) {
9608            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
9609        }
9610
9611        N = pkg.instrumentation.size();
9612        r = null;
9613        for (i=0; i<N; i++) {
9614            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
9615            mInstrumentation.remove(a.getComponentName());
9616            if (DEBUG_REMOVE && chatty) {
9617                if (r == null) {
9618                    r = new StringBuilder(256);
9619                } else {
9620                    r.append(' ');
9621                }
9622                r.append(a.info.name);
9623            }
9624        }
9625        if (r != null) {
9626            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
9627        }
9628
9629        r = null;
9630        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
9631            // Only system apps can hold shared libraries.
9632            if (pkg.libraryNames != null) {
9633                for (i=0; i<pkg.libraryNames.size(); i++) {
9634                    String name = pkg.libraryNames.get(i);
9635                    SharedLibraryEntry cur = mSharedLibraries.get(name);
9636                    if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) {
9637                        mSharedLibraries.remove(name);
9638                        if (DEBUG_REMOVE && chatty) {
9639                            if (r == null) {
9640                                r = new StringBuilder(256);
9641                            } else {
9642                                r.append(' ');
9643                            }
9644                            r.append(name);
9645                        }
9646                    }
9647                }
9648            }
9649        }
9650        if (r != null) {
9651            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
9652        }
9653    }
9654
9655    private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
9656        for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
9657            if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
9658                return true;
9659            }
9660        }
9661        return false;
9662    }
9663
9664    static final int UPDATE_PERMISSIONS_ALL = 1<<0;
9665    static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
9666    static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
9667
9668    private void updatePermissionsLPw(PackageParser.Package pkg, int flags) {
9669        // Update the parent permissions
9670        updatePermissionsLPw(pkg.packageName, pkg, flags);
9671        // Update the child permissions
9672        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9673        for (int i = 0; i < childCount; i++) {
9674            PackageParser.Package childPkg = pkg.childPackages.get(i);
9675            updatePermissionsLPw(childPkg.packageName, childPkg, flags);
9676        }
9677    }
9678
9679    private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo,
9680            int flags) {
9681        final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null;
9682        updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags);
9683    }
9684
9685    private void updatePermissionsLPw(String changingPkg,
9686            PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) {
9687        // Make sure there are no dangling permission trees.
9688        Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator();
9689        while (it.hasNext()) {
9690            final BasePermission bp = it.next();
9691            if (bp.packageSetting == null) {
9692                // We may not yet have parsed the package, so just see if
9693                // we still know about its settings.
9694                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
9695            }
9696            if (bp.packageSetting == null) {
9697                Slog.w(TAG, "Removing dangling permission tree: " + bp.name
9698                        + " from package " + bp.sourcePackage);
9699                it.remove();
9700            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
9701                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
9702                    Slog.i(TAG, "Removing old permission tree: " + bp.name
9703                            + " from package " + bp.sourcePackage);
9704                    flags |= UPDATE_PERMISSIONS_ALL;
9705                    it.remove();
9706                }
9707            }
9708        }
9709
9710        // Make sure all dynamic permissions have been assigned to a package,
9711        // and make sure there are no dangling permissions.
9712        it = mSettings.mPermissions.values().iterator();
9713        while (it.hasNext()) {
9714            final BasePermission bp = it.next();
9715            if (bp.type == BasePermission.TYPE_DYNAMIC) {
9716                if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
9717                        + bp.name + " pkg=" + bp.sourcePackage
9718                        + " info=" + bp.pendingInfo);
9719                if (bp.packageSetting == null && bp.pendingInfo != null) {
9720                    final BasePermission tree = findPermissionTreeLP(bp.name);
9721                    if (tree != null && tree.perm != null) {
9722                        bp.packageSetting = tree.packageSetting;
9723                        bp.perm = new PackageParser.Permission(tree.perm.owner,
9724                                new PermissionInfo(bp.pendingInfo));
9725                        bp.perm.info.packageName = tree.perm.info.packageName;
9726                        bp.perm.info.name = bp.name;
9727                        bp.uid = tree.uid;
9728                    }
9729                }
9730            }
9731            if (bp.packageSetting == null) {
9732                // We may not yet have parsed the package, so just see if
9733                // we still know about its settings.
9734                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
9735            }
9736            if (bp.packageSetting == null) {
9737                Slog.w(TAG, "Removing dangling permission: " + bp.name
9738                        + " from package " + bp.sourcePackage);
9739                it.remove();
9740            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
9741                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
9742                    Slog.i(TAG, "Removing old permission: " + bp.name
9743                            + " from package " + bp.sourcePackage);
9744                    flags |= UPDATE_PERMISSIONS_ALL;
9745                    it.remove();
9746                }
9747            }
9748        }
9749
9750        // Now update the permissions for all packages, in particular
9751        // replace the granted permissions of the system packages.
9752        if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
9753            for (PackageParser.Package pkg : mPackages.values()) {
9754                if (pkg != pkgInfo) {
9755                    // Only replace for packages on requested volume
9756                    final String volumeUuid = getVolumeUuidForPackage(pkg);
9757                    final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0)
9758                            && Objects.equals(replaceVolumeUuid, volumeUuid);
9759                    grantPermissionsLPw(pkg, replace, changingPkg);
9760                }
9761            }
9762        }
9763
9764        if (pkgInfo != null) {
9765            // Only replace for packages on requested volume
9766            final String volumeUuid = getVolumeUuidForPackage(pkgInfo);
9767            final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0)
9768                    && Objects.equals(replaceVolumeUuid, volumeUuid);
9769            grantPermissionsLPw(pkgInfo, replace, changingPkg);
9770        }
9771    }
9772
9773    private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace,
9774            String packageOfInterest) {
9775        // IMPORTANT: There are two types of permissions: install and runtime.
9776        // Install time permissions are granted when the app is installed to
9777        // all device users and users added in the future. Runtime permissions
9778        // are granted at runtime explicitly to specific users. Normal and signature
9779        // protected permissions are install time permissions. Dangerous permissions
9780        // are install permissions if the app's target SDK is Lollipop MR1 or older,
9781        // otherwise they are runtime permissions. This function does not manage
9782        // runtime permissions except for the case an app targeting Lollipop MR1
9783        // being upgraded to target a newer SDK, in which case dangerous permissions
9784        // are transformed from install time to runtime ones.
9785
9786        final PackageSetting ps = (PackageSetting) pkg.mExtras;
9787        if (ps == null) {
9788            return;
9789        }
9790
9791        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions");
9792
9793        PermissionsState permissionsState = ps.getPermissionsState();
9794        PermissionsState origPermissions = permissionsState;
9795
9796        final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
9797
9798        boolean runtimePermissionsRevoked = false;
9799        int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY;
9800
9801        boolean changedInstallPermission = false;
9802
9803        if (replace) {
9804            ps.installPermissionsFixed = false;
9805            if (!ps.isSharedUser()) {
9806                origPermissions = new PermissionsState(permissionsState);
9807                permissionsState.reset();
9808            } else {
9809                // We need to know only about runtime permission changes since the
9810                // calling code always writes the install permissions state but
9811                // the runtime ones are written only if changed. The only cases of
9812                // changed runtime permissions here are promotion of an install to
9813                // runtime and revocation of a runtime from a shared user.
9814                changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw(
9815                        ps.sharedUser, UserManagerService.getInstance().getUserIds());
9816                if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) {
9817                    runtimePermissionsRevoked = true;
9818                }
9819            }
9820        }
9821
9822        permissionsState.setGlobalGids(mGlobalGids);
9823
9824        final int N = pkg.requestedPermissions.size();
9825        for (int i=0; i<N; i++) {
9826            final String name = pkg.requestedPermissions.get(i);
9827            final BasePermission bp = mSettings.mPermissions.get(name);
9828
9829            if (DEBUG_INSTALL) {
9830                Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
9831            }
9832
9833            if (bp == null || bp.packageSetting == null) {
9834                if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
9835                    Slog.w(TAG, "Unknown permission " + name
9836                            + " in package " + pkg.packageName);
9837                }
9838                continue;
9839            }
9840
9841            final String perm = bp.name;
9842            boolean allowedSig = false;
9843            int grant = GRANT_DENIED;
9844
9845            // Keep track of app op permissions.
9846            if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
9847                ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name);
9848                if (pkgs == null) {
9849                    pkgs = new ArraySet<>();
9850                    mAppOpPermissionPackages.put(bp.name, pkgs);
9851                }
9852                pkgs.add(pkg.packageName);
9853            }
9854
9855            final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE;
9856            final boolean appSupportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion
9857                    >= Build.VERSION_CODES.M;
9858            switch (level) {
9859                case PermissionInfo.PROTECTION_NORMAL: {
9860                    // For all apps normal permissions are install time ones.
9861                    grant = GRANT_INSTALL;
9862                } break;
9863
9864                case PermissionInfo.PROTECTION_DANGEROUS: {
9865                    // If a permission review is required for legacy apps we represent
9866                    // their permissions as always granted runtime ones since we need
9867                    // to keep the review required permission flag per user while an
9868                    // install permission's state is shared across all users.
9869                    if (!appSupportsRuntimePermissions && !Build.PERMISSIONS_REVIEW_REQUIRED) {
9870                        // For legacy apps dangerous permissions are install time ones.
9871                        grant = GRANT_INSTALL;
9872                    } else if (origPermissions.hasInstallPermission(bp.name)) {
9873                        // For legacy apps that became modern, install becomes runtime.
9874                        grant = GRANT_UPGRADE;
9875                    } else if (mPromoteSystemApps
9876                            && isSystemApp(ps)
9877                            && mExistingSystemPackages.contains(ps.name)) {
9878                        // For legacy system apps, install becomes runtime.
9879                        // We cannot check hasInstallPermission() for system apps since those
9880                        // permissions were granted implicitly and not persisted pre-M.
9881                        grant = GRANT_UPGRADE;
9882                    } else {
9883                        // For modern apps keep runtime permissions unchanged.
9884                        grant = GRANT_RUNTIME;
9885                    }
9886                } break;
9887
9888                case PermissionInfo.PROTECTION_SIGNATURE: {
9889                    // For all apps signature permissions are install time ones.
9890                    allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions);
9891                    if (allowedSig) {
9892                        grant = GRANT_INSTALL;
9893                    }
9894                } break;
9895            }
9896
9897            if (DEBUG_INSTALL) {
9898                Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
9899            }
9900
9901            if (grant != GRANT_DENIED) {
9902                if (!isSystemApp(ps) && ps.installPermissionsFixed) {
9903                    // If this is an existing, non-system package, then
9904                    // we can't add any new permissions to it.
9905                    if (!allowedSig && !origPermissions.hasInstallPermission(perm)) {
9906                        // Except...  if this is a permission that was added
9907                        // to the platform (note: need to only do this when
9908                        // updating the platform).
9909                        if (!isNewPlatformPermissionForPackage(perm, pkg)) {
9910                            grant = GRANT_DENIED;
9911                        }
9912                    }
9913                }
9914
9915                switch (grant) {
9916                    case GRANT_INSTALL: {
9917                        // Revoke this as runtime permission to handle the case of
9918                        // a runtime permission being downgraded to an install one.
9919                        // Also in permission review mode we keep dangerous permissions
9920                        // for legacy apps
9921                        for (int userId : UserManagerService.getInstance().getUserIds()) {
9922                            if (origPermissions.getRuntimePermissionState(
9923                                    bp.name, userId) != null) {
9924                                // Revoke the runtime permission and clear the flags.
9925                                origPermissions.revokeRuntimePermission(bp, userId);
9926                                origPermissions.updatePermissionFlags(bp, userId,
9927                                      PackageManager.MASK_PERMISSION_FLAGS, 0);
9928                                // If we revoked a permission permission, we have to write.
9929                                changedRuntimePermissionUserIds = ArrayUtils.appendInt(
9930                                        changedRuntimePermissionUserIds, userId);
9931                            }
9932                        }
9933                        // Grant an install permission.
9934                        if (permissionsState.grantInstallPermission(bp) !=
9935                                PermissionsState.PERMISSION_OPERATION_FAILURE) {
9936                            changedInstallPermission = true;
9937                        }
9938                    } break;
9939
9940                    case GRANT_RUNTIME: {
9941                        // Grant previously granted runtime permissions.
9942                        for (int userId : UserManagerService.getInstance().getUserIds()) {
9943                            PermissionState permissionState = origPermissions
9944                                    .getRuntimePermissionState(bp.name, userId);
9945                            int flags = permissionState != null
9946                                    ? permissionState.getFlags() : 0;
9947                            if (origPermissions.hasRuntimePermission(bp.name, userId)) {
9948                                if (permissionsState.grantRuntimePermission(bp, userId) ==
9949                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
9950                                    // If we cannot put the permission as it was, we have to write.
9951                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
9952                                            changedRuntimePermissionUserIds, userId);
9953                                }
9954                                // If the app supports runtime permissions no need for a review.
9955                                if (Build.PERMISSIONS_REVIEW_REQUIRED
9956                                        && appSupportsRuntimePermissions
9957                                        && (flags & PackageManager
9958                                                .FLAG_PERMISSION_REVIEW_REQUIRED) != 0) {
9959                                    flags &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
9960                                    // Since we changed the flags, we have to write.
9961                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
9962                                            changedRuntimePermissionUserIds, userId);
9963                                }
9964                            } else if (Build.PERMISSIONS_REVIEW_REQUIRED
9965                                    && !appSupportsRuntimePermissions) {
9966                                // For legacy apps that need a permission review, every new
9967                                // runtime permission is granted but it is pending a review.
9968                                // We also need to review only platform defined runtime
9969                                // permissions as these are the only ones the platform knows
9970                                // how to disable the API to simulate revocation as legacy
9971                                // apps don't expect to run with revoked permissions.
9972                                if (PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage)) {
9973                                    if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
9974                                        flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
9975                                        // We changed the flags, hence have to write.
9976                                        changedRuntimePermissionUserIds = ArrayUtils.appendInt(
9977                                                changedRuntimePermissionUserIds, userId);
9978                                    }
9979                                }
9980                                if (permissionsState.grantRuntimePermission(bp, userId)
9981                                        != PermissionsState.PERMISSION_OPERATION_FAILURE) {
9982                                    // We changed the permission, hence have to write.
9983                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
9984                                            changedRuntimePermissionUserIds, userId);
9985                                }
9986                            }
9987                            // Propagate the permission flags.
9988                            permissionsState.updatePermissionFlags(bp, userId, flags, flags);
9989                        }
9990                    } break;
9991
9992                    case GRANT_UPGRADE: {
9993                        // Grant runtime permissions for a previously held install permission.
9994                        PermissionState permissionState = origPermissions
9995                                .getInstallPermissionState(bp.name);
9996                        final int flags = permissionState != null ? permissionState.getFlags() : 0;
9997
9998                        if (origPermissions.revokeInstallPermission(bp)
9999                                != PermissionsState.PERMISSION_OPERATION_FAILURE) {
10000                            // We will be transferring the permission flags, so clear them.
10001                            origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL,
10002                                    PackageManager.MASK_PERMISSION_FLAGS, 0);
10003                            changedInstallPermission = true;
10004                        }
10005
10006                        // If the permission is not to be promoted to runtime we ignore it and
10007                        // also its other flags as they are not applicable to install permissions.
10008                        if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) {
10009                            for (int userId : currentUserIds) {
10010                                if (permissionsState.grantRuntimePermission(bp, userId) !=
10011                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
10012                                    // Transfer the permission flags.
10013                                    permissionsState.updatePermissionFlags(bp, userId,
10014                                            flags, flags);
10015                                    // If we granted the permission, we have to write.
10016                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
10017                                            changedRuntimePermissionUserIds, userId);
10018                                }
10019                            }
10020                        }
10021                    } break;
10022
10023                    default: {
10024                        if (packageOfInterest == null
10025                                || packageOfInterest.equals(pkg.packageName)) {
10026                            Slog.w(TAG, "Not granting permission " + perm
10027                                    + " to package " + pkg.packageName
10028                                    + " because it was previously installed without");
10029                        }
10030                    } break;
10031                }
10032            } else {
10033                if (permissionsState.revokeInstallPermission(bp) !=
10034                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
10035                    // Also drop the permission flags.
10036                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
10037                            PackageManager.MASK_PERMISSION_FLAGS, 0);
10038                    changedInstallPermission = true;
10039                    Slog.i(TAG, "Un-granting permission " + perm
10040                            + " from package " + pkg.packageName
10041                            + " (protectionLevel=" + bp.protectionLevel
10042                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
10043                            + ")");
10044                } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) {
10045                    // Don't print warning for app op permissions, since it is fine for them
10046                    // not to be granted, there is a UI for the user to decide.
10047                    if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
10048                        Slog.w(TAG, "Not granting permission " + perm
10049                                + " to package " + pkg.packageName
10050                                + " (protectionLevel=" + bp.protectionLevel
10051                                + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
10052                                + ")");
10053                    }
10054                }
10055            }
10056        }
10057
10058        if ((changedInstallPermission || replace) && !ps.installPermissionsFixed &&
10059                !isSystemApp(ps) || isUpdatedSystemApp(ps)){
10060            // This is the first that we have heard about this package, so the
10061            // permissions we have now selected are fixed until explicitly
10062            // changed.
10063            ps.installPermissionsFixed = true;
10064        }
10065
10066        // Persist the runtime permissions state for users with changes. If permissions
10067        // were revoked because no app in the shared user declares them we have to
10068        // write synchronously to avoid losing runtime permissions state.
10069        for (int userId : changedRuntimePermissionUserIds) {
10070            mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked);
10071        }
10072
10073        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10074    }
10075
10076    private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) {
10077        boolean allowed = false;
10078        final int NP = PackageParser.NEW_PERMISSIONS.length;
10079        for (int ip=0; ip<NP; ip++) {
10080            final PackageParser.NewPermissionInfo npi
10081                    = PackageParser.NEW_PERMISSIONS[ip];
10082            if (npi.name.equals(perm)
10083                    && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
10084                allowed = true;
10085                Log.i(TAG, "Auto-granting " + perm + " to old pkg "
10086                        + pkg.packageName);
10087                break;
10088            }
10089        }
10090        return allowed;
10091    }
10092
10093    private boolean grantSignaturePermission(String perm, PackageParser.Package pkg,
10094            BasePermission bp, PermissionsState origPermissions) {
10095        boolean allowed;
10096        allowed = (compareSignatures(
10097                bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
10098                        == PackageManager.SIGNATURE_MATCH)
10099                || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
10100                        == PackageManager.SIGNATURE_MATCH);
10101        if (!allowed && (bp.protectionLevel
10102                & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0) {
10103            if (isSystemApp(pkg)) {
10104                // For updated system applications, a system permission
10105                // is granted only if it had been defined by the original application.
10106                if (pkg.isUpdatedSystemApp()) {
10107                    final PackageSetting sysPs = mSettings
10108                            .getDisabledSystemPkgLPr(pkg.packageName);
10109                    if (sysPs != null && sysPs.getPermissionsState().hasInstallPermission(perm)) {
10110                        // If the original was granted this permission, we take
10111                        // that grant decision as read and propagate it to the
10112                        // update.
10113                        if (sysPs.isPrivileged()) {
10114                            allowed = true;
10115                        }
10116                    } else {
10117                        // The system apk may have been updated with an older
10118                        // version of the one on the data partition, but which
10119                        // granted a new system permission that it didn't have
10120                        // before.  In this case we do want to allow the app to
10121                        // now get the new permission if the ancestral apk is
10122                        // privileged to get it.
10123                        if (sysPs != null && sysPs.pkg != null && sysPs.isPrivileged()) {
10124                            for (int j = 0; j < sysPs.pkg.requestedPermissions.size(); j++) {
10125                                if (perm.equals(sysPs.pkg.requestedPermissions.get(j))) {
10126                                    allowed = true;
10127                                    break;
10128                                }
10129                            }
10130                        }
10131                        // Also if a privileged parent package on the system image or any of
10132                        // its children requested a privileged permission, the updated child
10133                        // packages can also get the permission.
10134                        if (pkg.parentPackage != null) {
10135                            final PackageSetting disabledSysParentPs = mSettings
10136                                    .getDisabledSystemPkgLPr(pkg.parentPackage.packageName);
10137                            if (disabledSysParentPs != null && disabledSysParentPs.pkg != null
10138                                    && disabledSysParentPs.isPrivileged()) {
10139                                if (isPackageRequestingPermission(disabledSysParentPs.pkg, perm)) {
10140                                    allowed = true;
10141                                } else if (disabledSysParentPs.pkg.childPackages != null) {
10142                                    final int count = disabledSysParentPs.pkg.childPackages.size();
10143                                    for (int i = 0; i < count; i++) {
10144                                        PackageParser.Package disabledSysChildPkg =
10145                                                disabledSysParentPs.pkg.childPackages.get(i);
10146                                        if (isPackageRequestingPermission(disabledSysChildPkg,
10147                                                perm)) {
10148                                            allowed = true;
10149                                            break;
10150                                        }
10151                                    }
10152                                }
10153                            }
10154                        }
10155                    }
10156                } else {
10157                    allowed = isPrivilegedApp(pkg);
10158                }
10159            }
10160        }
10161        if (!allowed) {
10162            if (!allowed && (bp.protectionLevel
10163                    & PermissionInfo.PROTECTION_FLAG_PRE23) != 0
10164                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
10165                // If this was a previously normal/dangerous permission that got moved
10166                // to a system permission as part of the runtime permission redesign, then
10167                // we still want to blindly grant it to old apps.
10168                allowed = true;
10169            }
10170            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0
10171                    && pkg.packageName.equals(mRequiredInstallerPackage)) {
10172                // If this permission is to be granted to the system installer and
10173                // this app is an installer, then it gets the permission.
10174                allowed = true;
10175            }
10176            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0
10177                    && pkg.packageName.equals(mRequiredVerifierPackage)) {
10178                // If this permission is to be granted to the system verifier and
10179                // this app is a verifier, then it gets the permission.
10180                allowed = true;
10181            }
10182            if (!allowed && (bp.protectionLevel
10183                    & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0
10184                    && isSystemApp(pkg)) {
10185                // Any pre-installed system app is allowed to get this permission.
10186                allowed = true;
10187            }
10188            if (!allowed && (bp.protectionLevel
10189                    & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) {
10190                // For development permissions, a development permission
10191                // is granted only if it was already granted.
10192                allowed = origPermissions.hasInstallPermission(perm);
10193            }
10194            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_SETUP) != 0
10195                    && pkg.packageName.equals(mSetupWizardPackage)) {
10196                // If this permission is to be granted to the system setup wizard and
10197                // this app is a setup wizard, then it gets the permission.
10198                allowed = true;
10199            }
10200        }
10201        return allowed;
10202    }
10203
10204    private boolean isPackageRequestingPermission(PackageParser.Package pkg, String permission) {
10205        final int permCount = pkg.requestedPermissions.size();
10206        for (int j = 0; j < permCount; j++) {
10207            String requestedPermission = pkg.requestedPermissions.get(j);
10208            if (permission.equals(requestedPermission)) {
10209                return true;
10210            }
10211        }
10212        return false;
10213    }
10214
10215    final class ActivityIntentResolver
10216            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
10217        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
10218                boolean defaultOnly, int userId) {
10219            if (!sUserManager.exists(userId)) return null;
10220            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
10221            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
10222        }
10223
10224        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
10225                int userId) {
10226            if (!sUserManager.exists(userId)) return null;
10227            mFlags = flags;
10228            return super.queryIntent(intent, resolvedType,
10229                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
10230        }
10231
10232        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
10233                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
10234            if (!sUserManager.exists(userId)) return null;
10235            if (packageActivities == null) {
10236                return null;
10237            }
10238            mFlags = flags;
10239            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
10240            final int N = packageActivities.size();
10241            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
10242                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
10243
10244            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
10245            for (int i = 0; i < N; ++i) {
10246                intentFilters = packageActivities.get(i).intents;
10247                if (intentFilters != null && intentFilters.size() > 0) {
10248                    PackageParser.ActivityIntentInfo[] array =
10249                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
10250                    intentFilters.toArray(array);
10251                    listCut.add(array);
10252                }
10253            }
10254            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
10255        }
10256
10257        /**
10258         * Finds a privileged activity that matches the specified activity names.
10259         */
10260        private PackageParser.Activity findMatchingActivity(
10261                List<PackageParser.Activity> activityList, ActivityInfo activityInfo) {
10262            for (PackageParser.Activity sysActivity : activityList) {
10263                if (sysActivity.info.name.equals(activityInfo.name)) {
10264                    return sysActivity;
10265                }
10266                if (sysActivity.info.name.equals(activityInfo.targetActivity)) {
10267                    return sysActivity;
10268                }
10269                if (sysActivity.info.targetActivity != null) {
10270                    if (sysActivity.info.targetActivity.equals(activityInfo.name)) {
10271                        return sysActivity;
10272                    }
10273                    if (sysActivity.info.targetActivity.equals(activityInfo.targetActivity)) {
10274                        return sysActivity;
10275                    }
10276                }
10277            }
10278            return null;
10279        }
10280
10281        public class IterGenerator<E> {
10282            public Iterator<E> generate(ActivityIntentInfo info) {
10283                return null;
10284            }
10285        }
10286
10287        public class ActionIterGenerator extends IterGenerator<String> {
10288            @Override
10289            public Iterator<String> generate(ActivityIntentInfo info) {
10290                return info.actionsIterator();
10291            }
10292        }
10293
10294        public class CategoriesIterGenerator extends IterGenerator<String> {
10295            @Override
10296            public Iterator<String> generate(ActivityIntentInfo info) {
10297                return info.categoriesIterator();
10298            }
10299        }
10300
10301        public class SchemesIterGenerator extends IterGenerator<String> {
10302            @Override
10303            public Iterator<String> generate(ActivityIntentInfo info) {
10304                return info.schemesIterator();
10305            }
10306        }
10307
10308        public class AuthoritiesIterGenerator extends IterGenerator<IntentFilter.AuthorityEntry> {
10309            @Override
10310            public Iterator<IntentFilter.AuthorityEntry> generate(ActivityIntentInfo info) {
10311                return info.authoritiesIterator();
10312            }
10313        }
10314
10315        /**
10316         * <em>WARNING</em> for performance reasons, the passed in intentList WILL BE
10317         * MODIFIED. Do not pass in a list that should not be changed.
10318         */
10319        private <T> void getIntentListSubset(List<ActivityIntentInfo> intentList,
10320                IterGenerator<T> generator, Iterator<T> searchIterator) {
10321            // loop through the set of actions; every one must be found in the intent filter
10322            while (searchIterator.hasNext()) {
10323                // we must have at least one filter in the list to consider a match
10324                if (intentList.size() == 0) {
10325                    break;
10326                }
10327
10328                final T searchAction = searchIterator.next();
10329
10330                // loop through the set of intent filters
10331                final Iterator<ActivityIntentInfo> intentIter = intentList.iterator();
10332                while (intentIter.hasNext()) {
10333                    final ActivityIntentInfo intentInfo = intentIter.next();
10334                    boolean selectionFound = false;
10335
10336                    // loop through the intent filter's selection criteria; at least one
10337                    // of them must match the searched criteria
10338                    final Iterator<T> intentSelectionIter = generator.generate(intentInfo);
10339                    while (intentSelectionIter != null && intentSelectionIter.hasNext()) {
10340                        final T intentSelection = intentSelectionIter.next();
10341                        if (intentSelection != null && intentSelection.equals(searchAction)) {
10342                            selectionFound = true;
10343                            break;
10344                        }
10345                    }
10346
10347                    // the selection criteria wasn't found in this filter's set; this filter
10348                    // is not a potential match
10349                    if (!selectionFound) {
10350                        intentIter.remove();
10351                    }
10352                }
10353            }
10354        }
10355
10356        private boolean isProtectedAction(ActivityIntentInfo filter) {
10357            final Iterator<String> actionsIter = filter.actionsIterator();
10358            while (actionsIter != null && actionsIter.hasNext()) {
10359                final String filterAction = actionsIter.next();
10360                if (PROTECTED_ACTIONS.contains(filterAction)) {
10361                    return true;
10362                }
10363            }
10364            return false;
10365        }
10366
10367        /**
10368         * Adjusts the priority of the given intent filter according to policy.
10369         * <p>
10370         * <ul>
10371         * <li>The priority for non privileged applications is capped to '0'</li>
10372         * <li>The priority for protected actions on privileged applications is capped to '0'</li>
10373         * <li>The priority for unbundled updates to privileged applications is capped to the
10374         *      priority defined on the system partition</li>
10375         * </ul>
10376         * <p>
10377         * <em>NOTE:</em> There is one exception. For security reasons, the setup wizard is
10378         * allowed to obtain any priority on any action.
10379         */
10380        private void adjustPriority(
10381                List<PackageParser.Activity> systemActivities, ActivityIntentInfo intent) {
10382            // nothing to do; priority is fine as-is
10383            if (intent.getPriority() <= 0) {
10384                return;
10385            }
10386
10387            final ActivityInfo activityInfo = intent.activity.info;
10388            final ApplicationInfo applicationInfo = activityInfo.applicationInfo;
10389
10390            final boolean privilegedApp =
10391                    ((applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0);
10392            if (!privilegedApp) {
10393                // non-privileged applications can never define a priority >0
10394                Slog.w(TAG, "Non-privileged app; cap priority to 0;"
10395                        + " package: " + applicationInfo.packageName
10396                        + " activity: " + intent.activity.className
10397                        + " origPrio: " + intent.getPriority());
10398                intent.setPriority(0);
10399                return;
10400            }
10401
10402            if (systemActivities == null) {
10403                // the system package is not disabled; we're parsing the system partition
10404                if (isProtectedAction(intent)) {
10405                    if (mDeferProtectedFilters) {
10406                        // We can't deal with these just yet. No component should ever obtain a
10407                        // >0 priority for a protected actions, with ONE exception -- the setup
10408                        // wizard. The setup wizard, however, cannot be known until we're able to
10409                        // query it for the category CATEGORY_SETUP_WIZARD. Which we can't do
10410                        // until all intent filters have been processed. Chicken, meet egg.
10411                        // Let the filter temporarily have a high priority and rectify the
10412                        // priorities after all system packages have been scanned.
10413                        mProtectedFilters.add(intent);
10414                        if (DEBUG_FILTERS) {
10415                            Slog.i(TAG, "Protected action; save for later;"
10416                                    + " package: " + applicationInfo.packageName
10417                                    + " activity: " + intent.activity.className
10418                                    + " origPrio: " + intent.getPriority());
10419                        }
10420                        return;
10421                    } else {
10422                        if (DEBUG_FILTERS && mSetupWizardPackage == null) {
10423                            Slog.i(TAG, "No setup wizard;"
10424                                + " All protected intents capped to priority 0");
10425                        }
10426                        if (intent.activity.info.packageName.equals(mSetupWizardPackage)) {
10427                            if (DEBUG_FILTERS) {
10428                                Slog.i(TAG, "Found setup wizard;"
10429                                    + " allow priority " + intent.getPriority() + ";"
10430                                    + " package: " + intent.activity.info.packageName
10431                                    + " activity: " + intent.activity.className
10432                                    + " priority: " + intent.getPriority());
10433                            }
10434                            // setup wizard gets whatever it wants
10435                            return;
10436                        }
10437                        Slog.w(TAG, "Protected action; cap priority to 0;"
10438                                + " package: " + intent.activity.info.packageName
10439                                + " activity: " + intent.activity.className
10440                                + " origPrio: " + intent.getPriority());
10441                        intent.setPriority(0);
10442                        return;
10443                    }
10444                }
10445                // privileged apps on the system image get whatever priority they request
10446                return;
10447            }
10448
10449            // privileged app unbundled update ... try to find the same activity
10450            final PackageParser.Activity foundActivity =
10451                    findMatchingActivity(systemActivities, activityInfo);
10452            if (foundActivity == null) {
10453                // this is a new activity; it cannot obtain >0 priority
10454                if (DEBUG_FILTERS) {
10455                    Slog.i(TAG, "New activity; cap priority to 0;"
10456                            + " package: " + applicationInfo.packageName
10457                            + " activity: " + intent.activity.className
10458                            + " origPrio: " + intent.getPriority());
10459                }
10460                intent.setPriority(0);
10461                return;
10462            }
10463
10464            // found activity, now check for filter equivalence
10465
10466            // a shallow copy is enough; we modify the list, not its contents
10467            final List<ActivityIntentInfo> intentListCopy =
10468                    new ArrayList<>(foundActivity.intents);
10469            final List<ActivityIntentInfo> foundFilters = findFilters(intent);
10470
10471            // find matching action subsets
10472            final Iterator<String> actionsIterator = intent.actionsIterator();
10473            if (actionsIterator != null) {
10474                getIntentListSubset(
10475                        intentListCopy, new ActionIterGenerator(), actionsIterator);
10476                if (intentListCopy.size() == 0) {
10477                    // no more intents to match; we're not equivalent
10478                    if (DEBUG_FILTERS) {
10479                        Slog.i(TAG, "Mismatched action; cap priority to 0;"
10480                                + " package: " + applicationInfo.packageName
10481                                + " activity: " + intent.activity.className
10482                                + " origPrio: " + intent.getPriority());
10483                    }
10484                    intent.setPriority(0);
10485                    return;
10486                }
10487            }
10488
10489            // find matching category subsets
10490            final Iterator<String> categoriesIterator = intent.categoriesIterator();
10491            if (categoriesIterator != null) {
10492                getIntentListSubset(intentListCopy, new CategoriesIterGenerator(),
10493                        categoriesIterator);
10494                if (intentListCopy.size() == 0) {
10495                    // no more intents to match; we're not equivalent
10496                    if (DEBUG_FILTERS) {
10497                        Slog.i(TAG, "Mismatched category; cap priority to 0;"
10498                                + " package: " + applicationInfo.packageName
10499                                + " activity: " + intent.activity.className
10500                                + " origPrio: " + intent.getPriority());
10501                    }
10502                    intent.setPriority(0);
10503                    return;
10504                }
10505            }
10506
10507            // find matching schemes subsets
10508            final Iterator<String> schemesIterator = intent.schemesIterator();
10509            if (schemesIterator != null) {
10510                getIntentListSubset(intentListCopy, new SchemesIterGenerator(),
10511                        schemesIterator);
10512                if (intentListCopy.size() == 0) {
10513                    // no more intents to match; we're not equivalent
10514                    if (DEBUG_FILTERS) {
10515                        Slog.i(TAG, "Mismatched scheme; cap priority to 0;"
10516                                + " package: " + applicationInfo.packageName
10517                                + " activity: " + intent.activity.className
10518                                + " origPrio: " + intent.getPriority());
10519                    }
10520                    intent.setPriority(0);
10521                    return;
10522                }
10523            }
10524
10525            // find matching authorities subsets
10526            final Iterator<IntentFilter.AuthorityEntry>
10527                    authoritiesIterator = intent.authoritiesIterator();
10528            if (authoritiesIterator != null) {
10529                getIntentListSubset(intentListCopy,
10530                        new AuthoritiesIterGenerator(),
10531                        authoritiesIterator);
10532                if (intentListCopy.size() == 0) {
10533                    // no more intents to match; we're not equivalent
10534                    if (DEBUG_FILTERS) {
10535                        Slog.i(TAG, "Mismatched authority; cap priority to 0;"
10536                                + " package: " + applicationInfo.packageName
10537                                + " activity: " + intent.activity.className
10538                                + " origPrio: " + intent.getPriority());
10539                    }
10540                    intent.setPriority(0);
10541                    return;
10542                }
10543            }
10544
10545            // we found matching filter(s); app gets the max priority of all intents
10546            int cappedPriority = 0;
10547            for (int i = intentListCopy.size() - 1; i >= 0; --i) {
10548                cappedPriority = Math.max(cappedPriority, intentListCopy.get(i).getPriority());
10549            }
10550            if (intent.getPriority() > cappedPriority) {
10551                if (DEBUG_FILTERS) {
10552                    Slog.i(TAG, "Found matching filter(s);"
10553                            + " cap priority to " + cappedPriority + ";"
10554                            + " package: " + applicationInfo.packageName
10555                            + " activity: " + intent.activity.className
10556                            + " origPrio: " + intent.getPriority());
10557                }
10558                intent.setPriority(cappedPriority);
10559                return;
10560            }
10561            // all this for nothing; the requested priority was <= what was on the system
10562        }
10563
10564        public final void addActivity(PackageParser.Activity a, String type) {
10565            mActivities.put(a.getComponentName(), a);
10566            if (DEBUG_SHOW_INFO)
10567                Log.v(
10568                TAG, "  " + type + " " +
10569                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
10570            if (DEBUG_SHOW_INFO)
10571                Log.v(TAG, "    Class=" + a.info.name);
10572            final int NI = a.intents.size();
10573            for (int j=0; j<NI; j++) {
10574                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
10575                if ("activity".equals(type)) {
10576                    final PackageSetting ps =
10577                            mSettings.getDisabledSystemPkgLPr(intent.activity.info.packageName);
10578                    final List<PackageParser.Activity> systemActivities =
10579                            ps != null && ps.pkg != null ? ps.pkg.activities : null;
10580                    adjustPriority(systemActivities, intent);
10581                }
10582                if (DEBUG_SHOW_INFO) {
10583                    Log.v(TAG, "    IntentFilter:");
10584                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
10585                }
10586                if (!intent.debugCheck()) {
10587                    Log.w(TAG, "==> For Activity " + a.info.name);
10588                }
10589                addFilter(intent);
10590            }
10591        }
10592
10593        public final void removeActivity(PackageParser.Activity a, String type) {
10594            mActivities.remove(a.getComponentName());
10595            if (DEBUG_SHOW_INFO) {
10596                Log.v(TAG, "  " + type + " "
10597                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
10598                                : a.info.name) + ":");
10599                Log.v(TAG, "    Class=" + a.info.name);
10600            }
10601            final int NI = a.intents.size();
10602            for (int j=0; j<NI; j++) {
10603                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
10604                if (DEBUG_SHOW_INFO) {
10605                    Log.v(TAG, "    IntentFilter:");
10606                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
10607                }
10608                removeFilter(intent);
10609            }
10610        }
10611
10612        @Override
10613        protected boolean allowFilterResult(
10614                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
10615            ActivityInfo filterAi = filter.activity.info;
10616            for (int i=dest.size()-1; i>=0; i--) {
10617                ActivityInfo destAi = dest.get(i).activityInfo;
10618                if (destAi.name == filterAi.name
10619                        && destAi.packageName == filterAi.packageName) {
10620                    return false;
10621                }
10622            }
10623            return true;
10624        }
10625
10626        @Override
10627        protected ActivityIntentInfo[] newArray(int size) {
10628            return new ActivityIntentInfo[size];
10629        }
10630
10631        @Override
10632        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
10633            if (!sUserManager.exists(userId)) return true;
10634            PackageParser.Package p = filter.activity.owner;
10635            if (p != null) {
10636                PackageSetting ps = (PackageSetting)p.mExtras;
10637                if (ps != null) {
10638                    // System apps are never considered stopped for purposes of
10639                    // filtering, because there may be no way for the user to
10640                    // actually re-launch them.
10641                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
10642                            && ps.getStopped(userId);
10643                }
10644            }
10645            return false;
10646        }
10647
10648        @Override
10649        protected boolean isPackageForFilter(String packageName,
10650                PackageParser.ActivityIntentInfo info) {
10651            return packageName.equals(info.activity.owner.packageName);
10652        }
10653
10654        @Override
10655        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
10656                int match, int userId) {
10657            if (!sUserManager.exists(userId)) return null;
10658            if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) {
10659                return null;
10660            }
10661            final PackageParser.Activity activity = info.activity;
10662            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
10663            if (ps == null) {
10664                return null;
10665            }
10666            ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags,
10667                    ps.readUserState(userId), userId);
10668            if (ai == null) {
10669                return null;
10670            }
10671            final ResolveInfo res = new ResolveInfo();
10672            res.activityInfo = ai;
10673            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
10674                res.filter = info;
10675            }
10676            if (info != null) {
10677                res.handleAllWebDataURI = info.handleAllWebDataURI();
10678            }
10679            res.priority = info.getPriority();
10680            res.preferredOrder = activity.owner.mPreferredOrder;
10681            //System.out.println("Result: " + res.activityInfo.className +
10682            //                   " = " + res.priority);
10683            res.match = match;
10684            res.isDefault = info.hasDefault;
10685            res.labelRes = info.labelRes;
10686            res.nonLocalizedLabel = info.nonLocalizedLabel;
10687            if (userNeedsBadging(userId)) {
10688                res.noResourceId = true;
10689            } else {
10690                res.icon = info.icon;
10691            }
10692            res.iconResourceId = info.icon;
10693            res.system = res.activityInfo.applicationInfo.isSystemApp();
10694            return res;
10695        }
10696
10697        @Override
10698        protected void sortResults(List<ResolveInfo> results) {
10699            Collections.sort(results, mResolvePrioritySorter);
10700        }
10701
10702        @Override
10703        protected void dumpFilter(PrintWriter out, String prefix,
10704                PackageParser.ActivityIntentInfo filter) {
10705            out.print(prefix); out.print(
10706                    Integer.toHexString(System.identityHashCode(filter.activity)));
10707                    out.print(' ');
10708                    filter.activity.printComponentShortName(out);
10709                    out.print(" filter ");
10710                    out.println(Integer.toHexString(System.identityHashCode(filter)));
10711        }
10712
10713        @Override
10714        protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) {
10715            return filter.activity;
10716        }
10717
10718        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
10719            PackageParser.Activity activity = (PackageParser.Activity)label;
10720            out.print(prefix); out.print(
10721                    Integer.toHexString(System.identityHashCode(activity)));
10722                    out.print(' ');
10723                    activity.printComponentShortName(out);
10724            if (count > 1) {
10725                out.print(" ("); out.print(count); out.print(" filters)");
10726            }
10727            out.println();
10728        }
10729
10730        // Keys are String (activity class name), values are Activity.
10731        private final ArrayMap<ComponentName, PackageParser.Activity> mActivities
10732                = new ArrayMap<ComponentName, PackageParser.Activity>();
10733        private int mFlags;
10734    }
10735
10736    private final class ServiceIntentResolver
10737            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
10738        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
10739                boolean defaultOnly, int userId) {
10740            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
10741            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
10742        }
10743
10744        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
10745                int userId) {
10746            if (!sUserManager.exists(userId)) return null;
10747            mFlags = flags;
10748            return super.queryIntent(intent, resolvedType,
10749                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
10750        }
10751
10752        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
10753                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
10754            if (!sUserManager.exists(userId)) return null;
10755            if (packageServices == null) {
10756                return null;
10757            }
10758            mFlags = flags;
10759            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
10760            final int N = packageServices.size();
10761            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
10762                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
10763
10764            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
10765            for (int i = 0; i < N; ++i) {
10766                intentFilters = packageServices.get(i).intents;
10767                if (intentFilters != null && intentFilters.size() > 0) {
10768                    PackageParser.ServiceIntentInfo[] array =
10769                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
10770                    intentFilters.toArray(array);
10771                    listCut.add(array);
10772                }
10773            }
10774            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
10775        }
10776
10777        public final void addService(PackageParser.Service s) {
10778            mServices.put(s.getComponentName(), s);
10779            if (DEBUG_SHOW_INFO) {
10780                Log.v(TAG, "  "
10781                        + (s.info.nonLocalizedLabel != null
10782                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
10783                Log.v(TAG, "    Class=" + s.info.name);
10784            }
10785            final int NI = s.intents.size();
10786            int j;
10787            for (j=0; j<NI; j++) {
10788                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
10789                if (DEBUG_SHOW_INFO) {
10790                    Log.v(TAG, "    IntentFilter:");
10791                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
10792                }
10793                if (!intent.debugCheck()) {
10794                    Log.w(TAG, "==> For Service " + s.info.name);
10795                }
10796                addFilter(intent);
10797            }
10798        }
10799
10800        public final void removeService(PackageParser.Service s) {
10801            mServices.remove(s.getComponentName());
10802            if (DEBUG_SHOW_INFO) {
10803                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
10804                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
10805                Log.v(TAG, "    Class=" + s.info.name);
10806            }
10807            final int NI = s.intents.size();
10808            int j;
10809            for (j=0; j<NI; j++) {
10810                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
10811                if (DEBUG_SHOW_INFO) {
10812                    Log.v(TAG, "    IntentFilter:");
10813                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
10814                }
10815                removeFilter(intent);
10816            }
10817        }
10818
10819        @Override
10820        protected boolean allowFilterResult(
10821                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
10822            ServiceInfo filterSi = filter.service.info;
10823            for (int i=dest.size()-1; i>=0; i--) {
10824                ServiceInfo destAi = dest.get(i).serviceInfo;
10825                if (destAi.name == filterSi.name
10826                        && destAi.packageName == filterSi.packageName) {
10827                    return false;
10828                }
10829            }
10830            return true;
10831        }
10832
10833        @Override
10834        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
10835            return new PackageParser.ServiceIntentInfo[size];
10836        }
10837
10838        @Override
10839        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
10840            if (!sUserManager.exists(userId)) return true;
10841            PackageParser.Package p = filter.service.owner;
10842            if (p != null) {
10843                PackageSetting ps = (PackageSetting)p.mExtras;
10844                if (ps != null) {
10845                    // System apps are never considered stopped for purposes of
10846                    // filtering, because there may be no way for the user to
10847                    // actually re-launch them.
10848                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
10849                            && ps.getStopped(userId);
10850                }
10851            }
10852            return false;
10853        }
10854
10855        @Override
10856        protected boolean isPackageForFilter(String packageName,
10857                PackageParser.ServiceIntentInfo info) {
10858            return packageName.equals(info.service.owner.packageName);
10859        }
10860
10861        @Override
10862        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
10863                int match, int userId) {
10864            if (!sUserManager.exists(userId)) return null;
10865            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
10866            if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) {
10867                return null;
10868            }
10869            final PackageParser.Service service = info.service;
10870            PackageSetting ps = (PackageSetting) service.owner.mExtras;
10871            if (ps == null) {
10872                return null;
10873            }
10874            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
10875                    ps.readUserState(userId), userId);
10876            if (si == null) {
10877                return null;
10878            }
10879            final ResolveInfo res = new ResolveInfo();
10880            res.serviceInfo = si;
10881            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
10882                res.filter = filter;
10883            }
10884            res.priority = info.getPriority();
10885            res.preferredOrder = service.owner.mPreferredOrder;
10886            res.match = match;
10887            res.isDefault = info.hasDefault;
10888            res.labelRes = info.labelRes;
10889            res.nonLocalizedLabel = info.nonLocalizedLabel;
10890            res.icon = info.icon;
10891            res.system = res.serviceInfo.applicationInfo.isSystemApp();
10892            return res;
10893        }
10894
10895        @Override
10896        protected void sortResults(List<ResolveInfo> results) {
10897            Collections.sort(results, mResolvePrioritySorter);
10898        }
10899
10900        @Override
10901        protected void dumpFilter(PrintWriter out, String prefix,
10902                PackageParser.ServiceIntentInfo filter) {
10903            out.print(prefix); out.print(
10904                    Integer.toHexString(System.identityHashCode(filter.service)));
10905                    out.print(' ');
10906                    filter.service.printComponentShortName(out);
10907                    out.print(" filter ");
10908                    out.println(Integer.toHexString(System.identityHashCode(filter)));
10909        }
10910
10911        @Override
10912        protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) {
10913            return filter.service;
10914        }
10915
10916        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
10917            PackageParser.Service service = (PackageParser.Service)label;
10918            out.print(prefix); out.print(
10919                    Integer.toHexString(System.identityHashCode(service)));
10920                    out.print(' ');
10921                    service.printComponentShortName(out);
10922            if (count > 1) {
10923                out.print(" ("); out.print(count); out.print(" filters)");
10924            }
10925            out.println();
10926        }
10927
10928//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
10929//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
10930//            final List<ResolveInfo> retList = Lists.newArrayList();
10931//            while (i.hasNext()) {
10932//                final ResolveInfo resolveInfo = (ResolveInfo) i;
10933//                if (isEnabledLP(resolveInfo.serviceInfo)) {
10934//                    retList.add(resolveInfo);
10935//                }
10936//            }
10937//            return retList;
10938//        }
10939
10940        // Keys are String (activity class name), values are Activity.
10941        private final ArrayMap<ComponentName, PackageParser.Service> mServices
10942                = new ArrayMap<ComponentName, PackageParser.Service>();
10943        private int mFlags;
10944    };
10945
10946    private final class ProviderIntentResolver
10947            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
10948        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
10949                boolean defaultOnly, int userId) {
10950            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
10951            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
10952        }
10953
10954        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
10955                int userId) {
10956            if (!sUserManager.exists(userId))
10957                return null;
10958            mFlags = flags;
10959            return super.queryIntent(intent, resolvedType,
10960                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
10961        }
10962
10963        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
10964                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
10965            if (!sUserManager.exists(userId))
10966                return null;
10967            if (packageProviders == null) {
10968                return null;
10969            }
10970            mFlags = flags;
10971            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
10972            final int N = packageProviders.size();
10973            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
10974                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
10975
10976            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
10977            for (int i = 0; i < N; ++i) {
10978                intentFilters = packageProviders.get(i).intents;
10979                if (intentFilters != null && intentFilters.size() > 0) {
10980                    PackageParser.ProviderIntentInfo[] array =
10981                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
10982                    intentFilters.toArray(array);
10983                    listCut.add(array);
10984                }
10985            }
10986            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
10987        }
10988
10989        public final void addProvider(PackageParser.Provider p) {
10990            if (mProviders.containsKey(p.getComponentName())) {
10991                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
10992                return;
10993            }
10994
10995            mProviders.put(p.getComponentName(), p);
10996            if (DEBUG_SHOW_INFO) {
10997                Log.v(TAG, "  "
10998                        + (p.info.nonLocalizedLabel != null
10999                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
11000                Log.v(TAG, "    Class=" + p.info.name);
11001            }
11002            final int NI = p.intents.size();
11003            int j;
11004            for (j = 0; j < NI; j++) {
11005                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
11006                if (DEBUG_SHOW_INFO) {
11007                    Log.v(TAG, "    IntentFilter:");
11008                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
11009                }
11010                if (!intent.debugCheck()) {
11011                    Log.w(TAG, "==> For Provider " + p.info.name);
11012                }
11013                addFilter(intent);
11014            }
11015        }
11016
11017        public final void removeProvider(PackageParser.Provider p) {
11018            mProviders.remove(p.getComponentName());
11019            if (DEBUG_SHOW_INFO) {
11020                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
11021                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
11022                Log.v(TAG, "    Class=" + p.info.name);
11023            }
11024            final int NI = p.intents.size();
11025            int j;
11026            for (j = 0; j < NI; j++) {
11027                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
11028                if (DEBUG_SHOW_INFO) {
11029                    Log.v(TAG, "    IntentFilter:");
11030                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
11031                }
11032                removeFilter(intent);
11033            }
11034        }
11035
11036        @Override
11037        protected boolean allowFilterResult(
11038                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
11039            ProviderInfo filterPi = filter.provider.info;
11040            for (int i = dest.size() - 1; i >= 0; i--) {
11041                ProviderInfo destPi = dest.get(i).providerInfo;
11042                if (destPi.name == filterPi.name
11043                        && destPi.packageName == filterPi.packageName) {
11044                    return false;
11045                }
11046            }
11047            return true;
11048        }
11049
11050        @Override
11051        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
11052            return new PackageParser.ProviderIntentInfo[size];
11053        }
11054
11055        @Override
11056        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
11057            if (!sUserManager.exists(userId))
11058                return true;
11059            PackageParser.Package p = filter.provider.owner;
11060            if (p != null) {
11061                PackageSetting ps = (PackageSetting) p.mExtras;
11062                if (ps != null) {
11063                    // System apps are never considered stopped for purposes of
11064                    // filtering, because there may be no way for the user to
11065                    // actually re-launch them.
11066                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
11067                            && ps.getStopped(userId);
11068                }
11069            }
11070            return false;
11071        }
11072
11073        @Override
11074        protected boolean isPackageForFilter(String packageName,
11075                PackageParser.ProviderIntentInfo info) {
11076            return packageName.equals(info.provider.owner.packageName);
11077        }
11078
11079        @Override
11080        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
11081                int match, int userId) {
11082            if (!sUserManager.exists(userId))
11083                return null;
11084            final PackageParser.ProviderIntentInfo info = filter;
11085            if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) {
11086                return null;
11087            }
11088            final PackageParser.Provider provider = info.provider;
11089            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
11090            if (ps == null) {
11091                return null;
11092            }
11093            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
11094                    ps.readUserState(userId), userId);
11095            if (pi == null) {
11096                return null;
11097            }
11098            final ResolveInfo res = new ResolveInfo();
11099            res.providerInfo = pi;
11100            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
11101                res.filter = filter;
11102            }
11103            res.priority = info.getPriority();
11104            res.preferredOrder = provider.owner.mPreferredOrder;
11105            res.match = match;
11106            res.isDefault = info.hasDefault;
11107            res.labelRes = info.labelRes;
11108            res.nonLocalizedLabel = info.nonLocalizedLabel;
11109            res.icon = info.icon;
11110            res.system = res.providerInfo.applicationInfo.isSystemApp();
11111            return res;
11112        }
11113
11114        @Override
11115        protected void sortResults(List<ResolveInfo> results) {
11116            Collections.sort(results, mResolvePrioritySorter);
11117        }
11118
11119        @Override
11120        protected void dumpFilter(PrintWriter out, String prefix,
11121                PackageParser.ProviderIntentInfo filter) {
11122            out.print(prefix);
11123            out.print(
11124                    Integer.toHexString(System.identityHashCode(filter.provider)));
11125            out.print(' ');
11126            filter.provider.printComponentShortName(out);
11127            out.print(" filter ");
11128            out.println(Integer.toHexString(System.identityHashCode(filter)));
11129        }
11130
11131        @Override
11132        protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) {
11133            return filter.provider;
11134        }
11135
11136        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
11137            PackageParser.Provider provider = (PackageParser.Provider)label;
11138            out.print(prefix); out.print(
11139                    Integer.toHexString(System.identityHashCode(provider)));
11140                    out.print(' ');
11141                    provider.printComponentShortName(out);
11142            if (count > 1) {
11143                out.print(" ("); out.print(count); out.print(" filters)");
11144            }
11145            out.println();
11146        }
11147
11148        private final ArrayMap<ComponentName, PackageParser.Provider> mProviders
11149                = new ArrayMap<ComponentName, PackageParser.Provider>();
11150        private int mFlags;
11151    }
11152
11153    private static final class EphemeralIntentResolver
11154            extends IntentResolver<EphemeralResolveIntentInfo, EphemeralResolveInfo> {
11155        @Override
11156        protected EphemeralResolveIntentInfo[] newArray(int size) {
11157            return new EphemeralResolveIntentInfo[size];
11158        }
11159
11160        @Override
11161        protected boolean isPackageForFilter(String packageName, EphemeralResolveIntentInfo info) {
11162            return true;
11163        }
11164
11165        @Override
11166        protected EphemeralResolveInfo newResult(EphemeralResolveIntentInfo info, int match,
11167                int userId) {
11168            if (!sUserManager.exists(userId)) {
11169                return null;
11170            }
11171            return info.getEphemeralResolveInfo();
11172        }
11173    }
11174
11175    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
11176            new Comparator<ResolveInfo>() {
11177        public int compare(ResolveInfo r1, ResolveInfo r2) {
11178            int v1 = r1.priority;
11179            int v2 = r2.priority;
11180            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
11181            if (v1 != v2) {
11182                return (v1 > v2) ? -1 : 1;
11183            }
11184            v1 = r1.preferredOrder;
11185            v2 = r2.preferredOrder;
11186            if (v1 != v2) {
11187                return (v1 > v2) ? -1 : 1;
11188            }
11189            if (r1.isDefault != r2.isDefault) {
11190                return r1.isDefault ? -1 : 1;
11191            }
11192            v1 = r1.match;
11193            v2 = r2.match;
11194            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
11195            if (v1 != v2) {
11196                return (v1 > v2) ? -1 : 1;
11197            }
11198            if (r1.system != r2.system) {
11199                return r1.system ? -1 : 1;
11200            }
11201            if (r1.activityInfo != null) {
11202                return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName);
11203            }
11204            if (r1.serviceInfo != null) {
11205                return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName);
11206            }
11207            if (r1.providerInfo != null) {
11208                return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName);
11209            }
11210            return 0;
11211        }
11212    };
11213
11214    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
11215            new Comparator<ProviderInfo>() {
11216        public int compare(ProviderInfo p1, ProviderInfo p2) {
11217            final int v1 = p1.initOrder;
11218            final int v2 = p2.initOrder;
11219            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
11220        }
11221    };
11222
11223    final void sendPackageBroadcast(final String action, final String pkg, final Bundle extras,
11224            final int flags, final String targetPkg, final IIntentReceiver finishedReceiver,
11225            final int[] userIds) {
11226        mHandler.post(new Runnable() {
11227            @Override
11228            public void run() {
11229                try {
11230                    final IActivityManager am = ActivityManagerNative.getDefault();
11231                    if (am == null) return;
11232                    final int[] resolvedUserIds;
11233                    if (userIds == null) {
11234                        resolvedUserIds = am.getRunningUserIds();
11235                    } else {
11236                        resolvedUserIds = userIds;
11237                    }
11238                    for (int id : resolvedUserIds) {
11239                        final Intent intent = new Intent(action,
11240                                pkg != null ? Uri.fromParts("package", pkg, null) : null);
11241                        if (extras != null) {
11242                            intent.putExtras(extras);
11243                        }
11244                        if (targetPkg != null) {
11245                            intent.setPackage(targetPkg);
11246                        }
11247                        // Modify the UID when posting to other users
11248                        int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
11249                        if (uid > 0 && UserHandle.getUserId(uid) != id) {
11250                            uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
11251                            intent.putExtra(Intent.EXTRA_UID, uid);
11252                        }
11253                        intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
11254                        intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags);
11255                        if (DEBUG_BROADCASTS) {
11256                            RuntimeException here = new RuntimeException("here");
11257                            here.fillInStackTrace();
11258                            Slog.d(TAG, "Sending to user " + id + ": "
11259                                    + intent.toShortString(false, true, false, false)
11260                                    + " " + intent.getExtras(), here);
11261                        }
11262                        am.broadcastIntent(null, intent, null, finishedReceiver,
11263                                0, null, null, null, android.app.AppOpsManager.OP_NONE,
11264                                null, finishedReceiver != null, false, id);
11265                    }
11266                } catch (RemoteException ex) {
11267                }
11268            }
11269        });
11270    }
11271
11272    /**
11273     * Check if the external storage media is available. This is true if there
11274     * is a mounted external storage medium or if the external storage is
11275     * emulated.
11276     */
11277    private boolean isExternalMediaAvailable() {
11278        return mMediaMounted || Environment.isExternalStorageEmulated();
11279    }
11280
11281    @Override
11282    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
11283        // writer
11284        synchronized (mPackages) {
11285            if (!isExternalMediaAvailable()) {
11286                // If the external storage is no longer mounted at this point,
11287                // the caller may not have been able to delete all of this
11288                // packages files and can not delete any more.  Bail.
11289                return null;
11290            }
11291            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
11292            if (lastPackage != null) {
11293                pkgs.remove(lastPackage);
11294            }
11295            if (pkgs.size() > 0) {
11296                return pkgs.get(0);
11297            }
11298        }
11299        return null;
11300    }
11301
11302    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
11303        final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
11304                userId, andCode ? 1 : 0, packageName);
11305        if (mSystemReady) {
11306            msg.sendToTarget();
11307        } else {
11308            if (mPostSystemReadyMessages == null) {
11309                mPostSystemReadyMessages = new ArrayList<>();
11310            }
11311            mPostSystemReadyMessages.add(msg);
11312        }
11313    }
11314
11315    void startCleaningPackages() {
11316        // reader
11317        if (!isExternalMediaAvailable()) {
11318            return;
11319        }
11320        synchronized (mPackages) {
11321            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
11322                return;
11323            }
11324        }
11325        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
11326        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
11327        IActivityManager am = ActivityManagerNative.getDefault();
11328        if (am != null) {
11329            try {
11330                am.startService(null, intent, null, mContext.getOpPackageName(),
11331                        UserHandle.USER_SYSTEM);
11332            } catch (RemoteException e) {
11333            }
11334        }
11335    }
11336
11337    @Override
11338    public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer,
11339            int installFlags, String installerPackageName, int userId) {
11340        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
11341
11342        final int callingUid = Binder.getCallingUid();
11343        enforceCrossUserPermission(callingUid, userId,
11344                true /* requireFullPermission */, true /* checkShell */, "installPackageAsUser");
11345
11346        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
11347            try {
11348                if (observer != null) {
11349                    observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null);
11350                }
11351            } catch (RemoteException re) {
11352            }
11353            return;
11354        }
11355
11356        if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) {
11357            installFlags |= PackageManager.INSTALL_FROM_ADB;
11358
11359        } else {
11360            // Caller holds INSTALL_PACKAGES permission, so we're less strict
11361            // about installerPackageName.
11362
11363            installFlags &= ~PackageManager.INSTALL_FROM_ADB;
11364            installFlags &= ~PackageManager.INSTALL_ALL_USERS;
11365        }
11366
11367        UserHandle user;
11368        if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) {
11369            user = UserHandle.ALL;
11370        } else {
11371            user = new UserHandle(userId);
11372        }
11373
11374        // Only system components can circumvent runtime permissions when installing.
11375        if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0
11376                && mContext.checkCallingOrSelfPermission(Manifest.permission
11377                .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) {
11378            throw new SecurityException("You need the "
11379                    + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission "
11380                    + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag");
11381        }
11382
11383        final File originFile = new File(originPath);
11384        final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile);
11385
11386        final Message msg = mHandler.obtainMessage(INIT_COPY);
11387        final VerificationInfo verificationInfo = new VerificationInfo(
11388                null /*originatingUri*/, null /*referrer*/, -1 /*originatingUid*/, callingUid);
11389        final InstallParams params = new InstallParams(origin, null /*moveInfo*/, observer,
11390                installFlags, installerPackageName, null /*volumeUuid*/, verificationInfo, user,
11391                null /*packageAbiOverride*/, null /*grantedPermissions*/,
11392                null /*certificates*/);
11393        params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params));
11394        msg.obj = params;
11395
11396        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser",
11397                System.identityHashCode(msg.obj));
11398        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
11399                System.identityHashCode(msg.obj));
11400
11401        mHandler.sendMessage(msg);
11402    }
11403
11404    void installStage(String packageName, File stagedDir, String stagedCid,
11405            IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams,
11406            String installerPackageName, int installerUid, UserHandle user,
11407            Certificate[][] certificates) {
11408        if (DEBUG_EPHEMERAL) {
11409            if ((sessionParams.installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) {
11410                Slog.d(TAG, "Ephemeral install of " + packageName);
11411            }
11412        }
11413        final VerificationInfo verificationInfo = new VerificationInfo(
11414                sessionParams.originatingUri, sessionParams.referrerUri,
11415                sessionParams.originatingUid, installerUid);
11416
11417        final OriginInfo origin;
11418        if (stagedDir != null) {
11419            origin = OriginInfo.fromStagedFile(stagedDir);
11420        } else {
11421            origin = OriginInfo.fromStagedContainer(stagedCid);
11422        }
11423
11424        final Message msg = mHandler.obtainMessage(INIT_COPY);
11425        final InstallParams params = new InstallParams(origin, null, observer,
11426                sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid,
11427                verificationInfo, user, sessionParams.abiOverride,
11428                sessionParams.grantedRuntimePermissions, certificates);
11429        params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params));
11430        msg.obj = params;
11431
11432        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage",
11433                System.identityHashCode(msg.obj));
11434        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
11435                System.identityHashCode(msg.obj));
11436
11437        mHandler.sendMessage(msg);
11438    }
11439
11440    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting,
11441            int userId) {
11442        final boolean isSystem = isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
11443        sendPackageAddedForUser(packageName, isSystem, pkgSetting.appId, userId);
11444    }
11445
11446    private void sendPackageAddedForUser(String packageName, boolean isSystem,
11447            int appId, int userId) {
11448        Bundle extras = new Bundle(1);
11449        extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, appId));
11450
11451        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
11452                packageName, extras, 0, null, null, new int[] {userId});
11453        try {
11454            IActivityManager am = ActivityManagerNative.getDefault();
11455            if (isSystem && am.isUserRunning(userId, 0)) {
11456                // The just-installed/enabled app is bundled on the system, so presumed
11457                // to be able to run automatically without needing an explicit launch.
11458                // Send it a BOOT_COMPLETED if it would ordinarily have gotten one.
11459                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED)
11460                        .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES)
11461                        .setPackage(packageName);
11462                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null,
11463                        android.app.AppOpsManager.OP_NONE, null, false, false, userId);
11464            }
11465        } catch (RemoteException e) {
11466            // shouldn't happen
11467            Slog.w(TAG, "Unable to bootstrap installed package", e);
11468        }
11469    }
11470
11471    @Override
11472    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
11473            int userId) {
11474        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
11475        PackageSetting pkgSetting;
11476        final int uid = Binder.getCallingUid();
11477        enforceCrossUserPermission(uid, userId,
11478                true /* requireFullPermission */, true /* checkShell */,
11479                "setApplicationHiddenSetting for user " + userId);
11480
11481        if (hidden && isPackageDeviceAdmin(packageName, userId)) {
11482            Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
11483            return false;
11484        }
11485
11486        long callingId = Binder.clearCallingIdentity();
11487        try {
11488            boolean sendAdded = false;
11489            boolean sendRemoved = false;
11490            // writer
11491            synchronized (mPackages) {
11492                pkgSetting = mSettings.mPackages.get(packageName);
11493                if (pkgSetting == null) {
11494                    return false;
11495                }
11496                if (pkgSetting.getHidden(userId) != hidden) {
11497                    pkgSetting.setHidden(hidden, userId);
11498                    mSettings.writePackageRestrictionsLPr(userId);
11499                    if (hidden) {
11500                        sendRemoved = true;
11501                    } else {
11502                        sendAdded = true;
11503                    }
11504                }
11505            }
11506            if (sendAdded) {
11507                sendPackageAddedForUser(packageName, pkgSetting, userId);
11508                return true;
11509            }
11510            if (sendRemoved) {
11511                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
11512                        "hiding pkg");
11513                sendApplicationHiddenForUser(packageName, pkgSetting, userId);
11514                return true;
11515            }
11516        } finally {
11517            Binder.restoreCallingIdentity(callingId);
11518        }
11519        return false;
11520    }
11521
11522    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
11523            int userId) {
11524        final PackageRemovedInfo info = new PackageRemovedInfo();
11525        info.removedPackage = packageName;
11526        info.removedUsers = new int[] {userId};
11527        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
11528        info.sendPackageRemovedBroadcasts(true /*killApp*/);
11529    }
11530
11531    private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended) {
11532        if (pkgList.length > 0) {
11533            Bundle extras = new Bundle(1);
11534            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
11535
11536            sendPackageBroadcast(
11537                    suspended ? Intent.ACTION_PACKAGES_SUSPENDED
11538                            : Intent.ACTION_PACKAGES_UNSUSPENDED,
11539                    null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null,
11540                    new int[] {userId});
11541        }
11542    }
11543
11544    /**
11545     * Returns true if application is not found or there was an error. Otherwise it returns
11546     * the hidden state of the package for the given user.
11547     */
11548    @Override
11549    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
11550        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
11551        enforceCrossUserPermission(Binder.getCallingUid(), userId,
11552                true /* requireFullPermission */, false /* checkShell */,
11553                "getApplicationHidden for user " + userId);
11554        PackageSetting pkgSetting;
11555        long callingId = Binder.clearCallingIdentity();
11556        try {
11557            // writer
11558            synchronized (mPackages) {
11559                pkgSetting = mSettings.mPackages.get(packageName);
11560                if (pkgSetting == null) {
11561                    return true;
11562                }
11563                return pkgSetting.getHidden(userId);
11564            }
11565        } finally {
11566            Binder.restoreCallingIdentity(callingId);
11567        }
11568    }
11569
11570    /**
11571     * @hide
11572     */
11573    @Override
11574    public int installExistingPackageAsUser(String packageName, int userId) {
11575        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
11576                null);
11577        PackageSetting pkgSetting;
11578        final int uid = Binder.getCallingUid();
11579        enforceCrossUserPermission(uid, userId,
11580                true /* requireFullPermission */, true /* checkShell */,
11581                "installExistingPackage for user " + userId);
11582        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
11583            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
11584        }
11585
11586        long callingId = Binder.clearCallingIdentity();
11587        try {
11588            boolean installed = false;
11589
11590            // writer
11591            synchronized (mPackages) {
11592                pkgSetting = mSettings.mPackages.get(packageName);
11593                if (pkgSetting == null) {
11594                    return PackageManager.INSTALL_FAILED_INVALID_URI;
11595                }
11596                if (!pkgSetting.getInstalled(userId)) {
11597                    pkgSetting.setInstalled(true, userId);
11598                    pkgSetting.setHidden(false, userId);
11599                    mSettings.writePackageRestrictionsLPr(userId);
11600                    installed = true;
11601                }
11602            }
11603
11604            if (installed) {
11605                if (pkgSetting.pkg != null) {
11606                    synchronized (mInstallLock) {
11607                        // We don't need to freeze for a brand new install
11608                        prepareAppDataAfterInstallLIF(pkgSetting.pkg);
11609                    }
11610                }
11611                sendPackageAddedForUser(packageName, pkgSetting, userId);
11612            }
11613        } finally {
11614            Binder.restoreCallingIdentity(callingId);
11615        }
11616
11617        return PackageManager.INSTALL_SUCCEEDED;
11618    }
11619
11620    boolean isUserRestricted(int userId, String restrictionKey) {
11621        Bundle restrictions = sUserManager.getUserRestrictions(userId);
11622        if (restrictions.getBoolean(restrictionKey, false)) {
11623            Log.w(TAG, "User is restricted: " + restrictionKey);
11624            return true;
11625        }
11626        return false;
11627    }
11628
11629    @Override
11630    public String[] setPackagesSuspendedAsUser(String[] packageNames, boolean suspended,
11631            int userId) {
11632        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
11633        enforceCrossUserPermission(Binder.getCallingUid(), userId,
11634                true /* requireFullPermission */, true /* checkShell */,
11635                "setPackagesSuspended for user " + userId);
11636
11637        if (ArrayUtils.isEmpty(packageNames)) {
11638            return packageNames;
11639        }
11640
11641        // List of package names for whom the suspended state has changed.
11642        List<String> changedPackages = new ArrayList<>(packageNames.length);
11643        // List of package names for whom the suspended state is not set as requested in this
11644        // method.
11645        List<String> unactionedPackages = new ArrayList<>(packageNames.length);
11646        long callingId = Binder.clearCallingIdentity();
11647        try {
11648            for (int i = 0; i < packageNames.length; i++) {
11649                String packageName = packageNames[i];
11650                boolean changed = false;
11651                final int appId;
11652                synchronized (mPackages) {
11653                    final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
11654                    if (pkgSetting == null) {
11655                        Slog.w(TAG, "Could not find package setting for package \"" + packageName
11656                                + "\". Skipping suspending/un-suspending.");
11657                        unactionedPackages.add(packageName);
11658                        continue;
11659                    }
11660                    appId = pkgSetting.appId;
11661                    if (pkgSetting.getSuspended(userId) != suspended) {
11662                        if (!canSuspendPackageForUserLocked(packageName, userId)) {
11663                            unactionedPackages.add(packageName);
11664                            continue;
11665                        }
11666                        pkgSetting.setSuspended(suspended, userId);
11667                        mSettings.writePackageRestrictionsLPr(userId);
11668                        changed = true;
11669                        changedPackages.add(packageName);
11670                    }
11671                }
11672
11673                if (changed && suspended) {
11674                    killApplication(packageName, UserHandle.getUid(userId, appId),
11675                            "suspending package");
11676                }
11677            }
11678        } finally {
11679            Binder.restoreCallingIdentity(callingId);
11680        }
11681
11682        if (!changedPackages.isEmpty()) {
11683            sendPackagesSuspendedForUser(changedPackages.toArray(
11684                    new String[changedPackages.size()]), userId, suspended);
11685        }
11686
11687        return unactionedPackages.toArray(new String[unactionedPackages.size()]);
11688    }
11689
11690    @Override
11691    public boolean isPackageSuspendedForUser(String packageName, int userId) {
11692        enforceCrossUserPermission(Binder.getCallingUid(), userId,
11693                true /* requireFullPermission */, false /* checkShell */,
11694                "isPackageSuspendedForUser for user " + userId);
11695        synchronized (mPackages) {
11696            final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
11697            if (pkgSetting == null) {
11698                throw new IllegalArgumentException("Unknown target package: " + packageName);
11699            }
11700            return pkgSetting.getSuspended(userId);
11701        }
11702    }
11703
11704    private boolean canSuspendPackageForUserLocked(String packageName, int userId) {
11705        if (isPackageDeviceAdmin(packageName, userId)) {
11706            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
11707                    + "\": has an active device admin");
11708            return false;
11709        }
11710
11711        String activeLauncherPackageName = getActiveLauncherPackageName(userId);
11712        if (packageName.equals(activeLauncherPackageName)) {
11713            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
11714                    + "\": contains the active launcher");
11715            return false;
11716        }
11717
11718        if (packageName.equals(mRequiredInstallerPackage)) {
11719            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
11720                    + "\": required for package installation");
11721            return false;
11722        }
11723
11724        if (packageName.equals(mRequiredVerifierPackage)) {
11725            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
11726                    + "\": required for package verification");
11727            return false;
11728        }
11729
11730        if (packageName.equals(getDefaultDialerPackageName(userId))) {
11731            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
11732                    + "\": is the default dialer");
11733            return false;
11734        }
11735
11736        return true;
11737    }
11738
11739    private String getActiveLauncherPackageName(int userId) {
11740        Intent intent = new Intent(Intent.ACTION_MAIN);
11741        intent.addCategory(Intent.CATEGORY_HOME);
11742        ResolveInfo resolveInfo = resolveIntent(
11743                intent,
11744                intent.resolveTypeIfNeeded(mContext.getContentResolver()),
11745                PackageManager.MATCH_DEFAULT_ONLY,
11746                userId);
11747
11748        return resolveInfo == null ? null : resolveInfo.activityInfo.packageName;
11749    }
11750
11751    private String getDefaultDialerPackageName(int userId) {
11752        synchronized (mPackages) {
11753            return mSettings.getDefaultDialerPackageNameLPw(userId);
11754        }
11755    }
11756
11757    @Override
11758    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
11759        mContext.enforceCallingOrSelfPermission(
11760                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
11761                "Only package verification agents can verify applications");
11762
11763        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
11764        final PackageVerificationResponse response = new PackageVerificationResponse(
11765                verificationCode, Binder.getCallingUid());
11766        msg.arg1 = id;
11767        msg.obj = response;
11768        mHandler.sendMessage(msg);
11769    }
11770
11771    @Override
11772    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
11773            long millisecondsToDelay) {
11774        mContext.enforceCallingOrSelfPermission(
11775                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
11776                "Only package verification agents can extend verification timeouts");
11777
11778        final PackageVerificationState state = mPendingVerification.get(id);
11779        final PackageVerificationResponse response = new PackageVerificationResponse(
11780                verificationCodeAtTimeout, Binder.getCallingUid());
11781
11782        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
11783            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
11784        }
11785        if (millisecondsToDelay < 0) {
11786            millisecondsToDelay = 0;
11787        }
11788        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
11789                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
11790            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
11791        }
11792
11793        if ((state != null) && !state.timeoutExtended()) {
11794            state.extendTimeout();
11795
11796            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
11797            msg.arg1 = id;
11798            msg.obj = response;
11799            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
11800        }
11801    }
11802
11803    private void broadcastPackageVerified(int verificationId, Uri packageUri,
11804            int verificationCode, UserHandle user) {
11805        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
11806        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
11807        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
11808        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
11809        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
11810
11811        mContext.sendBroadcastAsUser(intent, user,
11812                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
11813    }
11814
11815    private ComponentName matchComponentForVerifier(String packageName,
11816            List<ResolveInfo> receivers) {
11817        ActivityInfo targetReceiver = null;
11818
11819        final int NR = receivers.size();
11820        for (int i = 0; i < NR; i++) {
11821            final ResolveInfo info = receivers.get(i);
11822            if (info.activityInfo == null) {
11823                continue;
11824            }
11825
11826            if (packageName.equals(info.activityInfo.packageName)) {
11827                targetReceiver = info.activityInfo;
11828                break;
11829            }
11830        }
11831
11832        if (targetReceiver == null) {
11833            return null;
11834        }
11835
11836        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
11837    }
11838
11839    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
11840            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
11841        if (pkgInfo.verifiers.length == 0) {
11842            return null;
11843        }
11844
11845        final int N = pkgInfo.verifiers.length;
11846        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
11847        for (int i = 0; i < N; i++) {
11848            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
11849
11850            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
11851                    receivers);
11852            if (comp == null) {
11853                continue;
11854            }
11855
11856            final int verifierUid = getUidForVerifier(verifierInfo);
11857            if (verifierUid == -1) {
11858                continue;
11859            }
11860
11861            if (DEBUG_VERIFY) {
11862                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
11863                        + " with the correct signature");
11864            }
11865            sufficientVerifiers.add(comp);
11866            verificationState.addSufficientVerifier(verifierUid);
11867        }
11868
11869        return sufficientVerifiers;
11870    }
11871
11872    private int getUidForVerifier(VerifierInfo verifierInfo) {
11873        synchronized (mPackages) {
11874            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
11875            if (pkg == null) {
11876                return -1;
11877            } else if (pkg.mSignatures.length != 1) {
11878                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
11879                        + " has more than one signature; ignoring");
11880                return -1;
11881            }
11882
11883            /*
11884             * If the public key of the package's signature does not match
11885             * our expected public key, then this is a different package and
11886             * we should skip.
11887             */
11888
11889            final byte[] expectedPublicKey;
11890            try {
11891                final Signature verifierSig = pkg.mSignatures[0];
11892                final PublicKey publicKey = verifierSig.getPublicKey();
11893                expectedPublicKey = publicKey.getEncoded();
11894            } catch (CertificateException e) {
11895                return -1;
11896            }
11897
11898            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
11899
11900            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
11901                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
11902                        + " does not have the expected public key; ignoring");
11903                return -1;
11904            }
11905
11906            return pkg.applicationInfo.uid;
11907        }
11908    }
11909
11910    @Override
11911    public void finishPackageInstall(int token, boolean didLaunch) {
11912        enforceSystemOrRoot("Only the system is allowed to finish installs");
11913
11914        if (DEBUG_INSTALL) {
11915            Slog.v(TAG, "BM finishing package install for " + token);
11916        }
11917        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
11918
11919        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, didLaunch ? 1 : 0);
11920        mHandler.sendMessage(msg);
11921    }
11922
11923    /**
11924     * Get the verification agent timeout.
11925     *
11926     * @return verification timeout in milliseconds
11927     */
11928    private long getVerificationTimeout() {
11929        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
11930                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
11931                DEFAULT_VERIFICATION_TIMEOUT);
11932    }
11933
11934    /**
11935     * Get the default verification agent response code.
11936     *
11937     * @return default verification response code
11938     */
11939    private int getDefaultVerificationResponse() {
11940        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
11941                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
11942                DEFAULT_VERIFICATION_RESPONSE);
11943    }
11944
11945    /**
11946     * Check whether or not package verification has been enabled.
11947     *
11948     * @return true if verification should be performed
11949     */
11950    private boolean isVerificationEnabled(int userId, int installFlags) {
11951        if (!DEFAULT_VERIFY_ENABLE) {
11952            return false;
11953        }
11954        // Ephemeral apps don't get the full verification treatment
11955        if ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) {
11956            if (DEBUG_EPHEMERAL) {
11957                Slog.d(TAG, "INSTALL_EPHEMERAL so skipping verification");
11958            }
11959            return false;
11960        }
11961
11962        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
11963
11964        // Check if installing from ADB
11965        if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
11966            // Do not run verification in a test harness environment
11967            if (ActivityManager.isRunningInTestHarness()) {
11968                return false;
11969            }
11970            if (ensureVerifyAppsEnabled) {
11971                return true;
11972            }
11973            // Check if the developer does not want package verification for ADB installs
11974            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
11975                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
11976                return false;
11977            }
11978        }
11979
11980        if (ensureVerifyAppsEnabled) {
11981            return true;
11982        }
11983
11984        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
11985                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
11986    }
11987
11988    @Override
11989    public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains)
11990            throws RemoteException {
11991        mContext.enforceCallingOrSelfPermission(
11992                Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
11993                "Only intentfilter verification agents can verify applications");
11994
11995        final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED);
11996        final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse(
11997                Binder.getCallingUid(), verificationCode, failedDomains);
11998        msg.arg1 = id;
11999        msg.obj = response;
12000        mHandler.sendMessage(msg);
12001    }
12002
12003    @Override
12004    public int getIntentVerificationStatus(String packageName, int userId) {
12005        synchronized (mPackages) {
12006            return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
12007        }
12008    }
12009
12010    @Override
12011    public boolean updateIntentVerificationStatus(String packageName, int status, int userId) {
12012        mContext.enforceCallingOrSelfPermission(
12013                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
12014
12015        boolean result = false;
12016        synchronized (mPackages) {
12017            result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId);
12018        }
12019        if (result) {
12020            scheduleWritePackageRestrictionsLocked(userId);
12021        }
12022        return result;
12023    }
12024
12025    @Override
12026    public @NonNull ParceledListSlice<IntentFilterVerificationInfo> getIntentFilterVerifications(
12027            String packageName) {
12028        synchronized (mPackages) {
12029            return new ParceledListSlice<>(mSettings.getIntentFilterVerificationsLPr(packageName));
12030        }
12031    }
12032
12033    @Override
12034    public @NonNull ParceledListSlice<IntentFilter> getAllIntentFilters(String packageName) {
12035        if (TextUtils.isEmpty(packageName)) {
12036            return ParceledListSlice.emptyList();
12037        }
12038        synchronized (mPackages) {
12039            PackageParser.Package pkg = mPackages.get(packageName);
12040            if (pkg == null || pkg.activities == null) {
12041                return ParceledListSlice.emptyList();
12042            }
12043            final int count = pkg.activities.size();
12044            ArrayList<IntentFilter> result = new ArrayList<>();
12045            for (int n=0; n<count; n++) {
12046                PackageParser.Activity activity = pkg.activities.get(n);
12047                if (activity.intents != null && activity.intents.size() > 0) {
12048                    result.addAll(activity.intents);
12049                }
12050            }
12051            return new ParceledListSlice<>(result);
12052        }
12053    }
12054
12055    @Override
12056    public boolean setDefaultBrowserPackageName(String packageName, int userId) {
12057        mContext.enforceCallingOrSelfPermission(
12058                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
12059
12060        synchronized (mPackages) {
12061            boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId);
12062            if (packageName != null) {
12063                result |= updateIntentVerificationStatus(packageName,
12064                        PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS,
12065                        userId);
12066                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr(
12067                        packageName, userId);
12068            }
12069            return result;
12070        }
12071    }
12072
12073    @Override
12074    public String getDefaultBrowserPackageName(int userId) {
12075        synchronized (mPackages) {
12076            return mSettings.getDefaultBrowserPackageNameLPw(userId);
12077        }
12078    }
12079
12080    /**
12081     * Get the "allow unknown sources" setting.
12082     *
12083     * @return the current "allow unknown sources" setting
12084     */
12085    private int getUnknownSourcesSettings() {
12086        return android.provider.Settings.Secure.getInt(mContext.getContentResolver(),
12087                android.provider.Settings.Secure.INSTALL_NON_MARKET_APPS,
12088                -1);
12089    }
12090
12091    @Override
12092    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
12093        final int uid = Binder.getCallingUid();
12094        // writer
12095        synchronized (mPackages) {
12096            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
12097            if (targetPackageSetting == null) {
12098                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
12099            }
12100
12101            PackageSetting installerPackageSetting;
12102            if (installerPackageName != null) {
12103                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
12104                if (installerPackageSetting == null) {
12105                    throw new IllegalArgumentException("Unknown installer package: "
12106                            + installerPackageName);
12107                }
12108            } else {
12109                installerPackageSetting = null;
12110            }
12111
12112            Signature[] callerSignature;
12113            Object obj = mSettings.getUserIdLPr(uid);
12114            if (obj != null) {
12115                if (obj instanceof SharedUserSetting) {
12116                    callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
12117                } else if (obj instanceof PackageSetting) {
12118                    callerSignature = ((PackageSetting)obj).signatures.mSignatures;
12119                } else {
12120                    throw new SecurityException("Bad object " + obj + " for uid " + uid);
12121                }
12122            } else {
12123                throw new SecurityException("Unknown calling UID: " + uid);
12124            }
12125
12126            // Verify: can't set installerPackageName to a package that is
12127            // not signed with the same cert as the caller.
12128            if (installerPackageSetting != null) {
12129                if (compareSignatures(callerSignature,
12130                        installerPackageSetting.signatures.mSignatures)
12131                        != PackageManager.SIGNATURE_MATCH) {
12132                    throw new SecurityException(
12133                            "Caller does not have same cert as new installer package "
12134                            + installerPackageName);
12135                }
12136            }
12137
12138            // Verify: if target already has an installer package, it must
12139            // be signed with the same cert as the caller.
12140            if (targetPackageSetting.installerPackageName != null) {
12141                PackageSetting setting = mSettings.mPackages.get(
12142                        targetPackageSetting.installerPackageName);
12143                // If the currently set package isn't valid, then it's always
12144                // okay to change it.
12145                if (setting != null) {
12146                    if (compareSignatures(callerSignature,
12147                            setting.signatures.mSignatures)
12148                            != PackageManager.SIGNATURE_MATCH) {
12149                        throw new SecurityException(
12150                                "Caller does not have same cert as old installer package "
12151                                + targetPackageSetting.installerPackageName);
12152                    }
12153                }
12154            }
12155
12156            // Okay!
12157            targetPackageSetting.installerPackageName = installerPackageName;
12158            if (installerPackageName != null) {
12159                mSettings.mInstallerPackages.add(installerPackageName);
12160            }
12161            scheduleWriteSettingsLocked();
12162        }
12163    }
12164
12165    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
12166        // Queue up an async operation since the package installation may take a little while.
12167        mHandler.post(new Runnable() {
12168            public void run() {
12169                mHandler.removeCallbacks(this);
12170                 // Result object to be returned
12171                PackageInstalledInfo res = new PackageInstalledInfo();
12172                res.setReturnCode(currentStatus);
12173                res.uid = -1;
12174                res.pkg = null;
12175                res.removedInfo = null;
12176                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
12177                    args.doPreInstall(res.returnCode);
12178                    synchronized (mInstallLock) {
12179                        installPackageTracedLI(args, res);
12180                    }
12181                    args.doPostInstall(res.returnCode, res.uid);
12182                }
12183
12184                // A restore should be performed at this point if (a) the install
12185                // succeeded, (b) the operation is not an update, and (c) the new
12186                // package has not opted out of backup participation.
12187                final boolean update = res.removedInfo != null
12188                        && res.removedInfo.removedPackage != null;
12189                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
12190                boolean doRestore = !update
12191                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
12192
12193                // Set up the post-install work request bookkeeping.  This will be used
12194                // and cleaned up by the post-install event handling regardless of whether
12195                // there's a restore pass performed.  Token values are >= 1.
12196                int token;
12197                if (mNextInstallToken < 0) mNextInstallToken = 1;
12198                token = mNextInstallToken++;
12199
12200                PostInstallData data = new PostInstallData(args, res);
12201                mRunningInstalls.put(token, data);
12202                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
12203
12204                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
12205                    // Pass responsibility to the Backup Manager.  It will perform a
12206                    // restore if appropriate, then pass responsibility back to the
12207                    // Package Manager to run the post-install observer callbacks
12208                    // and broadcasts.
12209                    IBackupManager bm = IBackupManager.Stub.asInterface(
12210                            ServiceManager.getService(Context.BACKUP_SERVICE));
12211                    if (bm != null) {
12212                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
12213                                + " to BM for possible restore");
12214                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
12215                        try {
12216                            // TODO: http://b/22388012
12217                            if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) {
12218                                bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
12219                            } else {
12220                                doRestore = false;
12221                            }
12222                        } catch (RemoteException e) {
12223                            // can't happen; the backup manager is local
12224                        } catch (Exception e) {
12225                            Slog.e(TAG, "Exception trying to enqueue restore", e);
12226                            doRestore = false;
12227                        }
12228                    } else {
12229                        Slog.e(TAG, "Backup Manager not found!");
12230                        doRestore = false;
12231                    }
12232                }
12233
12234                if (!doRestore) {
12235                    // No restore possible, or the Backup Manager was mysteriously not
12236                    // available -- just fire the post-install work request directly.
12237                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
12238
12239                    Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token);
12240
12241                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
12242                    mHandler.sendMessage(msg);
12243                }
12244            }
12245        });
12246    }
12247
12248    /**
12249     * Callback from PackageSettings whenever an app is first transitioned out of the
12250     * 'stopped' state.  Normally we just issue the broadcast, but we can't do that if
12251     * the app was "launched" for a restoreAtInstall operation.  Therefore we check
12252     * here whether the app is the target of an ongoing install, and only send the
12253     * broadcast immediately if it is not in that state.  If it *is* undergoing a restore,
12254     * the first-launch broadcast will be sent implicitly on that basis in POST_INSTALL
12255     * handling.
12256     */
12257    void notifyFirstLaunch(final String pkgName, final String installerPackage, final int userId) {
12258        // Serialize this with the rest of the install-process message chain.  In the
12259        // restore-at-install case, this Runnable will necessarily run before the
12260        // POST_INSTALL message is processed, so the contents of mRunningInstalls
12261        // are coherent.  In the non-restore case, the app has already completed install
12262        // and been launched through some other means, so it is not in a problematic
12263        // state for observers to see the FIRST_LAUNCH signal.
12264        mHandler.post(new Runnable() {
12265            @Override
12266            public void run() {
12267                for (int i = 0; i < mRunningInstalls.size(); i++) {
12268                    final PostInstallData data = mRunningInstalls.valueAt(i);
12269                    if (pkgName.equals(data.res.pkg.applicationInfo.packageName)) {
12270                        // right package; but is it for the right user?
12271                        for (int uIndex = 0; uIndex < data.res.newUsers.length; uIndex++) {
12272                            if (userId == data.res.newUsers[uIndex]) {
12273                                if (DEBUG_BACKUP) {
12274                                    Slog.i(TAG, "Package " + pkgName
12275                                            + " being restored so deferring FIRST_LAUNCH");
12276                                }
12277                                return;
12278                            }
12279                        }
12280                    }
12281                }
12282                // didn't find it, so not being restored
12283                if (DEBUG_BACKUP) {
12284                    Slog.i(TAG, "Package " + pkgName + " sending normal FIRST_LAUNCH");
12285                }
12286                sendFirstLaunchBroadcast(pkgName, installerPackage, new int[] {userId});
12287            }
12288        });
12289    }
12290
12291    private void sendFirstLaunchBroadcast(String pkgName, String installerPkg, int[] userIds) {
12292        sendPackageBroadcast(Intent.ACTION_PACKAGE_FIRST_LAUNCH, pkgName, null, 0,
12293                installerPkg, null, userIds);
12294    }
12295
12296    private abstract class HandlerParams {
12297        private static final int MAX_RETRIES = 4;
12298
12299        /**
12300         * Number of times startCopy() has been attempted and had a non-fatal
12301         * error.
12302         */
12303        private int mRetries = 0;
12304
12305        /** User handle for the user requesting the information or installation. */
12306        private final UserHandle mUser;
12307        String traceMethod;
12308        int traceCookie;
12309
12310        HandlerParams(UserHandle user) {
12311            mUser = user;
12312        }
12313
12314        UserHandle getUser() {
12315            return mUser;
12316        }
12317
12318        HandlerParams setTraceMethod(String traceMethod) {
12319            this.traceMethod = traceMethod;
12320            return this;
12321        }
12322
12323        HandlerParams setTraceCookie(int traceCookie) {
12324            this.traceCookie = traceCookie;
12325            return this;
12326        }
12327
12328        final boolean startCopy() {
12329            boolean res;
12330            try {
12331                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
12332
12333                if (++mRetries > MAX_RETRIES) {
12334                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
12335                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
12336                    handleServiceError();
12337                    return false;
12338                } else {
12339                    handleStartCopy();
12340                    res = true;
12341                }
12342            } catch (RemoteException e) {
12343                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
12344                mHandler.sendEmptyMessage(MCS_RECONNECT);
12345                res = false;
12346            }
12347            handleReturnCode();
12348            return res;
12349        }
12350
12351        final void serviceError() {
12352            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
12353            handleServiceError();
12354            handleReturnCode();
12355        }
12356
12357        abstract void handleStartCopy() throws RemoteException;
12358        abstract void handleServiceError();
12359        abstract void handleReturnCode();
12360    }
12361
12362    class MeasureParams extends HandlerParams {
12363        private final PackageStats mStats;
12364        private boolean mSuccess;
12365
12366        private final IPackageStatsObserver mObserver;
12367
12368        public MeasureParams(PackageStats stats, IPackageStatsObserver observer) {
12369            super(new UserHandle(stats.userHandle));
12370            mObserver = observer;
12371            mStats = stats;
12372        }
12373
12374        @Override
12375        public String toString() {
12376            return "MeasureParams{"
12377                + Integer.toHexString(System.identityHashCode(this))
12378                + " " + mStats.packageName + "}";
12379        }
12380
12381        @Override
12382        void handleStartCopy() throws RemoteException {
12383            synchronized (mInstallLock) {
12384                mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats);
12385            }
12386
12387            if (mSuccess) {
12388                boolean mounted = false;
12389                try {
12390                    final String status = Environment.getExternalStorageState();
12391                    mounted = (Environment.MEDIA_MOUNTED.equals(status)
12392                            || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status));
12393                } catch (Exception e) {
12394                }
12395
12396                if (mounted) {
12397                    final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle);
12398
12399                    mStats.externalCacheSize = calculateDirectorySize(mContainerService,
12400                            userEnv.buildExternalStorageAppCacheDirs(mStats.packageName));
12401
12402                    mStats.externalDataSize = calculateDirectorySize(mContainerService,
12403                            userEnv.buildExternalStorageAppDataDirs(mStats.packageName));
12404
12405                    // Always subtract cache size, since it's a subdirectory
12406                    mStats.externalDataSize -= mStats.externalCacheSize;
12407
12408                    mStats.externalMediaSize = calculateDirectorySize(mContainerService,
12409                            userEnv.buildExternalStorageAppMediaDirs(mStats.packageName));
12410
12411                    mStats.externalObbSize = calculateDirectorySize(mContainerService,
12412                            userEnv.buildExternalStorageAppObbDirs(mStats.packageName));
12413                }
12414            }
12415        }
12416
12417        @Override
12418        void handleReturnCode() {
12419            if (mObserver != null) {
12420                try {
12421                    mObserver.onGetStatsCompleted(mStats, mSuccess);
12422                } catch (RemoteException e) {
12423                    Slog.i(TAG, "Observer no longer exists.");
12424                }
12425            }
12426        }
12427
12428        @Override
12429        void handleServiceError() {
12430            Slog.e(TAG, "Could not measure application " + mStats.packageName
12431                            + " external storage");
12432        }
12433    }
12434
12435    private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths)
12436            throws RemoteException {
12437        long result = 0;
12438        for (File path : paths) {
12439            result += mcs.calculateDirectorySize(path.getAbsolutePath());
12440        }
12441        return result;
12442    }
12443
12444    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
12445        for (File path : paths) {
12446            try {
12447                mcs.clearDirectory(path.getAbsolutePath());
12448            } catch (RemoteException e) {
12449            }
12450        }
12451    }
12452
12453    static class OriginInfo {
12454        /**
12455         * Location where install is coming from, before it has been
12456         * copied/renamed into place. This could be a single monolithic APK
12457         * file, or a cluster directory. This location may be untrusted.
12458         */
12459        final File file;
12460        final String cid;
12461
12462        /**
12463         * Flag indicating that {@link #file} or {@link #cid} has already been
12464         * staged, meaning downstream users don't need to defensively copy the
12465         * contents.
12466         */
12467        final boolean staged;
12468
12469        /**
12470         * Flag indicating that {@link #file} or {@link #cid} is an already
12471         * installed app that is being moved.
12472         */
12473        final boolean existing;
12474
12475        final String resolvedPath;
12476        final File resolvedFile;
12477
12478        static OriginInfo fromNothing() {
12479            return new OriginInfo(null, null, false, false);
12480        }
12481
12482        static OriginInfo fromUntrustedFile(File file) {
12483            return new OriginInfo(file, null, false, false);
12484        }
12485
12486        static OriginInfo fromExistingFile(File file) {
12487            return new OriginInfo(file, null, false, true);
12488        }
12489
12490        static OriginInfo fromStagedFile(File file) {
12491            return new OriginInfo(file, null, true, false);
12492        }
12493
12494        static OriginInfo fromStagedContainer(String cid) {
12495            return new OriginInfo(null, cid, true, false);
12496        }
12497
12498        private OriginInfo(File file, String cid, boolean staged, boolean existing) {
12499            this.file = file;
12500            this.cid = cid;
12501            this.staged = staged;
12502            this.existing = existing;
12503
12504            if (cid != null) {
12505                resolvedPath = PackageHelper.getSdDir(cid);
12506                resolvedFile = new File(resolvedPath);
12507            } else if (file != null) {
12508                resolvedPath = file.getAbsolutePath();
12509                resolvedFile = file;
12510            } else {
12511                resolvedPath = null;
12512                resolvedFile = null;
12513            }
12514        }
12515    }
12516
12517    static class MoveInfo {
12518        final int moveId;
12519        final String fromUuid;
12520        final String toUuid;
12521        final String packageName;
12522        final String dataAppName;
12523        final int appId;
12524        final String seinfo;
12525        final int targetSdkVersion;
12526
12527        public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName,
12528                String dataAppName, int appId, String seinfo, int targetSdkVersion) {
12529            this.moveId = moveId;
12530            this.fromUuid = fromUuid;
12531            this.toUuid = toUuid;
12532            this.packageName = packageName;
12533            this.dataAppName = dataAppName;
12534            this.appId = appId;
12535            this.seinfo = seinfo;
12536            this.targetSdkVersion = targetSdkVersion;
12537        }
12538    }
12539
12540    static class VerificationInfo {
12541        /** A constant used to indicate that a uid value is not present. */
12542        public static final int NO_UID = -1;
12543
12544        /** URI referencing where the package was downloaded from. */
12545        final Uri originatingUri;
12546
12547        /** HTTP referrer URI associated with the originatingURI. */
12548        final Uri referrer;
12549
12550        /** UID of the application that the install request originated from. */
12551        final int originatingUid;
12552
12553        /** UID of application requesting the install */
12554        final int installerUid;
12555
12556        VerificationInfo(Uri originatingUri, Uri referrer, int originatingUid, int installerUid) {
12557            this.originatingUri = originatingUri;
12558            this.referrer = referrer;
12559            this.originatingUid = originatingUid;
12560            this.installerUid = installerUid;
12561        }
12562    }
12563
12564    class InstallParams extends HandlerParams {
12565        final OriginInfo origin;
12566        final MoveInfo move;
12567        final IPackageInstallObserver2 observer;
12568        int installFlags;
12569        final String installerPackageName;
12570        final String volumeUuid;
12571        private InstallArgs mArgs;
12572        private int mRet;
12573        final String packageAbiOverride;
12574        final String[] grantedRuntimePermissions;
12575        final VerificationInfo verificationInfo;
12576        final Certificate[][] certificates;
12577
12578        InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
12579                int installFlags, String installerPackageName, String volumeUuid,
12580                VerificationInfo verificationInfo, UserHandle user, String packageAbiOverride,
12581                String[] grantedPermissions, Certificate[][] certificates) {
12582            super(user);
12583            this.origin = origin;
12584            this.move = move;
12585            this.observer = observer;
12586            this.installFlags = installFlags;
12587            this.installerPackageName = installerPackageName;
12588            this.volumeUuid = volumeUuid;
12589            this.verificationInfo = verificationInfo;
12590            this.packageAbiOverride = packageAbiOverride;
12591            this.grantedRuntimePermissions = grantedPermissions;
12592            this.certificates = certificates;
12593        }
12594
12595        @Override
12596        public String toString() {
12597            return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
12598                    + " file=" + origin.file + " cid=" + origin.cid + "}";
12599        }
12600
12601        private int installLocationPolicy(PackageInfoLite pkgLite) {
12602            String packageName = pkgLite.packageName;
12603            int installLocation = pkgLite.installLocation;
12604            boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
12605            // reader
12606            synchronized (mPackages) {
12607                // Currently installed package which the new package is attempting to replace or
12608                // null if no such package is installed.
12609                PackageParser.Package installedPkg = mPackages.get(packageName);
12610                // Package which currently owns the data which the new package will own if installed.
12611                // If an app is unstalled while keeping data (e.g., adb uninstall -k), installedPkg
12612                // will be null whereas dataOwnerPkg will contain information about the package
12613                // which was uninstalled while keeping its data.
12614                PackageParser.Package dataOwnerPkg = installedPkg;
12615                if (dataOwnerPkg  == null) {
12616                    PackageSetting ps = mSettings.mPackages.get(packageName);
12617                    if (ps != null) {
12618                        dataOwnerPkg = ps.pkg;
12619                    }
12620                }
12621
12622                if (dataOwnerPkg != null) {
12623                    // If installed, the package will get access to data left on the device by its
12624                    // predecessor. As a security measure, this is permited only if this is not a
12625                    // version downgrade or if the predecessor package is marked as debuggable and
12626                    // a downgrade is explicitly requested.
12627                    //
12628                    // On debuggable platform builds, downgrades are permitted even for
12629                    // non-debuggable packages to make testing easier. Debuggable platform builds do
12630                    // not offer security guarantees and thus it's OK to disable some security
12631                    // mechanisms to make debugging/testing easier on those builds. However, even on
12632                    // debuggable builds downgrades of packages are permitted only if requested via
12633                    // installFlags. This is because we aim to keep the behavior of debuggable
12634                    // platform builds as close as possible to the behavior of non-debuggable
12635                    // platform builds.
12636                    final boolean downgradeRequested =
12637                            (installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) != 0;
12638                    final boolean packageDebuggable =
12639                                (dataOwnerPkg.applicationInfo.flags
12640                                        & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
12641                    final boolean downgradePermitted =
12642                            (downgradeRequested) && ((Build.IS_DEBUGGABLE) || (packageDebuggable));
12643                    if (!downgradePermitted) {
12644                        try {
12645                            checkDowngrade(dataOwnerPkg, pkgLite);
12646                        } catch (PackageManagerException e) {
12647                            Slog.w(TAG, "Downgrade detected: " + e.getMessage());
12648                            return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
12649                        }
12650                    }
12651                }
12652
12653                if (installedPkg != null) {
12654                    if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
12655                        // Check for updated system application.
12656                        if ((installedPkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
12657                            if (onSd) {
12658                                Slog.w(TAG, "Cannot install update to system app on sdcard");
12659                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
12660                            }
12661                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
12662                        } else {
12663                            if (onSd) {
12664                                // Install flag overrides everything.
12665                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
12666                            }
12667                            // If current upgrade specifies particular preference
12668                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
12669                                // Application explicitly specified internal.
12670                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
12671                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
12672                                // App explictly prefers external. Let policy decide
12673                            } else {
12674                                // Prefer previous location
12675                                if (isExternal(installedPkg)) {
12676                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
12677                                }
12678                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
12679                            }
12680                        }
12681                    } else {
12682                        // Invalid install. Return error code
12683                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
12684                    }
12685                }
12686            }
12687            // All the special cases have been taken care of.
12688            // Return result based on recommended install location.
12689            if (onSd) {
12690                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
12691            }
12692            return pkgLite.recommendedInstallLocation;
12693        }
12694
12695        /*
12696         * Invoke remote method to get package information and install
12697         * location values. Override install location based on default
12698         * policy if needed and then create install arguments based
12699         * on the install location.
12700         */
12701        public void handleStartCopy() throws RemoteException {
12702            int ret = PackageManager.INSTALL_SUCCEEDED;
12703
12704            // If we're already staged, we've firmly committed to an install location
12705            if (origin.staged) {
12706                if (origin.file != null) {
12707                    installFlags |= PackageManager.INSTALL_INTERNAL;
12708                    installFlags &= ~PackageManager.INSTALL_EXTERNAL;
12709                } else if (origin.cid != null) {
12710                    installFlags |= PackageManager.INSTALL_EXTERNAL;
12711                    installFlags &= ~PackageManager.INSTALL_INTERNAL;
12712                } else {
12713                    throw new IllegalStateException("Invalid stage location");
12714                }
12715            }
12716
12717            final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
12718            final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
12719            final boolean ephemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0;
12720            PackageInfoLite pkgLite = null;
12721
12722            if (onInt && onSd) {
12723                // Check if both bits are set.
12724                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
12725                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
12726            } else if (onSd && ephemeral) {
12727                Slog.w(TAG,  "Conflicting flags specified for installing ephemeral on external");
12728                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
12729            } else {
12730                pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
12731                        packageAbiOverride);
12732
12733                if (DEBUG_EPHEMERAL && ephemeral) {
12734                    Slog.v(TAG, "pkgLite for install: " + pkgLite);
12735                }
12736
12737                /*
12738                 * If we have too little free space, try to free cache
12739                 * before giving up.
12740                 */
12741                if (!origin.staged && pkgLite.recommendedInstallLocation
12742                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
12743                    // TODO: focus freeing disk space on the target device
12744                    final StorageManager storage = StorageManager.from(mContext);
12745                    final long lowThreshold = storage.getStorageLowBytes(
12746                            Environment.getDataDirectory());
12747
12748                    final long sizeBytes = mContainerService.calculateInstalledSize(
12749                            origin.resolvedPath, isForwardLocked(), packageAbiOverride);
12750
12751                    try {
12752                        mInstaller.freeCache(null, sizeBytes + lowThreshold);
12753                        pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
12754                                installFlags, packageAbiOverride);
12755                    } catch (InstallerException e) {
12756                        Slog.w(TAG, "Failed to free cache", e);
12757                    }
12758
12759                    /*
12760                     * The cache free must have deleted the file we
12761                     * downloaded to install.
12762                     *
12763                     * TODO: fix the "freeCache" call to not delete
12764                     *       the file we care about.
12765                     */
12766                    if (pkgLite.recommendedInstallLocation
12767                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
12768                        pkgLite.recommendedInstallLocation
12769                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
12770                    }
12771                }
12772            }
12773
12774            if (ret == PackageManager.INSTALL_SUCCEEDED) {
12775                int loc = pkgLite.recommendedInstallLocation;
12776                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
12777                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
12778                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
12779                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
12780                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
12781                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
12782                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
12783                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
12784                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
12785                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
12786                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
12787                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
12788                } else {
12789                    // Override with defaults if needed.
12790                    loc = installLocationPolicy(pkgLite);
12791                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
12792                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
12793                    } else if (!onSd && !onInt) {
12794                        // Override install location with flags
12795                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
12796                            // Set the flag to install on external media.
12797                            installFlags |= PackageManager.INSTALL_EXTERNAL;
12798                            installFlags &= ~PackageManager.INSTALL_INTERNAL;
12799                        } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) {
12800                            if (DEBUG_EPHEMERAL) {
12801                                Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag");
12802                            }
12803                            installFlags |= PackageManager.INSTALL_EPHEMERAL;
12804                            installFlags &= ~(PackageManager.INSTALL_EXTERNAL
12805                                    |PackageManager.INSTALL_INTERNAL);
12806                        } else {
12807                            // Make sure the flag for installing on external
12808                            // media is unset
12809                            installFlags |= PackageManager.INSTALL_INTERNAL;
12810                            installFlags &= ~PackageManager.INSTALL_EXTERNAL;
12811                        }
12812                    }
12813                }
12814            }
12815
12816            final InstallArgs args = createInstallArgs(this);
12817            mArgs = args;
12818
12819            if (ret == PackageManager.INSTALL_SUCCEEDED) {
12820                // TODO: http://b/22976637
12821                // Apps installed for "all" users use the device owner to verify the app
12822                UserHandle verifierUser = getUser();
12823                if (verifierUser == UserHandle.ALL) {
12824                    verifierUser = UserHandle.SYSTEM;
12825                }
12826
12827                /*
12828                 * Determine if we have any installed package verifiers. If we
12829                 * do, then we'll defer to them to verify the packages.
12830                 */
12831                final int requiredUid = mRequiredVerifierPackage == null ? -1
12832                        : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
12833                                verifierUser.getIdentifier());
12834                if (!origin.existing && requiredUid != -1
12835                        && isVerificationEnabled(verifierUser.getIdentifier(), installFlags)) {
12836                    final Intent verification = new Intent(
12837                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
12838                    verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
12839                    verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
12840                            PACKAGE_MIME_TYPE);
12841                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
12842
12843                    // Query all live verifiers based on current user state
12844                    final List<ResolveInfo> receivers = queryIntentReceiversInternal(verification,
12845                            PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier());
12846
12847                    if (DEBUG_VERIFY) {
12848                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
12849                                + verification.toString() + " with " + pkgLite.verifiers.length
12850                                + " optional verifiers");
12851                    }
12852
12853                    final int verificationId = mPendingVerificationToken++;
12854
12855                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
12856
12857                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
12858                            installerPackageName);
12859
12860                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
12861                            installFlags);
12862
12863                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
12864                            pkgLite.packageName);
12865
12866                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
12867                            pkgLite.versionCode);
12868
12869                    if (verificationInfo != null) {
12870                        if (verificationInfo.originatingUri != null) {
12871                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
12872                                    verificationInfo.originatingUri);
12873                        }
12874                        if (verificationInfo.referrer != null) {
12875                            verification.putExtra(Intent.EXTRA_REFERRER,
12876                                    verificationInfo.referrer);
12877                        }
12878                        if (verificationInfo.originatingUid >= 0) {
12879                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
12880                                    verificationInfo.originatingUid);
12881                        }
12882                        if (verificationInfo.installerUid >= 0) {
12883                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
12884                                    verificationInfo.installerUid);
12885                        }
12886                    }
12887
12888                    final PackageVerificationState verificationState = new PackageVerificationState(
12889                            requiredUid, args);
12890
12891                    mPendingVerification.append(verificationId, verificationState);
12892
12893                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
12894                            receivers, verificationState);
12895
12896                    /*
12897                     * If any sufficient verifiers were listed in the package
12898                     * manifest, attempt to ask them.
12899                     */
12900                    if (sufficientVerifiers != null) {
12901                        final int N = sufficientVerifiers.size();
12902                        if (N == 0) {
12903                            Slog.i(TAG, "Additional verifiers required, but none installed.");
12904                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
12905                        } else {
12906                            for (int i = 0; i < N; i++) {
12907                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
12908
12909                                final Intent sufficientIntent = new Intent(verification);
12910                                sufficientIntent.setComponent(verifierComponent);
12911                                mContext.sendBroadcastAsUser(sufficientIntent, verifierUser);
12912                            }
12913                        }
12914                    }
12915
12916                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
12917                            mRequiredVerifierPackage, receivers);
12918                    if (ret == PackageManager.INSTALL_SUCCEEDED
12919                            && mRequiredVerifierPackage != null) {
12920                        Trace.asyncTraceBegin(
12921                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
12922                        /*
12923                         * Send the intent to the required verification agent,
12924                         * but only start the verification timeout after the
12925                         * target BroadcastReceivers have run.
12926                         */
12927                        verification.setComponent(requiredVerifierComponent);
12928                        mContext.sendOrderedBroadcastAsUser(verification, verifierUser,
12929                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
12930                                new BroadcastReceiver() {
12931                                    @Override
12932                                    public void onReceive(Context context, Intent intent) {
12933                                        final Message msg = mHandler
12934                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
12935                                        msg.arg1 = verificationId;
12936                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
12937                                    }
12938                                }, null, 0, null, null);
12939
12940                        /*
12941                         * We don't want the copy to proceed until verification
12942                         * succeeds, so null out this field.
12943                         */
12944                        mArgs = null;
12945                    }
12946                } else {
12947                    /*
12948                     * No package verification is enabled, so immediately start
12949                     * the remote call to initiate copy using temporary file.
12950                     */
12951                    ret = args.copyApk(mContainerService, true);
12952                }
12953            }
12954
12955            mRet = ret;
12956        }
12957
12958        @Override
12959        void handleReturnCode() {
12960            // If mArgs is null, then MCS couldn't be reached. When it
12961            // reconnects, it will try again to install. At that point, this
12962            // will succeed.
12963            if (mArgs != null) {
12964                processPendingInstall(mArgs, mRet);
12965            }
12966        }
12967
12968        @Override
12969        void handleServiceError() {
12970            mArgs = createInstallArgs(this);
12971            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
12972        }
12973
12974        public boolean isForwardLocked() {
12975            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
12976        }
12977    }
12978
12979    /**
12980     * Used during creation of InstallArgs
12981     *
12982     * @param installFlags package installation flags
12983     * @return true if should be installed on external storage
12984     */
12985    private static boolean installOnExternalAsec(int installFlags) {
12986        if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) {
12987            return false;
12988        }
12989        if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
12990            return true;
12991        }
12992        return false;
12993    }
12994
12995    /**
12996     * Used during creation of InstallArgs
12997     *
12998     * @param installFlags package installation flags
12999     * @return true if should be installed as forward locked
13000     */
13001    private static boolean installForwardLocked(int installFlags) {
13002        return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
13003    }
13004
13005    private InstallArgs createInstallArgs(InstallParams params) {
13006        if (params.move != null) {
13007            return new MoveInstallArgs(params);
13008        } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) {
13009            return new AsecInstallArgs(params);
13010        } else {
13011            return new FileInstallArgs(params);
13012        }
13013    }
13014
13015    /**
13016     * Create args that describe an existing installed package. Typically used
13017     * when cleaning up old installs, or used as a move source.
13018     */
13019    private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
13020            String resourcePath, String[] instructionSets) {
13021        final boolean isInAsec;
13022        if (installOnExternalAsec(installFlags)) {
13023            /* Apps on SD card are always in ASEC containers. */
13024            isInAsec = true;
13025        } else if (installForwardLocked(installFlags)
13026                && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) {
13027            /*
13028             * Forward-locked apps are only in ASEC containers if they're the
13029             * new style
13030             */
13031            isInAsec = true;
13032        } else {
13033            isInAsec = false;
13034        }
13035
13036        if (isInAsec) {
13037            return new AsecInstallArgs(codePath, instructionSets,
13038                    installOnExternalAsec(installFlags), installForwardLocked(installFlags));
13039        } else {
13040            return new FileInstallArgs(codePath, resourcePath, instructionSets);
13041        }
13042    }
13043
13044    static abstract class InstallArgs {
13045        /** @see InstallParams#origin */
13046        final OriginInfo origin;
13047        /** @see InstallParams#move */
13048        final MoveInfo move;
13049
13050        final IPackageInstallObserver2 observer;
13051        // Always refers to PackageManager flags only
13052        final int installFlags;
13053        final String installerPackageName;
13054        final String volumeUuid;
13055        final UserHandle user;
13056        final String abiOverride;
13057        final String[] installGrantPermissions;
13058        /** If non-null, drop an async trace when the install completes */
13059        final String traceMethod;
13060        final int traceCookie;
13061        final Certificate[][] certificates;
13062
13063        // The list of instruction sets supported by this app. This is currently
13064        // only used during the rmdex() phase to clean up resources. We can get rid of this
13065        // if we move dex files under the common app path.
13066        /* nullable */ String[] instructionSets;
13067
13068        InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
13069                int installFlags, String installerPackageName, String volumeUuid,
13070                UserHandle user, String[] instructionSets,
13071                String abiOverride, String[] installGrantPermissions,
13072                String traceMethod, int traceCookie, Certificate[][] certificates) {
13073            this.origin = origin;
13074            this.move = move;
13075            this.installFlags = installFlags;
13076            this.observer = observer;
13077            this.installerPackageName = installerPackageName;
13078            this.volumeUuid = volumeUuid;
13079            this.user = user;
13080            this.instructionSets = instructionSets;
13081            this.abiOverride = abiOverride;
13082            this.installGrantPermissions = installGrantPermissions;
13083            this.traceMethod = traceMethod;
13084            this.traceCookie = traceCookie;
13085            this.certificates = certificates;
13086        }
13087
13088        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
13089        abstract int doPreInstall(int status);
13090
13091        /**
13092         * Rename package into final resting place. All paths on the given
13093         * scanned package should be updated to reflect the rename.
13094         */
13095        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
13096        abstract int doPostInstall(int status, int uid);
13097
13098        /** @see PackageSettingBase#codePathString */
13099        abstract String getCodePath();
13100        /** @see PackageSettingBase#resourcePathString */
13101        abstract String getResourcePath();
13102
13103        // Need installer lock especially for dex file removal.
13104        abstract void cleanUpResourcesLI();
13105        abstract boolean doPostDeleteLI(boolean delete);
13106
13107        /**
13108         * Called before the source arguments are copied. This is used mostly
13109         * for MoveParams when it needs to read the source file to put it in the
13110         * destination.
13111         */
13112        int doPreCopy() {
13113            return PackageManager.INSTALL_SUCCEEDED;
13114        }
13115
13116        /**
13117         * Called after the source arguments are copied. This is used mostly for
13118         * MoveParams when it needs to read the source file to put it in the
13119         * destination.
13120         */
13121        int doPostCopy(int uid) {
13122            return PackageManager.INSTALL_SUCCEEDED;
13123        }
13124
13125        protected boolean isFwdLocked() {
13126            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
13127        }
13128
13129        protected boolean isExternalAsec() {
13130            return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
13131        }
13132
13133        protected boolean isEphemeral() {
13134            return (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0;
13135        }
13136
13137        UserHandle getUser() {
13138            return user;
13139        }
13140    }
13141
13142    private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) {
13143        if (!allCodePaths.isEmpty()) {
13144            if (instructionSets == null) {
13145                throw new IllegalStateException("instructionSet == null");
13146            }
13147            String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
13148            for (String codePath : allCodePaths) {
13149                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
13150                    try {
13151                        mInstaller.rmdex(codePath, dexCodeInstructionSet);
13152                    } catch (InstallerException ignored) {
13153                    }
13154                }
13155            }
13156        }
13157    }
13158
13159    /**
13160     * Logic to handle installation of non-ASEC applications, including copying
13161     * and renaming logic.
13162     */
13163    class FileInstallArgs extends InstallArgs {
13164        private File codeFile;
13165        private File resourceFile;
13166
13167        // Example topology:
13168        // /data/app/com.example/base.apk
13169        // /data/app/com.example/split_foo.apk
13170        // /data/app/com.example/lib/arm/libfoo.so
13171        // /data/app/com.example/lib/arm64/libfoo.so
13172        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
13173
13174        /** New install */
13175        FileInstallArgs(InstallParams params) {
13176            super(params.origin, params.move, params.observer, params.installFlags,
13177                    params.installerPackageName, params.volumeUuid,
13178                    params.getUser(), null /*instructionSets*/, params.packageAbiOverride,
13179                    params.grantedRuntimePermissions,
13180                    params.traceMethod, params.traceCookie, params.certificates);
13181            if (isFwdLocked()) {
13182                throw new IllegalArgumentException("Forward locking only supported in ASEC");
13183            }
13184        }
13185
13186        /** Existing install */
13187        FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) {
13188            super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets,
13189                    null, null, null, 0, null /*certificates*/);
13190            this.codeFile = (codePath != null) ? new File(codePath) : null;
13191            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
13192        }
13193
13194        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
13195            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk");
13196            try {
13197                return doCopyApk(imcs, temp);
13198            } finally {
13199                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
13200            }
13201        }
13202
13203        private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
13204            if (origin.staged) {
13205                if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy");
13206                codeFile = origin.file;
13207                resourceFile = origin.file;
13208                return PackageManager.INSTALL_SUCCEEDED;
13209            }
13210
13211            try {
13212                final boolean isEphemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0;
13213                final File tempDir =
13214                        mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral);
13215                codeFile = tempDir;
13216                resourceFile = tempDir;
13217            } catch (IOException e) {
13218                Slog.w(TAG, "Failed to create copy file: " + e);
13219                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
13220            }
13221
13222            final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
13223                @Override
13224                public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
13225                    if (!FileUtils.isValidExtFilename(name)) {
13226                        throw new IllegalArgumentException("Invalid filename: " + name);
13227                    }
13228                    try {
13229                        final File file = new File(codeFile, name);
13230                        final FileDescriptor fd = Os.open(file.getAbsolutePath(),
13231                                O_RDWR | O_CREAT, 0644);
13232                        Os.chmod(file.getAbsolutePath(), 0644);
13233                        return new ParcelFileDescriptor(fd);
13234                    } catch (ErrnoException e) {
13235                        throw new RemoteException("Failed to open: " + e.getMessage());
13236                    }
13237                }
13238            };
13239
13240            int ret = PackageManager.INSTALL_SUCCEEDED;
13241            ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
13242            if (ret != PackageManager.INSTALL_SUCCEEDED) {
13243                Slog.e(TAG, "Failed to copy package");
13244                return ret;
13245            }
13246
13247            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
13248            NativeLibraryHelper.Handle handle = null;
13249            try {
13250                handle = NativeLibraryHelper.Handle.create(codeFile);
13251                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
13252                        abiOverride);
13253            } catch (IOException e) {
13254                Slog.e(TAG, "Copying native libraries failed", e);
13255                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
13256            } finally {
13257                IoUtils.closeQuietly(handle);
13258            }
13259
13260            return ret;
13261        }
13262
13263        int doPreInstall(int status) {
13264            if (status != PackageManager.INSTALL_SUCCEEDED) {
13265                cleanUp();
13266            }
13267            return status;
13268        }
13269
13270        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
13271            if (status != PackageManager.INSTALL_SUCCEEDED) {
13272                cleanUp();
13273                return false;
13274            }
13275
13276            final File targetDir = codeFile.getParentFile();
13277            final File beforeCodeFile = codeFile;
13278            final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName);
13279
13280            if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
13281            try {
13282                Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
13283            } catch (ErrnoException e) {
13284                Slog.w(TAG, "Failed to rename", e);
13285                return false;
13286            }
13287
13288            if (!SELinux.restoreconRecursive(afterCodeFile)) {
13289                Slog.w(TAG, "Failed to restorecon");
13290                return false;
13291            }
13292
13293            // Reflect the rename internally
13294            codeFile = afterCodeFile;
13295            resourceFile = afterCodeFile;
13296
13297            // Reflect the rename in scanned details
13298            pkg.setCodePath(afterCodeFile.getAbsolutePath());
13299            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
13300                    afterCodeFile, pkg.baseCodePath));
13301            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
13302                    afterCodeFile, pkg.splitCodePaths));
13303
13304            // Reflect the rename in app info
13305            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
13306            pkg.setApplicationInfoCodePath(pkg.codePath);
13307            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
13308            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
13309            pkg.setApplicationInfoResourcePath(pkg.codePath);
13310            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
13311            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
13312
13313            return true;
13314        }
13315
13316        int doPostInstall(int status, int uid) {
13317            if (status != PackageManager.INSTALL_SUCCEEDED) {
13318                cleanUp();
13319            }
13320            return status;
13321        }
13322
13323        @Override
13324        String getCodePath() {
13325            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
13326        }
13327
13328        @Override
13329        String getResourcePath() {
13330            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
13331        }
13332
13333        private boolean cleanUp() {
13334            if (codeFile == null || !codeFile.exists()) {
13335                return false;
13336            }
13337
13338            removeCodePathLI(codeFile);
13339
13340            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
13341                resourceFile.delete();
13342            }
13343
13344            return true;
13345        }
13346
13347        void cleanUpResourcesLI() {
13348            // Try enumerating all code paths before deleting
13349            List<String> allCodePaths = Collections.EMPTY_LIST;
13350            if (codeFile != null && codeFile.exists()) {
13351                try {
13352                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
13353                    allCodePaths = pkg.getAllCodePaths();
13354                } catch (PackageParserException e) {
13355                    // Ignored; we tried our best
13356                }
13357            }
13358
13359            cleanUp();
13360            removeDexFiles(allCodePaths, instructionSets);
13361        }
13362
13363        boolean doPostDeleteLI(boolean delete) {
13364            // XXX err, shouldn't we respect the delete flag?
13365            cleanUpResourcesLI();
13366            return true;
13367        }
13368    }
13369
13370    private boolean isAsecExternal(String cid) {
13371        final String asecPath = PackageHelper.getSdFilesystem(cid);
13372        return !asecPath.startsWith(mAsecInternalPath);
13373    }
13374
13375    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
13376            PackageManagerException {
13377        if (copyRet < 0) {
13378            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
13379                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
13380                throw new PackageManagerException(copyRet, message);
13381            }
13382        }
13383    }
13384
13385    /**
13386     * Extract the MountService "container ID" from the full code path of an
13387     * .apk.
13388     */
13389    static String cidFromCodePath(String fullCodePath) {
13390        int eidx = fullCodePath.lastIndexOf("/");
13391        String subStr1 = fullCodePath.substring(0, eidx);
13392        int sidx = subStr1.lastIndexOf("/");
13393        return subStr1.substring(sidx+1, eidx);
13394    }
13395
13396    /**
13397     * Logic to handle installation of ASEC applications, including copying and
13398     * renaming logic.
13399     */
13400    class AsecInstallArgs extends InstallArgs {
13401        static final String RES_FILE_NAME = "pkg.apk";
13402        static final String PUBLIC_RES_FILE_NAME = "res.zip";
13403
13404        String cid;
13405        String packagePath;
13406        String resourcePath;
13407
13408        /** New install */
13409        AsecInstallArgs(InstallParams params) {
13410            super(params.origin, params.move, params.observer, params.installFlags,
13411                    params.installerPackageName, params.volumeUuid,
13412                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
13413                    params.grantedRuntimePermissions,
13414                    params.traceMethod, params.traceCookie, params.certificates);
13415        }
13416
13417        /** Existing install */
13418        AsecInstallArgs(String fullCodePath, String[] instructionSets,
13419                        boolean isExternal, boolean isForwardLocked) {
13420            super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0)
13421              | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
13422                    instructionSets, null, null, null, 0, null /*certificates*/);
13423            // Hackily pretend we're still looking at a full code path
13424            if (!fullCodePath.endsWith(RES_FILE_NAME)) {
13425                fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath();
13426            }
13427
13428            // Extract cid from fullCodePath
13429            int eidx = fullCodePath.lastIndexOf("/");
13430            String subStr1 = fullCodePath.substring(0, eidx);
13431            int sidx = subStr1.lastIndexOf("/");
13432            cid = subStr1.substring(sidx+1, eidx);
13433            setMountPath(subStr1);
13434        }
13435
13436        AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) {
13437            super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0)
13438              | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
13439                    instructionSets, null, null, null, 0, null /*certificates*/);
13440            this.cid = cid;
13441            setMountPath(PackageHelper.getSdDir(cid));
13442        }
13443
13444        void createCopyFile() {
13445            cid = mInstallerService.allocateExternalStageCidLegacy();
13446        }
13447
13448        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
13449            if (origin.staged && origin.cid != null) {
13450                if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy");
13451                cid = origin.cid;
13452                setMountPath(PackageHelper.getSdDir(cid));
13453                return PackageManager.INSTALL_SUCCEEDED;
13454            }
13455
13456            if (temp) {
13457                createCopyFile();
13458            } else {
13459                /*
13460                 * Pre-emptively destroy the container since it's destroyed if
13461                 * copying fails due to it existing anyway.
13462                 */
13463                PackageHelper.destroySdDir(cid);
13464            }
13465
13466            final String newMountPath = imcs.copyPackageToContainer(
13467                    origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(),
13468                    isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */));
13469
13470            if (newMountPath != null) {
13471                setMountPath(newMountPath);
13472                return PackageManager.INSTALL_SUCCEEDED;
13473            } else {
13474                return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
13475            }
13476        }
13477
13478        @Override
13479        String getCodePath() {
13480            return packagePath;
13481        }
13482
13483        @Override
13484        String getResourcePath() {
13485            return resourcePath;
13486        }
13487
13488        int doPreInstall(int status) {
13489            if (status != PackageManager.INSTALL_SUCCEEDED) {
13490                // Destroy container
13491                PackageHelper.destroySdDir(cid);
13492            } else {
13493                boolean mounted = PackageHelper.isContainerMounted(cid);
13494                if (!mounted) {
13495                    String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(),
13496                            Process.SYSTEM_UID);
13497                    if (newMountPath != null) {
13498                        setMountPath(newMountPath);
13499                    } else {
13500                        return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
13501                    }
13502                }
13503            }
13504            return status;
13505        }
13506
13507        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
13508            String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME);
13509            String newMountPath = null;
13510            if (PackageHelper.isContainerMounted(cid)) {
13511                // Unmount the container
13512                if (!PackageHelper.unMountSdDir(cid)) {
13513                    Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
13514                    return false;
13515                }
13516            }
13517            if (!PackageHelper.renameSdDir(cid, newCacheId)) {
13518                Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
13519                        " which might be stale. Will try to clean up.");
13520                // Clean up the stale container and proceed to recreate.
13521                if (!PackageHelper.destroySdDir(newCacheId)) {
13522                    Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
13523                    return false;
13524                }
13525                // Successfully cleaned up stale container. Try to rename again.
13526                if (!PackageHelper.renameSdDir(cid, newCacheId)) {
13527                    Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
13528                            + " inspite of cleaning it up.");
13529                    return false;
13530                }
13531            }
13532            if (!PackageHelper.isContainerMounted(newCacheId)) {
13533                Slog.w(TAG, "Mounting container " + newCacheId);
13534                newMountPath = PackageHelper.mountSdDir(newCacheId,
13535                        getEncryptKey(), Process.SYSTEM_UID);
13536            } else {
13537                newMountPath = PackageHelper.getSdDir(newCacheId);
13538            }
13539            if (newMountPath == null) {
13540                Slog.w(TAG, "Failed to get cache path for  " + newCacheId);
13541                return false;
13542            }
13543            Log.i(TAG, "Succesfully renamed " + cid +
13544                    " to " + newCacheId +
13545                    " at new path: " + newMountPath);
13546            cid = newCacheId;
13547
13548            final File beforeCodeFile = new File(packagePath);
13549            setMountPath(newMountPath);
13550            final File afterCodeFile = new File(packagePath);
13551
13552            // Reflect the rename in scanned details
13553            pkg.setCodePath(afterCodeFile.getAbsolutePath());
13554            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
13555                    afterCodeFile, pkg.baseCodePath));
13556            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
13557                    afterCodeFile, pkg.splitCodePaths));
13558
13559            // Reflect the rename in app info
13560            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
13561            pkg.setApplicationInfoCodePath(pkg.codePath);
13562            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
13563            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
13564            pkg.setApplicationInfoResourcePath(pkg.codePath);
13565            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
13566            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
13567
13568            return true;
13569        }
13570
13571        private void setMountPath(String mountPath) {
13572            final File mountFile = new File(mountPath);
13573
13574            final File monolithicFile = new File(mountFile, RES_FILE_NAME);
13575            if (monolithicFile.exists()) {
13576                packagePath = monolithicFile.getAbsolutePath();
13577                if (isFwdLocked()) {
13578                    resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath();
13579                } else {
13580                    resourcePath = packagePath;
13581                }
13582            } else {
13583                packagePath = mountFile.getAbsolutePath();
13584                resourcePath = packagePath;
13585            }
13586        }
13587
13588        int doPostInstall(int status, int uid) {
13589            if (status != PackageManager.INSTALL_SUCCEEDED) {
13590                cleanUp();
13591            } else {
13592                final int groupOwner;
13593                final String protectedFile;
13594                if (isFwdLocked()) {
13595                    groupOwner = UserHandle.getSharedAppGid(uid);
13596                    protectedFile = RES_FILE_NAME;
13597                } else {
13598                    groupOwner = -1;
13599                    protectedFile = null;
13600                }
13601
13602                if (uid < Process.FIRST_APPLICATION_UID
13603                        || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) {
13604                    Slog.e(TAG, "Failed to finalize " + cid);
13605                    PackageHelper.destroySdDir(cid);
13606                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
13607                }
13608
13609                boolean mounted = PackageHelper.isContainerMounted(cid);
13610                if (!mounted) {
13611                    PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid());
13612                }
13613            }
13614            return status;
13615        }
13616
13617        private void cleanUp() {
13618            if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp");
13619
13620            // Destroy secure container
13621            PackageHelper.destroySdDir(cid);
13622        }
13623
13624        private List<String> getAllCodePaths() {
13625            final File codeFile = new File(getCodePath());
13626            if (codeFile != null && codeFile.exists()) {
13627                try {
13628                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
13629                    return pkg.getAllCodePaths();
13630                } catch (PackageParserException e) {
13631                    // Ignored; we tried our best
13632                }
13633            }
13634            return Collections.EMPTY_LIST;
13635        }
13636
13637        void cleanUpResourcesLI() {
13638            // Enumerate all code paths before deleting
13639            cleanUpResourcesLI(getAllCodePaths());
13640        }
13641
13642        private void cleanUpResourcesLI(List<String> allCodePaths) {
13643            cleanUp();
13644            removeDexFiles(allCodePaths, instructionSets);
13645        }
13646
13647        String getPackageName() {
13648            return getAsecPackageName(cid);
13649        }
13650
13651        boolean doPostDeleteLI(boolean delete) {
13652            if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete);
13653            final List<String> allCodePaths = getAllCodePaths();
13654            boolean mounted = PackageHelper.isContainerMounted(cid);
13655            if (mounted) {
13656                // Unmount first
13657                if (PackageHelper.unMountSdDir(cid)) {
13658                    mounted = false;
13659                }
13660            }
13661            if (!mounted && delete) {
13662                cleanUpResourcesLI(allCodePaths);
13663            }
13664            return !mounted;
13665        }
13666
13667        @Override
13668        int doPreCopy() {
13669            if (isFwdLocked()) {
13670                if (!PackageHelper.fixSdPermissions(cid, getPackageUid(DEFAULT_CONTAINER_PACKAGE,
13671                        MATCH_SYSTEM_ONLY, UserHandle.USER_SYSTEM), RES_FILE_NAME)) {
13672                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
13673                }
13674            }
13675
13676            return PackageManager.INSTALL_SUCCEEDED;
13677        }
13678
13679        @Override
13680        int doPostCopy(int uid) {
13681            if (isFwdLocked()) {
13682                if (uid < Process.FIRST_APPLICATION_UID
13683                        || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid),
13684                                RES_FILE_NAME)) {
13685                    Slog.e(TAG, "Failed to finalize " + cid);
13686                    PackageHelper.destroySdDir(cid);
13687                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
13688                }
13689            }
13690
13691            return PackageManager.INSTALL_SUCCEEDED;
13692        }
13693    }
13694
13695    /**
13696     * Logic to handle movement of existing installed applications.
13697     */
13698    class MoveInstallArgs extends InstallArgs {
13699        private File codeFile;
13700        private File resourceFile;
13701
13702        /** New install */
13703        MoveInstallArgs(InstallParams params) {
13704            super(params.origin, params.move, params.observer, params.installFlags,
13705                    params.installerPackageName, params.volumeUuid,
13706                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
13707                    params.grantedRuntimePermissions,
13708                    params.traceMethod, params.traceCookie, params.certificates);
13709        }
13710
13711        int copyApk(IMediaContainerService imcs, boolean temp) {
13712            if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from "
13713                    + move.fromUuid + " to " + move.toUuid);
13714            synchronized (mInstaller) {
13715                try {
13716                    mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName,
13717                            move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion);
13718                } catch (InstallerException e) {
13719                    Slog.w(TAG, "Failed to move app", e);
13720                    return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
13721                }
13722            }
13723
13724            codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName);
13725            resourceFile = codeFile;
13726            if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile);
13727
13728            return PackageManager.INSTALL_SUCCEEDED;
13729        }
13730
13731        int doPreInstall(int status) {
13732            if (status != PackageManager.INSTALL_SUCCEEDED) {
13733                cleanUp(move.toUuid);
13734            }
13735            return status;
13736        }
13737
13738        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
13739            if (status != PackageManager.INSTALL_SUCCEEDED) {
13740                cleanUp(move.toUuid);
13741                return false;
13742            }
13743
13744            // Reflect the move in app info
13745            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
13746            pkg.setApplicationInfoCodePath(pkg.codePath);
13747            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
13748            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
13749            pkg.setApplicationInfoResourcePath(pkg.codePath);
13750            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
13751            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
13752
13753            return true;
13754        }
13755
13756        int doPostInstall(int status, int uid) {
13757            if (status == PackageManager.INSTALL_SUCCEEDED) {
13758                cleanUp(move.fromUuid);
13759            } else {
13760                cleanUp(move.toUuid);
13761            }
13762            return status;
13763        }
13764
13765        @Override
13766        String getCodePath() {
13767            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
13768        }
13769
13770        @Override
13771        String getResourcePath() {
13772            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
13773        }
13774
13775        private boolean cleanUp(String volumeUuid) {
13776            final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid),
13777                    move.dataAppName);
13778            Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid);
13779            final int[] userIds = sUserManager.getUserIds();
13780            synchronized (mInstallLock) {
13781                // Clean up both app data and code
13782                // All package moves are frozen until finished
13783                for (int userId : userIds) {
13784                    try {
13785                        mInstaller.destroyAppData(volumeUuid, move.packageName, userId,
13786                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 0);
13787                    } catch (InstallerException e) {
13788                        Slog.w(TAG, String.valueOf(e));
13789                    }
13790                }
13791                removeCodePathLI(codeFile);
13792            }
13793            return true;
13794        }
13795
13796        void cleanUpResourcesLI() {
13797            throw new UnsupportedOperationException();
13798        }
13799
13800        boolean doPostDeleteLI(boolean delete) {
13801            throw new UnsupportedOperationException();
13802        }
13803    }
13804
13805    static String getAsecPackageName(String packageCid) {
13806        int idx = packageCid.lastIndexOf("-");
13807        if (idx == -1) {
13808            return packageCid;
13809        }
13810        return packageCid.substring(0, idx);
13811    }
13812
13813    // Utility method used to create code paths based on package name and available index.
13814    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
13815        String idxStr = "";
13816        int idx = 1;
13817        // Fall back to default value of idx=1 if prefix is not
13818        // part of oldCodePath
13819        if (oldCodePath != null) {
13820            String subStr = oldCodePath;
13821            // Drop the suffix right away
13822            if (suffix != null && subStr.endsWith(suffix)) {
13823                subStr = subStr.substring(0, subStr.length() - suffix.length());
13824            }
13825            // If oldCodePath already contains prefix find out the
13826            // ending index to either increment or decrement.
13827            int sidx = subStr.lastIndexOf(prefix);
13828            if (sidx != -1) {
13829                subStr = subStr.substring(sidx + prefix.length());
13830                if (subStr != null) {
13831                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
13832                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
13833                    }
13834                    try {
13835                        idx = Integer.parseInt(subStr);
13836                        if (idx <= 1) {
13837                            idx++;
13838                        } else {
13839                            idx--;
13840                        }
13841                    } catch(NumberFormatException e) {
13842                    }
13843                }
13844            }
13845        }
13846        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
13847        return prefix + idxStr;
13848    }
13849
13850    private File getNextCodePath(File targetDir, String packageName) {
13851        int suffix = 1;
13852        File result;
13853        do {
13854            result = new File(targetDir, packageName + "-" + suffix);
13855            suffix++;
13856        } while (result.exists());
13857        return result;
13858    }
13859
13860    // Utility method that returns the relative package path with respect
13861    // to the installation directory. Like say for /data/data/com.test-1.apk
13862    // string com.test-1 is returned.
13863    static String deriveCodePathName(String codePath) {
13864        if (codePath == null) {
13865            return null;
13866        }
13867        final File codeFile = new File(codePath);
13868        final String name = codeFile.getName();
13869        if (codeFile.isDirectory()) {
13870            return name;
13871        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
13872            final int lastDot = name.lastIndexOf('.');
13873            return name.substring(0, lastDot);
13874        } else {
13875            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
13876            return null;
13877        }
13878    }
13879
13880    static class PackageInstalledInfo {
13881        String name;
13882        int uid;
13883        // The set of users that originally had this package installed.
13884        int[] origUsers;
13885        // The set of users that now have this package installed.
13886        int[] newUsers;
13887        PackageParser.Package pkg;
13888        int returnCode;
13889        String returnMsg;
13890        PackageRemovedInfo removedInfo;
13891        ArrayMap<String, PackageInstalledInfo> addedChildPackages;
13892
13893        public void setError(int code, String msg) {
13894            setReturnCode(code);
13895            setReturnMessage(msg);
13896            Slog.w(TAG, msg);
13897        }
13898
13899        public void setError(String msg, PackageParserException e) {
13900            setReturnCode(e.error);
13901            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
13902            Slog.w(TAG, msg, e);
13903        }
13904
13905        public void setError(String msg, PackageManagerException e) {
13906            returnCode = e.error;
13907            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
13908            Slog.w(TAG, msg, e);
13909        }
13910
13911        public void setReturnCode(int returnCode) {
13912            this.returnCode = returnCode;
13913            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
13914            for (int i = 0; i < childCount; i++) {
13915                addedChildPackages.valueAt(i).returnCode = returnCode;
13916            }
13917        }
13918
13919        private void setReturnMessage(String returnMsg) {
13920            this.returnMsg = returnMsg;
13921            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
13922            for (int i = 0; i < childCount; i++) {
13923                addedChildPackages.valueAt(i).returnMsg = returnMsg;
13924            }
13925        }
13926
13927        // In some error cases we want to convey more info back to the observer
13928        String origPackage;
13929        String origPermission;
13930    }
13931
13932    /*
13933     * Install a non-existing package.
13934     */
13935    private void installNewPackageLIF(PackageParser.Package pkg, final int policyFlags,
13936            int scanFlags, UserHandle user, String installerPackageName, String volumeUuid,
13937            PackageInstalledInfo res) {
13938        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage");
13939
13940        // Remember this for later, in case we need to rollback this install
13941        String pkgName = pkg.packageName;
13942
13943        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
13944
13945        synchronized(mPackages) {
13946            if (mSettings.mRenamedPackages.containsKey(pkgName)) {
13947                // A package with the same name is already installed, though
13948                // it has been renamed to an older name.  The package we
13949                // are trying to install should be installed as an update to
13950                // the existing one, but that has not been requested, so bail.
13951                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
13952                        + " without first uninstalling package running as "
13953                        + mSettings.mRenamedPackages.get(pkgName));
13954                return;
13955            }
13956            if (mPackages.containsKey(pkgName)) {
13957                // Don't allow installation over an existing package with the same name.
13958                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
13959                        + " without first uninstalling.");
13960                return;
13961            }
13962        }
13963
13964        try {
13965            PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags,
13966                    System.currentTimeMillis(), user);
13967
13968            updateSettingsLI(newPackage, installerPackageName, null, res, user);
13969
13970            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
13971                prepareAppDataAfterInstallLIF(newPackage);
13972
13973            } else {
13974                // Remove package from internal structures, but keep around any
13975                // data that might have already existed
13976                deletePackageLIF(pkgName, UserHandle.ALL, false, null,
13977                        PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null);
13978            }
13979        } catch (PackageManagerException e) {
13980            res.setError("Package couldn't be installed in " + pkg.codePath, e);
13981        }
13982
13983        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
13984    }
13985
13986    private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) {
13987        // Can't rotate keys during boot or if sharedUser.
13988        if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null
13989                || !oldPs.keySetData.isUsingUpgradeKeySets()) {
13990            return false;
13991        }
13992        // app is using upgradeKeySets; make sure all are valid
13993        KeySetManagerService ksms = mSettings.mKeySetManagerService;
13994        long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets();
13995        for (int i = 0; i < upgradeKeySets.length; i++) {
13996            if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) {
13997                Slog.wtf(TAG, "Package "
13998                         + (oldPs.name != null ? oldPs.name : "<null>")
13999                         + " contains upgrade-key-set reference to unknown key-set: "
14000                         + upgradeKeySets[i]
14001                         + " reverting to signatures check.");
14002                return false;
14003            }
14004        }
14005        return true;
14006    }
14007
14008    private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) {
14009        // Upgrade keysets are being used.  Determine if new package has a superset of the
14010        // required keys.
14011        long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets();
14012        KeySetManagerService ksms = mSettings.mKeySetManagerService;
14013        for (int i = 0; i < upgradeKeySets.length; i++) {
14014            Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]);
14015            if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) {
14016                return true;
14017            }
14018        }
14019        return false;
14020    }
14021
14022    private static void updateDigest(MessageDigest digest, File file) throws IOException {
14023        try (DigestInputStream digestStream =
14024                new DigestInputStream(new FileInputStream(file), digest)) {
14025            while (digestStream.read() != -1) {} // nothing to do; just plow through the file
14026        }
14027    }
14028
14029    private void replacePackageLIF(PackageParser.Package pkg, final int policyFlags, int scanFlags,
14030            UserHandle user, String installerPackageName, PackageInstalledInfo res) {
14031        final boolean isEphemeral = (policyFlags & PackageParser.PARSE_IS_EPHEMERAL) != 0;
14032
14033        final PackageParser.Package oldPackage;
14034        final String pkgName = pkg.packageName;
14035        final int[] allUsers;
14036        final int[] installedUsers;
14037
14038        synchronized(mPackages) {
14039            oldPackage = mPackages.get(pkgName);
14040            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
14041
14042            // don't allow upgrade to target a release SDK from a pre-release SDK
14043            final boolean oldTargetsPreRelease = oldPackage.applicationInfo.targetSdkVersion
14044                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
14045            final boolean newTargetsPreRelease = pkg.applicationInfo.targetSdkVersion
14046                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
14047            if (oldTargetsPreRelease
14048                    && !newTargetsPreRelease
14049                    && ((policyFlags & PackageParser.PARSE_FORCE_SDK) == 0)) {
14050                Slog.w(TAG, "Can't install package targeting released sdk");
14051                res.setReturnCode(PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE);
14052                return;
14053            }
14054
14055            // don't allow an upgrade from full to ephemeral
14056            final boolean oldIsEphemeral = oldPackage.applicationInfo.isEphemeralApp();
14057            if (isEphemeral && !oldIsEphemeral) {
14058                // can't downgrade from full to ephemeral
14059                Slog.w(TAG, "Can't replace app with ephemeral: " + pkgName);
14060                res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID);
14061                return;
14062            }
14063
14064            // verify signatures are valid
14065            final PackageSetting ps = mSettings.mPackages.get(pkgName);
14066            if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
14067                if (!checkUpgradeKeySetLP(ps, pkg)) {
14068                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
14069                            "New package not signed by keys specified by upgrade-keysets: "
14070                                    + pkgName);
14071                    return;
14072                }
14073            } else {
14074                // default to original signature matching
14075                if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
14076                        != PackageManager.SIGNATURE_MATCH) {
14077                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
14078                            "New package has a different signature: " + pkgName);
14079                    return;
14080                }
14081            }
14082
14083            // don't allow a system upgrade unless the upgrade hash matches
14084            if (oldPackage.restrictUpdateHash != null && oldPackage.isSystemApp()) {
14085                byte[] digestBytes = null;
14086                try {
14087                    final MessageDigest digest = MessageDigest.getInstance("SHA-512");
14088                    updateDigest(digest, new File(pkg.baseCodePath));
14089                    if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
14090                        for (String path : pkg.splitCodePaths) {
14091                            updateDigest(digest, new File(path));
14092                        }
14093                    }
14094                    digestBytes = digest.digest();
14095                } catch (NoSuchAlgorithmException | IOException e) {
14096                    res.setError(INSTALL_FAILED_INVALID_APK,
14097                            "Could not compute hash: " + pkgName);
14098                    return;
14099                }
14100                if (!Arrays.equals(oldPackage.restrictUpdateHash, digestBytes)) {
14101                    res.setError(INSTALL_FAILED_INVALID_APK,
14102                            "New package fails restrict-update check: " + pkgName);
14103                    return;
14104                }
14105                // retain upgrade restriction
14106                pkg.restrictUpdateHash = oldPackage.restrictUpdateHash;
14107            }
14108
14109            // Check for shared user id changes
14110            String invalidPackageName =
14111                    getParentOrChildPackageChangedSharedUser(oldPackage, pkg);
14112            if (invalidPackageName != null) {
14113                res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
14114                        "Package " + invalidPackageName + " tried to change user "
14115                                + oldPackage.mSharedUserId);
14116                return;
14117            }
14118
14119            // In case of rollback, remember per-user/profile install state
14120            allUsers = sUserManager.getUserIds();
14121            installedUsers = ps.queryInstalledUsers(allUsers, true);
14122        }
14123
14124        // Update what is removed
14125        res.removedInfo = new PackageRemovedInfo();
14126        res.removedInfo.uid = oldPackage.applicationInfo.uid;
14127        res.removedInfo.removedPackage = oldPackage.packageName;
14128        res.removedInfo.isUpdate = true;
14129        res.removedInfo.origUsers = installedUsers;
14130        final int childCount = (oldPackage.childPackages != null)
14131                ? oldPackage.childPackages.size() : 0;
14132        for (int i = 0; i < childCount; i++) {
14133            boolean childPackageUpdated = false;
14134            PackageParser.Package childPkg = oldPackage.childPackages.get(i);
14135            if (res.addedChildPackages != null) {
14136                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
14137                if (childRes != null) {
14138                    childRes.removedInfo.uid = childPkg.applicationInfo.uid;
14139                    childRes.removedInfo.removedPackage = childPkg.packageName;
14140                    childRes.removedInfo.isUpdate = true;
14141                    childPackageUpdated = true;
14142                }
14143            }
14144            if (!childPackageUpdated) {
14145                PackageRemovedInfo childRemovedRes = new PackageRemovedInfo();
14146                childRemovedRes.removedPackage = childPkg.packageName;
14147                childRemovedRes.isUpdate = false;
14148                childRemovedRes.dataRemoved = true;
14149                synchronized (mPackages) {
14150                    PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName);
14151                    if (childPs != null) {
14152                        childRemovedRes.origUsers = childPs.queryInstalledUsers(allUsers, true);
14153                    }
14154                }
14155                if (res.removedInfo.removedChildPackages == null) {
14156                    res.removedInfo.removedChildPackages = new ArrayMap<>();
14157                }
14158                res.removedInfo.removedChildPackages.put(childPkg.packageName, childRemovedRes);
14159            }
14160        }
14161
14162        boolean sysPkg = (isSystemApp(oldPackage));
14163        if (sysPkg) {
14164            // Set the system/privileged flags as needed
14165            final boolean privileged =
14166                    (oldPackage.applicationInfo.privateFlags
14167                            & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
14168            final int systemPolicyFlags = policyFlags
14169                    | PackageParser.PARSE_IS_SYSTEM
14170                    | (privileged ? PackageParser.PARSE_IS_PRIVILEGED : 0);
14171
14172            replaceSystemPackageLIF(oldPackage, pkg, systemPolicyFlags, scanFlags,
14173                    user, allUsers, installerPackageName, res);
14174        } else {
14175            replaceNonSystemPackageLIF(oldPackage, pkg, policyFlags, scanFlags,
14176                    user, allUsers, installerPackageName, res);
14177        }
14178    }
14179
14180    public List<String> getPreviousCodePaths(String packageName) {
14181        final PackageSetting ps = mSettings.mPackages.get(packageName);
14182        final List<String> result = new ArrayList<String>();
14183        if (ps != null && ps.oldCodePaths != null) {
14184            result.addAll(ps.oldCodePaths);
14185        }
14186        return result;
14187    }
14188
14189    private void replaceNonSystemPackageLIF(PackageParser.Package deletedPackage,
14190            PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user,
14191            int[] allUsers, String installerPackageName, PackageInstalledInfo res) {
14192        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
14193                + deletedPackage);
14194
14195        String pkgName = deletedPackage.packageName;
14196        boolean deletedPkg = true;
14197        boolean addedPkg = false;
14198        boolean updatedSettings = false;
14199        final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0;
14200        final int deleteFlags = PackageManager.DELETE_KEEP_DATA
14201                | (killApp ? 0 : PackageManager.DELETE_DONT_KILL_APP);
14202
14203        final long origUpdateTime = (pkg.mExtras != null)
14204                ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0;
14205
14206        // First delete the existing package while retaining the data directory
14207        if (!deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
14208                res.removedInfo, true, pkg)) {
14209            // If the existing package wasn't successfully deleted
14210            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
14211            deletedPkg = false;
14212        } else {
14213            // Successfully deleted the old package; proceed with replace.
14214
14215            // If deleted package lived in a container, give users a chance to
14216            // relinquish resources before killing.
14217            if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) {
14218                if (DEBUG_INSTALL) {
14219                    Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
14220                }
14221                final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
14222                final ArrayList<String> pkgList = new ArrayList<String>(1);
14223                pkgList.add(deletedPackage.applicationInfo.packageName);
14224                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
14225            }
14226
14227            clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
14228                    | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
14229            clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL);
14230
14231            try {
14232                final PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags,
14233                        scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
14234                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user);
14235
14236                // Update the in-memory copy of the previous code paths.
14237                PackageSetting ps = mSettings.mPackages.get(pkgName);
14238                if (!killApp) {
14239                    if (ps.oldCodePaths == null) {
14240                        ps.oldCodePaths = new ArraySet<>();
14241                    }
14242                    Collections.addAll(ps.oldCodePaths, deletedPackage.baseCodePath);
14243                    if (deletedPackage.splitCodePaths != null) {
14244                        Collections.addAll(ps.oldCodePaths, deletedPackage.splitCodePaths);
14245                    }
14246                } else {
14247                    ps.oldCodePaths = null;
14248                }
14249                if (ps.childPackageNames != null) {
14250                    for (int i = ps.childPackageNames.size() - 1; i >= 0; --i) {
14251                        final String childPkgName = ps.childPackageNames.get(i);
14252                        final PackageSetting childPs = mSettings.mPackages.get(childPkgName);
14253                        childPs.oldCodePaths = ps.oldCodePaths;
14254                    }
14255                }
14256                prepareAppDataAfterInstallLIF(newPackage);
14257                addedPkg = true;
14258            } catch (PackageManagerException e) {
14259                res.setError("Package couldn't be installed in " + pkg.codePath, e);
14260            }
14261        }
14262
14263        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
14264            if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
14265
14266            // Revert all internal state mutations and added folders for the failed install
14267            if (addedPkg) {
14268                deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
14269                        res.removedInfo, true, null);
14270            }
14271
14272            // Restore the old package
14273            if (deletedPkg) {
14274                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
14275                File restoreFile = new File(deletedPackage.codePath);
14276                // Parse old package
14277                boolean oldExternal = isExternal(deletedPackage);
14278                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
14279                        (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) |
14280                        (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
14281                int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
14282                try {
14283                    scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime,
14284                            null);
14285                } catch (PackageManagerException e) {
14286                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
14287                            + e.getMessage());
14288                    return;
14289                }
14290
14291                synchronized (mPackages) {
14292                    // Ensure the installer package name up to date
14293                    setInstallerPackageNameLPw(deletedPackage, installerPackageName);
14294
14295                    // Update permissions for restored package
14296                    updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
14297
14298                    mSettings.writeLPr();
14299                }
14300
14301                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
14302            }
14303        } else {
14304            synchronized (mPackages) {
14305                PackageSetting ps = mSettings.peekPackageLPr(pkg.packageName);
14306                if (ps != null) {
14307                    res.removedInfo.removedForAllUsers = mPackages.get(ps.name) == null;
14308                    if (res.removedInfo.removedChildPackages != null) {
14309                        final int childCount = res.removedInfo.removedChildPackages.size();
14310                        // Iterate in reverse as we may modify the collection
14311                        for (int i = childCount - 1; i >= 0; i--) {
14312                            String childPackageName = res.removedInfo.removedChildPackages.keyAt(i);
14313                            if (res.addedChildPackages.containsKey(childPackageName)) {
14314                                res.removedInfo.removedChildPackages.removeAt(i);
14315                            } else {
14316                                PackageRemovedInfo childInfo = res.removedInfo
14317                                        .removedChildPackages.valueAt(i);
14318                                childInfo.removedForAllUsers = mPackages.get(
14319                                        childInfo.removedPackage) == null;
14320                            }
14321                        }
14322                    }
14323                }
14324            }
14325        }
14326    }
14327
14328    private void replaceSystemPackageLIF(PackageParser.Package deletedPackage,
14329            PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user,
14330            int[] allUsers, String installerPackageName, PackageInstalledInfo res) {
14331        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
14332                + ", old=" + deletedPackage);
14333
14334        final boolean disabledSystem;
14335
14336        // Remove existing system package
14337        removePackageLI(deletedPackage, true);
14338
14339        synchronized (mPackages) {
14340            disabledSystem = disableSystemPackageLPw(deletedPackage, pkg);
14341        }
14342        if (!disabledSystem) {
14343            // We didn't need to disable the .apk as a current system package,
14344            // which means we are replacing another update that is already
14345            // installed.  We need to make sure to delete the older one's .apk.
14346            res.removedInfo.args = createInstallArgsForExisting(0,
14347                    deletedPackage.applicationInfo.getCodePath(),
14348                    deletedPackage.applicationInfo.getResourcePath(),
14349                    getAppDexInstructionSets(deletedPackage.applicationInfo));
14350        } else {
14351            res.removedInfo.args = null;
14352        }
14353
14354        // Successfully disabled the old package. Now proceed with re-installation
14355        clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
14356                | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
14357        clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL);
14358
14359        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
14360        pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP,
14361                ApplicationInfo.FLAG_UPDATED_SYSTEM_APP);
14362
14363        PackageParser.Package newPackage = null;
14364        try {
14365            // Add the package to the internal data structures
14366            newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags, 0, user);
14367
14368            // Set the update and install times
14369            PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras;
14370            setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime,
14371                    System.currentTimeMillis());
14372
14373            // Update the package dynamic state if succeeded
14374            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
14375                // Now that the install succeeded make sure we remove data
14376                // directories for any child package the update removed.
14377                final int deletedChildCount = (deletedPackage.childPackages != null)
14378                        ? deletedPackage.childPackages.size() : 0;
14379                final int newChildCount = (newPackage.childPackages != null)
14380                        ? newPackage.childPackages.size() : 0;
14381                for (int i = 0; i < deletedChildCount; i++) {
14382                    PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i);
14383                    boolean childPackageDeleted = true;
14384                    for (int j = 0; j < newChildCount; j++) {
14385                        PackageParser.Package newChildPkg = newPackage.childPackages.get(j);
14386                        if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) {
14387                            childPackageDeleted = false;
14388                            break;
14389                        }
14390                    }
14391                    if (childPackageDeleted) {
14392                        PackageSetting ps = mSettings.getDisabledSystemPkgLPr(
14393                                deletedChildPkg.packageName);
14394                        if (ps != null && res.removedInfo.removedChildPackages != null) {
14395                            PackageRemovedInfo removedChildRes = res.removedInfo
14396                                    .removedChildPackages.get(deletedChildPkg.packageName);
14397                            removePackageDataLIF(ps, allUsers, removedChildRes, 0, false);
14398                            removedChildRes.removedForAllUsers = mPackages.get(ps.name) == null;
14399                        }
14400                    }
14401                }
14402
14403                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user);
14404                prepareAppDataAfterInstallLIF(newPackage);
14405            }
14406        } catch (PackageManagerException e) {
14407            res.setReturnCode(INSTALL_FAILED_INTERNAL_ERROR);
14408            res.setError("Package couldn't be installed in " + pkg.codePath, e);
14409        }
14410
14411        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
14412            // Re installation failed. Restore old information
14413            // Remove new pkg information
14414            if (newPackage != null) {
14415                removeInstalledPackageLI(newPackage, true);
14416            }
14417            // Add back the old system package
14418            try {
14419                scanPackageTracedLI(deletedPackage, policyFlags, SCAN_UPDATE_SIGNATURE, 0, user);
14420            } catch (PackageManagerException e) {
14421                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
14422            }
14423
14424            synchronized (mPackages) {
14425                if (disabledSystem) {
14426                    enableSystemPackageLPw(deletedPackage);
14427                }
14428
14429                // Ensure the installer package name up to date
14430                setInstallerPackageNameLPw(deletedPackage, installerPackageName);
14431
14432                // Update permissions for restored package
14433                updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
14434
14435                mSettings.writeLPr();
14436            }
14437
14438            Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName
14439                    + " after failed upgrade");
14440        }
14441    }
14442
14443    /**
14444     * Checks whether the parent or any of the child packages have a change shared
14445     * user. For a package to be a valid update the shred users of the parent and
14446     * the children should match. We may later support changing child shared users.
14447     * @param oldPkg The updated package.
14448     * @param newPkg The update package.
14449     * @return The shared user that change between the versions.
14450     */
14451    private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg,
14452            PackageParser.Package newPkg) {
14453        // Check parent shared user
14454        if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) {
14455            return newPkg.packageName;
14456        }
14457        // Check child shared users
14458        final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
14459        final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0;
14460        for (int i = 0; i < newChildCount; i++) {
14461            PackageParser.Package newChildPkg = newPkg.childPackages.get(i);
14462            // If this child was present, did it have the same shared user?
14463            for (int j = 0; j < oldChildCount; j++) {
14464                PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j);
14465                if (newChildPkg.packageName.equals(oldChildPkg.packageName)
14466                        && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) {
14467                    return newChildPkg.packageName;
14468                }
14469            }
14470        }
14471        return null;
14472    }
14473
14474    private void removeNativeBinariesLI(PackageSetting ps) {
14475        // Remove the lib path for the parent package
14476        if (ps != null) {
14477            NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString);
14478            // Remove the lib path for the child packages
14479            final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
14480            for (int i = 0; i < childCount; i++) {
14481                PackageSetting childPs = null;
14482                synchronized (mPackages) {
14483                    childPs = mSettings.peekPackageLPr(ps.childPackageNames.get(i));
14484                }
14485                if (childPs != null) {
14486                    NativeLibraryHelper.removeNativeBinariesLI(childPs
14487                            .legacyNativeLibraryPathString);
14488                }
14489            }
14490        }
14491    }
14492
14493    private void enableSystemPackageLPw(PackageParser.Package pkg) {
14494        // Enable the parent package
14495        mSettings.enableSystemPackageLPw(pkg.packageName);
14496        // Enable the child packages
14497        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
14498        for (int i = 0; i < childCount; i++) {
14499            PackageParser.Package childPkg = pkg.childPackages.get(i);
14500            mSettings.enableSystemPackageLPw(childPkg.packageName);
14501        }
14502    }
14503
14504    private boolean disableSystemPackageLPw(PackageParser.Package oldPkg,
14505            PackageParser.Package newPkg) {
14506        // Disable the parent package (parent always replaced)
14507        boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true);
14508        // Disable the child packages
14509        final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
14510        for (int i = 0; i < childCount; i++) {
14511            PackageParser.Package childPkg = oldPkg.childPackages.get(i);
14512            final boolean replace = newPkg.hasChildPackage(childPkg.packageName);
14513            disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace);
14514        }
14515        return disabled;
14516    }
14517
14518    private void setInstallerPackageNameLPw(PackageParser.Package pkg,
14519            String installerPackageName) {
14520        // Enable the parent package
14521        mSettings.setInstallerPackageName(pkg.packageName, installerPackageName);
14522        // Enable the child packages
14523        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
14524        for (int i = 0; i < childCount; i++) {
14525            PackageParser.Package childPkg = pkg.childPackages.get(i);
14526            mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName);
14527        }
14528    }
14529
14530    private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) {
14531        // Collect all used permissions in the UID
14532        ArraySet<String> usedPermissions = new ArraySet<>();
14533        final int packageCount = su.packages.size();
14534        for (int i = 0; i < packageCount; i++) {
14535            PackageSetting ps = su.packages.valueAt(i);
14536            if (ps.pkg == null) {
14537                continue;
14538            }
14539            final int requestedPermCount = ps.pkg.requestedPermissions.size();
14540            for (int j = 0; j < requestedPermCount; j++) {
14541                String permission = ps.pkg.requestedPermissions.get(j);
14542                BasePermission bp = mSettings.mPermissions.get(permission);
14543                if (bp != null) {
14544                    usedPermissions.add(permission);
14545                }
14546            }
14547        }
14548
14549        PermissionsState permissionsState = su.getPermissionsState();
14550        // Prune install permissions
14551        List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates();
14552        final int installPermCount = installPermStates.size();
14553        for (int i = installPermCount - 1; i >= 0;  i--) {
14554            PermissionState permissionState = installPermStates.get(i);
14555            if (!usedPermissions.contains(permissionState.getName())) {
14556                BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
14557                if (bp != null) {
14558                    permissionsState.revokeInstallPermission(bp);
14559                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
14560                            PackageManager.MASK_PERMISSION_FLAGS, 0);
14561                }
14562            }
14563        }
14564
14565        int[] runtimePermissionChangedUserIds = EmptyArray.INT;
14566
14567        // Prune runtime permissions
14568        for (int userId : allUserIds) {
14569            List<PermissionState> runtimePermStates = permissionsState
14570                    .getRuntimePermissionStates(userId);
14571            final int runtimePermCount = runtimePermStates.size();
14572            for (int i = runtimePermCount - 1; i >= 0; i--) {
14573                PermissionState permissionState = runtimePermStates.get(i);
14574                if (!usedPermissions.contains(permissionState.getName())) {
14575                    BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
14576                    if (bp != null) {
14577                        permissionsState.revokeRuntimePermission(bp, userId);
14578                        permissionsState.updatePermissionFlags(bp, userId,
14579                                PackageManager.MASK_PERMISSION_FLAGS, 0);
14580                        runtimePermissionChangedUserIds = ArrayUtils.appendInt(
14581                                runtimePermissionChangedUserIds, userId);
14582                    }
14583                }
14584            }
14585        }
14586
14587        return runtimePermissionChangedUserIds;
14588    }
14589
14590    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
14591            int[] allUsers, PackageInstalledInfo res, UserHandle user) {
14592        // Update the parent package setting
14593        updateSettingsInternalLI(newPackage, installerPackageName, allUsers, res.origUsers,
14594                res, user);
14595        // Update the child packages setting
14596        final int childCount = (newPackage.childPackages != null)
14597                ? newPackage.childPackages.size() : 0;
14598        for (int i = 0; i < childCount; i++) {
14599            PackageParser.Package childPackage = newPackage.childPackages.get(i);
14600            PackageInstalledInfo childRes = res.addedChildPackages.get(childPackage.packageName);
14601            updateSettingsInternalLI(childPackage, installerPackageName, allUsers,
14602                    childRes.origUsers, childRes, user);
14603        }
14604    }
14605
14606    private void updateSettingsInternalLI(PackageParser.Package newPackage,
14607            String installerPackageName, int[] allUsers, int[] installedForUsers,
14608            PackageInstalledInfo res, UserHandle user) {
14609        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
14610
14611        String pkgName = newPackage.packageName;
14612        synchronized (mPackages) {
14613            //write settings. the installStatus will be incomplete at this stage.
14614            //note that the new package setting would have already been
14615            //added to mPackages. It hasn't been persisted yet.
14616            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
14617            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
14618            mSettings.writeLPr();
14619            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
14620        }
14621
14622        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath);
14623        synchronized (mPackages) {
14624            updatePermissionsLPw(newPackage.packageName, newPackage,
14625                    UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
14626                            ? UPDATE_PERMISSIONS_ALL : 0));
14627            // For system-bundled packages, we assume that installing an upgraded version
14628            // of the package implies that the user actually wants to run that new code,
14629            // so we enable the package.
14630            PackageSetting ps = mSettings.mPackages.get(pkgName);
14631            final int userId = user.getIdentifier();
14632            if (ps != null) {
14633                if (isSystemApp(newPackage)) {
14634                    if (DEBUG_INSTALL) {
14635                        Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
14636                    }
14637                    // Enable system package for requested users
14638                    if (res.origUsers != null) {
14639                        for (int origUserId : res.origUsers) {
14640                            if (userId == UserHandle.USER_ALL || userId == origUserId) {
14641                                ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
14642                                        origUserId, installerPackageName);
14643                            }
14644                        }
14645                    }
14646                    // Also convey the prior install/uninstall state
14647                    if (allUsers != null && installedForUsers != null) {
14648                        for (int currentUserId : allUsers) {
14649                            final boolean installed = ArrayUtils.contains(
14650                                    installedForUsers, currentUserId);
14651                            if (DEBUG_INSTALL) {
14652                                Slog.d(TAG, "    user " + currentUserId + " => " + installed);
14653                            }
14654                            ps.setInstalled(installed, currentUserId);
14655                        }
14656                        // these install state changes will be persisted in the
14657                        // upcoming call to mSettings.writeLPr().
14658                    }
14659                }
14660                // It's implied that when a user requests installation, they want the app to be
14661                // installed and enabled.
14662                if (userId != UserHandle.USER_ALL) {
14663                    ps.setInstalled(true, userId);
14664                    ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName);
14665                }
14666            }
14667            res.name = pkgName;
14668            res.uid = newPackage.applicationInfo.uid;
14669            res.pkg = newPackage;
14670            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
14671            mSettings.setInstallerPackageName(pkgName, installerPackageName);
14672            res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
14673            //to update install status
14674            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
14675            mSettings.writeLPr();
14676            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
14677        }
14678
14679        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
14680    }
14681
14682    private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) {
14683        try {
14684            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage");
14685            installPackageLI(args, res);
14686        } finally {
14687            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
14688        }
14689    }
14690
14691    private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
14692        final int installFlags = args.installFlags;
14693        final String installerPackageName = args.installerPackageName;
14694        final String volumeUuid = args.volumeUuid;
14695        final File tmpPackageFile = new File(args.getCodePath());
14696        final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
14697        final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0)
14698                || (args.volumeUuid != null));
14699        final boolean ephemeral = ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0);
14700        final boolean forceSdk = ((installFlags & PackageManager.INSTALL_FORCE_SDK) != 0);
14701        boolean replace = false;
14702        int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE;
14703        if (args.move != null) {
14704            // moving a complete application; perform an initial scan on the new install location
14705            scanFlags |= SCAN_INITIAL;
14706        }
14707        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
14708            scanFlags |= SCAN_DONT_KILL_APP;
14709        }
14710
14711        // Result object to be returned
14712        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
14713
14714        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
14715
14716        // Sanity check
14717        if (ephemeral && (forwardLocked || onExternal)) {
14718            Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked
14719                    + " external=" + onExternal);
14720            res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID);
14721            return;
14722        }
14723
14724        // Retrieve PackageSettings and parse package
14725        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
14726                | PackageParser.PARSE_ENFORCE_CODE
14727                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
14728                | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0)
14729                | (ephemeral ? PackageParser.PARSE_IS_EPHEMERAL : 0)
14730                | (forceSdk ? PackageParser.PARSE_FORCE_SDK : 0);
14731        PackageParser pp = new PackageParser();
14732        pp.setSeparateProcesses(mSeparateProcesses);
14733        pp.setDisplayMetrics(mMetrics);
14734
14735        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
14736        final PackageParser.Package pkg;
14737        try {
14738            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
14739        } catch (PackageParserException e) {
14740            res.setError("Failed parse during installPackageLI", e);
14741            return;
14742        } finally {
14743            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
14744        }
14745
14746        // If we are installing a clustered package add results for the children
14747        if (pkg.childPackages != null) {
14748            synchronized (mPackages) {
14749                final int childCount = pkg.childPackages.size();
14750                for (int i = 0; i < childCount; i++) {
14751                    PackageParser.Package childPkg = pkg.childPackages.get(i);
14752                    PackageInstalledInfo childRes = new PackageInstalledInfo();
14753                    childRes.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
14754                    childRes.pkg = childPkg;
14755                    childRes.name = childPkg.packageName;
14756                    PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName);
14757                    if (childPs != null) {
14758                        childRes.origUsers = childPs.queryInstalledUsers(
14759                                sUserManager.getUserIds(), true);
14760                    }
14761                    if ((mPackages.containsKey(childPkg.packageName))) {
14762                        childRes.removedInfo = new PackageRemovedInfo();
14763                        childRes.removedInfo.removedPackage = childPkg.packageName;
14764                    }
14765                    if (res.addedChildPackages == null) {
14766                        res.addedChildPackages = new ArrayMap<>();
14767                    }
14768                    res.addedChildPackages.put(childPkg.packageName, childRes);
14769                }
14770            }
14771        }
14772
14773        // If package doesn't declare API override, mark that we have an install
14774        // time CPU ABI override.
14775        if (TextUtils.isEmpty(pkg.cpuAbiOverride)) {
14776            pkg.cpuAbiOverride = args.abiOverride;
14777        }
14778
14779        String pkgName = res.name = pkg.packageName;
14780        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
14781            if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
14782                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
14783                return;
14784            }
14785        }
14786
14787        try {
14788            // either use what we've been given or parse directly from the APK
14789            if (args.certificates != null) {
14790                try {
14791                    PackageParser.populateCertificates(pkg, args.certificates);
14792                } catch (PackageParserException e) {
14793                    // there was something wrong with the certificates we were given;
14794                    // try to pull them from the APK
14795                    PackageParser.collectCertificates(pkg, parseFlags);
14796                }
14797            } else {
14798                PackageParser.collectCertificates(pkg, parseFlags);
14799            }
14800        } catch (PackageParserException e) {
14801            res.setError("Failed collect during installPackageLI", e);
14802            return;
14803        }
14804
14805        // Get rid of all references to package scan path via parser.
14806        pp = null;
14807        String oldCodePath = null;
14808        boolean systemApp = false;
14809        synchronized (mPackages) {
14810            // Check if installing already existing package
14811            if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
14812                String oldName = mSettings.mRenamedPackages.get(pkgName);
14813                if (pkg.mOriginalPackages != null
14814                        && pkg.mOriginalPackages.contains(oldName)
14815                        && mPackages.containsKey(oldName)) {
14816                    // This package is derived from an original package,
14817                    // and this device has been updating from that original
14818                    // name.  We must continue using the original name, so
14819                    // rename the new package here.
14820                    pkg.setPackageName(oldName);
14821                    pkgName = pkg.packageName;
14822                    replace = true;
14823                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
14824                            + oldName + " pkgName=" + pkgName);
14825                } else if (mPackages.containsKey(pkgName)) {
14826                    // This package, under its official name, already exists
14827                    // on the device; we should replace it.
14828                    replace = true;
14829                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
14830                }
14831
14832                // Child packages are installed through the parent package
14833                if (pkg.parentPackage != null) {
14834                    res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
14835                            "Package " + pkg.packageName + " is child of package "
14836                                    + pkg.parentPackage.parentPackage + ". Child packages "
14837                                    + "can be updated only through the parent package.");
14838                    return;
14839                }
14840
14841                if (replace) {
14842                    // Prevent apps opting out from runtime permissions
14843                    PackageParser.Package oldPackage = mPackages.get(pkgName);
14844                    final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion;
14845                    final int newTargetSdk = pkg.applicationInfo.targetSdkVersion;
14846                    if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1
14847                            && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) {
14848                        res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE,
14849                                "Package " + pkg.packageName + " new target SDK " + newTargetSdk
14850                                        + " doesn't support runtime permissions but the old"
14851                                        + " target SDK " + oldTargetSdk + " does.");
14852                        return;
14853                    }
14854
14855                    // Prevent installing of child packages
14856                    if (oldPackage.parentPackage != null) {
14857                        res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
14858                                "Package " + pkg.packageName + " is child of package "
14859                                        + oldPackage.parentPackage + ". Child packages "
14860                                        + "can be updated only through the parent package.");
14861                        return;
14862                    }
14863                }
14864            }
14865
14866            PackageSetting ps = mSettings.mPackages.get(pkgName);
14867            if (ps != null) {
14868                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
14869
14870                // Quick sanity check that we're signed correctly if updating;
14871                // we'll check this again later when scanning, but we want to
14872                // bail early here before tripping over redefined permissions.
14873                if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
14874                    if (!checkUpgradeKeySetLP(ps, pkg)) {
14875                        res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
14876                                + pkg.packageName + " upgrade keys do not match the "
14877                                + "previously installed version");
14878                        return;
14879                    }
14880                } else {
14881                    try {
14882                        verifySignaturesLP(ps, pkg);
14883                    } catch (PackageManagerException e) {
14884                        res.setError(e.error, e.getMessage());
14885                        return;
14886                    }
14887                }
14888
14889                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
14890                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
14891                    systemApp = (ps.pkg.applicationInfo.flags &
14892                            ApplicationInfo.FLAG_SYSTEM) != 0;
14893                }
14894                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
14895            }
14896
14897            // Check whether the newly-scanned package wants to define an already-defined perm
14898            int N = pkg.permissions.size();
14899            for (int i = N-1; i >= 0; i--) {
14900                PackageParser.Permission perm = pkg.permissions.get(i);
14901                BasePermission bp = mSettings.mPermissions.get(perm.info.name);
14902                if (bp != null) {
14903                    // If the defining package is signed with our cert, it's okay.  This
14904                    // also includes the "updating the same package" case, of course.
14905                    // "updating same package" could also involve key-rotation.
14906                    final boolean sigsOk;
14907                    if (bp.sourcePackage.equals(pkg.packageName)
14908                            && (bp.packageSetting instanceof PackageSetting)
14909                            && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting,
14910                                    scanFlags))) {
14911                        sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg);
14912                    } else {
14913                        sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures,
14914                                pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
14915                    }
14916                    if (!sigsOk) {
14917                        // If the owning package is the system itself, we log but allow
14918                        // install to proceed; we fail the install on all other permission
14919                        // redefinitions.
14920                        if (!bp.sourcePackage.equals("android")) {
14921                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
14922                                    + pkg.packageName + " attempting to redeclare permission "
14923                                    + perm.info.name + " already owned by " + bp.sourcePackage);
14924                            res.origPermission = perm.info.name;
14925                            res.origPackage = bp.sourcePackage;
14926                            return;
14927                        } else {
14928                            Slog.w(TAG, "Package " + pkg.packageName
14929                                    + " attempting to redeclare system permission "
14930                                    + perm.info.name + "; ignoring new declaration");
14931                            pkg.permissions.remove(i);
14932                        }
14933                    }
14934                }
14935            }
14936        }
14937
14938        if (systemApp) {
14939            if (onExternal) {
14940                // Abort update; system app can't be replaced with app on sdcard
14941                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
14942                        "Cannot install updates to system apps on sdcard");
14943                return;
14944            } else if (ephemeral) {
14945                // Abort update; system app can't be replaced with an ephemeral app
14946                res.setError(INSTALL_FAILED_EPHEMERAL_INVALID,
14947                        "Cannot update a system app with an ephemeral app");
14948                return;
14949            }
14950        }
14951
14952        if (args.move != null) {
14953            // We did an in-place move, so dex is ready to roll
14954            scanFlags |= SCAN_NO_DEX;
14955            scanFlags |= SCAN_MOVE;
14956
14957            synchronized (mPackages) {
14958                final PackageSetting ps = mSettings.mPackages.get(pkgName);
14959                if (ps == null) {
14960                    res.setError(INSTALL_FAILED_INTERNAL_ERROR,
14961                            "Missing settings for moved package " + pkgName);
14962                }
14963
14964                // We moved the entire application as-is, so bring over the
14965                // previously derived ABI information.
14966                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
14967                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
14968            }
14969
14970        } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) {
14971            // Enable SCAN_NO_DEX flag to skip dexopt at a later stage
14972            scanFlags |= SCAN_NO_DEX;
14973
14974            try {
14975                String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ?
14976                    args.abiOverride : pkg.cpuAbiOverride);
14977                derivePackageAbi(pkg, new File(pkg.codePath), abiOverride,
14978                        true /* extract libs */);
14979            } catch (PackageManagerException pme) {
14980                Slog.e(TAG, "Error deriving application ABI", pme);
14981                res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI");
14982                return;
14983            }
14984
14985            // Shared libraries for the package need to be updated.
14986            synchronized (mPackages) {
14987                try {
14988                    updateSharedLibrariesLPw(pkg, null);
14989                } catch (PackageManagerException e) {
14990                    Slog.e(TAG, "updateSharedLibrariesLPw failed: " + e.getMessage());
14991                }
14992            }
14993            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
14994            // Do not run PackageDexOptimizer through the local performDexOpt
14995            // method because `pkg` may not be in `mPackages` yet.
14996            //
14997            // Also, don't fail application installs if the dexopt step fails.
14998            mPackageDexOptimizer.performDexOpt(pkg, pkg.usesLibraryFiles,
14999                    null /* instructionSets */, false /* checkProfiles */,
15000                    getCompilerFilterForReason(REASON_INSTALL),
15001                    getOrCreateCompilerPackageStats(pkg));
15002            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
15003
15004            // Notify BackgroundDexOptService that the package has been changed.
15005            // If this is an update of a package which used to fail to compile,
15006            // BDOS will remove it from its blacklist.
15007            BackgroundDexOptService.notifyPackageChanged(pkg.packageName);
15008        }
15009
15010        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
15011            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
15012            return;
15013        }
15014
15015        startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg);
15016
15017        try (PackageFreezer freezer = freezePackageForInstall(pkgName, installFlags,
15018                "installPackageLI")) {
15019            if (replace) {
15020                replacePackageLIF(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user,
15021                        installerPackageName, res);
15022            } else {
15023                installNewPackageLIF(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
15024                        args.user, installerPackageName, volumeUuid, res);
15025            }
15026        }
15027        synchronized (mPackages) {
15028            final PackageSetting ps = mSettings.mPackages.get(pkgName);
15029            if (ps != null) {
15030                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
15031            }
15032
15033            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
15034            for (int i = 0; i < childCount; i++) {
15035                PackageParser.Package childPkg = pkg.childPackages.get(i);
15036                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
15037                PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName);
15038                if (childPs != null) {
15039                    childRes.newUsers = childPs.queryInstalledUsers(
15040                            sUserManager.getUserIds(), true);
15041                }
15042            }
15043        }
15044    }
15045
15046    private void startIntentFilterVerifications(int userId, boolean replacing,
15047            PackageParser.Package pkg) {
15048        if (mIntentFilterVerifierComponent == null) {
15049            Slog.w(TAG, "No IntentFilter verification will not be done as "
15050                    + "there is no IntentFilterVerifier available!");
15051            return;
15052        }
15053
15054        final int verifierUid = getPackageUid(
15055                mIntentFilterVerifierComponent.getPackageName(),
15056                MATCH_DEBUG_TRIAGED_MISSING,
15057                (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId);
15058
15059        Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
15060        msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid);
15061        mHandler.sendMessage(msg);
15062
15063        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
15064        for (int i = 0; i < childCount; i++) {
15065            PackageParser.Package childPkg = pkg.childPackages.get(i);
15066            msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
15067            msg.obj = new IFVerificationParams(childPkg, replacing, userId, verifierUid);
15068            mHandler.sendMessage(msg);
15069        }
15070    }
15071
15072    private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing,
15073            PackageParser.Package pkg) {
15074        int size = pkg.activities.size();
15075        if (size == 0) {
15076            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
15077                    "No activity, so no need to verify any IntentFilter!");
15078            return;
15079        }
15080
15081        final boolean hasDomainURLs = hasDomainURLs(pkg);
15082        if (!hasDomainURLs) {
15083            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
15084                    "No domain URLs, so no need to verify any IntentFilter!");
15085            return;
15086        }
15087
15088        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId
15089                + " if any IntentFilter from the " + size
15090                + " Activities needs verification ...");
15091
15092        int count = 0;
15093        final String packageName = pkg.packageName;
15094
15095        synchronized (mPackages) {
15096            // If this is a new install and we see that we've already run verification for this
15097            // package, we have nothing to do: it means the state was restored from backup.
15098            if (!replacing) {
15099                IntentFilterVerificationInfo ivi =
15100                        mSettings.getIntentFilterVerificationLPr(packageName);
15101                if (ivi != null) {
15102                    if (DEBUG_DOMAIN_VERIFICATION) {
15103                        Slog.i(TAG, "Package " + packageName+ " already verified: status="
15104                                + ivi.getStatusString());
15105                    }
15106                    return;
15107                }
15108            }
15109
15110            // If any filters need to be verified, then all need to be.
15111            boolean needToVerify = false;
15112            for (PackageParser.Activity a : pkg.activities) {
15113                for (ActivityIntentInfo filter : a.intents) {
15114                    if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) {
15115                        if (DEBUG_DOMAIN_VERIFICATION) {
15116                            Slog.d(TAG, "Intent filter needs verification, so processing all filters");
15117                        }
15118                        needToVerify = true;
15119                        break;
15120                    }
15121                }
15122            }
15123
15124            if (needToVerify) {
15125                final int verificationId = mIntentFilterVerificationToken++;
15126                for (PackageParser.Activity a : pkg.activities) {
15127                    for (ActivityIntentInfo filter : a.intents) {
15128                        if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) {
15129                            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
15130                                    "Verification needed for IntentFilter:" + filter.toString());
15131                            mIntentFilterVerifier.addOneIntentFilterVerification(
15132                                    verifierUid, userId, verificationId, filter, packageName);
15133                            count++;
15134                        }
15135                    }
15136                }
15137            }
15138        }
15139
15140        if (count > 0) {
15141            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count
15142                    + " IntentFilter verification" + (count > 1 ? "s" : "")
15143                    +  " for userId:" + userId);
15144            mIntentFilterVerifier.startVerifications(userId);
15145        } else {
15146            if (DEBUG_DOMAIN_VERIFICATION) {
15147                Slog.d(TAG, "No filters or not all autoVerify for " + packageName);
15148            }
15149        }
15150    }
15151
15152    private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) {
15153        final ComponentName cn  = filter.activity.getComponentName();
15154        final String packageName = cn.getPackageName();
15155
15156        IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr(
15157                packageName);
15158        if (ivi == null) {
15159            return true;
15160        }
15161        int status = ivi.getStatus();
15162        switch (status) {
15163            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
15164            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
15165                return true;
15166
15167            default:
15168                // Nothing to do
15169                return false;
15170        }
15171    }
15172
15173    private static boolean isMultiArch(ApplicationInfo info) {
15174        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
15175    }
15176
15177    private static boolean isExternal(PackageParser.Package pkg) {
15178        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
15179    }
15180
15181    private static boolean isExternal(PackageSetting ps) {
15182        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
15183    }
15184
15185    private static boolean isEphemeral(PackageParser.Package pkg) {
15186        return pkg.applicationInfo.isEphemeralApp();
15187    }
15188
15189    private static boolean isEphemeral(PackageSetting ps) {
15190        return ps.pkg != null && isEphemeral(ps.pkg);
15191    }
15192
15193    private static boolean isSystemApp(PackageParser.Package pkg) {
15194        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
15195    }
15196
15197    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
15198        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
15199    }
15200
15201    private static boolean hasDomainURLs(PackageParser.Package pkg) {
15202        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0;
15203    }
15204
15205    private static boolean isSystemApp(PackageSetting ps) {
15206        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
15207    }
15208
15209    private static boolean isUpdatedSystemApp(PackageSetting ps) {
15210        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
15211    }
15212
15213    private int packageFlagsToInstallFlags(PackageSetting ps) {
15214        int installFlags = 0;
15215        if (isEphemeral(ps)) {
15216            installFlags |= PackageManager.INSTALL_EPHEMERAL;
15217        }
15218        if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) {
15219            // This existing package was an external ASEC install when we have
15220            // the external flag without a UUID
15221            installFlags |= PackageManager.INSTALL_EXTERNAL;
15222        }
15223        if (ps.isForwardLocked()) {
15224            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
15225        }
15226        return installFlags;
15227    }
15228
15229    private String getVolumeUuidForPackage(PackageParser.Package pkg) {
15230        if (isExternal(pkg)) {
15231            if (TextUtils.isEmpty(pkg.volumeUuid)) {
15232                return StorageManager.UUID_PRIMARY_PHYSICAL;
15233            } else {
15234                return pkg.volumeUuid;
15235            }
15236        } else {
15237            return StorageManager.UUID_PRIVATE_INTERNAL;
15238        }
15239    }
15240
15241    private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) {
15242        if (isExternal(pkg)) {
15243            if (TextUtils.isEmpty(pkg.volumeUuid)) {
15244                return mSettings.getExternalVersion();
15245            } else {
15246                return mSettings.findOrCreateVersion(pkg.volumeUuid);
15247            }
15248        } else {
15249            return mSettings.getInternalVersion();
15250        }
15251    }
15252
15253    private void deleteTempPackageFiles() {
15254        final FilenameFilter filter = new FilenameFilter() {
15255            public boolean accept(File dir, String name) {
15256                return name.startsWith("vmdl") && name.endsWith(".tmp");
15257            }
15258        };
15259        for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) {
15260            file.delete();
15261        }
15262    }
15263
15264    @Override
15265    public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId,
15266            int flags) {
15267        deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId,
15268                flags);
15269    }
15270
15271    @Override
15272    public void deletePackage(final String packageName,
15273            final IPackageDeleteObserver2 observer, final int userId, final int deleteFlags) {
15274        mContext.enforceCallingOrSelfPermission(
15275                android.Manifest.permission.DELETE_PACKAGES, null);
15276        Preconditions.checkNotNull(packageName);
15277        Preconditions.checkNotNull(observer);
15278        final int uid = Binder.getCallingUid();
15279        final boolean deleteAllUsers = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0;
15280        final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId };
15281        if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) {
15282            mContext.enforceCallingOrSelfPermission(
15283                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
15284                    "deletePackage for user " + userId);
15285        }
15286
15287        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
15288            try {
15289                observer.onPackageDeleted(packageName,
15290                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
15291            } catch (RemoteException re) {
15292            }
15293            return;
15294        }
15295
15296        if (!deleteAllUsers && getBlockUninstallForUser(packageName, userId)) {
15297            try {
15298                observer.onPackageDeleted(packageName,
15299                        PackageManager.DELETE_FAILED_OWNER_BLOCKED, null);
15300            } catch (RemoteException re) {
15301            }
15302            return;
15303        }
15304
15305        if (DEBUG_REMOVE) {
15306            Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId
15307                    + " deleteAllUsers: " + deleteAllUsers );
15308        }
15309        // Queue up an async operation since the package deletion may take a little while.
15310        mHandler.post(new Runnable() {
15311            public void run() {
15312                mHandler.removeCallbacks(this);
15313                int returnCode;
15314                if (!deleteAllUsers) {
15315                    returnCode = deletePackageX(packageName, userId, deleteFlags);
15316                } else {
15317                    int[] blockUninstallUserIds = getBlockUninstallForUsers(packageName, users);
15318                    // If nobody is blocking uninstall, proceed with delete for all users
15319                    if (ArrayUtils.isEmpty(blockUninstallUserIds)) {
15320                        returnCode = deletePackageX(packageName, userId, deleteFlags);
15321                    } else {
15322                        // Otherwise uninstall individually for users with blockUninstalls=false
15323                        final int userFlags = deleteFlags & ~PackageManager.DELETE_ALL_USERS;
15324                        for (int userId : users) {
15325                            if (!ArrayUtils.contains(blockUninstallUserIds, userId)) {
15326                                returnCode = deletePackageX(packageName, userId, userFlags);
15327                                if (returnCode != PackageManager.DELETE_SUCCEEDED) {
15328                                    Slog.w(TAG, "Package delete failed for user " + userId
15329                                            + ", returnCode " + returnCode);
15330                                }
15331                            }
15332                        }
15333                        // The app has only been marked uninstalled for certain users.
15334                        // We still need to report that delete was blocked
15335                        returnCode = PackageManager.DELETE_FAILED_OWNER_BLOCKED;
15336                    }
15337                }
15338                try {
15339                    observer.onPackageDeleted(packageName, returnCode, null);
15340                } catch (RemoteException e) {
15341                    Log.i(TAG, "Observer no longer exists.");
15342                } //end catch
15343            } //end run
15344        });
15345    }
15346
15347    private int[] getBlockUninstallForUsers(String packageName, int[] userIds) {
15348        int[] result = EMPTY_INT_ARRAY;
15349        for (int userId : userIds) {
15350            if (getBlockUninstallForUser(packageName, userId)) {
15351                result = ArrayUtils.appendInt(result, userId);
15352            }
15353        }
15354        return result;
15355    }
15356
15357    @Override
15358    public boolean isPackageDeviceAdminOnAnyUser(String packageName) {
15359        return isPackageDeviceAdmin(packageName, UserHandle.USER_ALL);
15360    }
15361
15362    private boolean isPackageDeviceAdmin(String packageName, int userId) {
15363        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
15364                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
15365        try {
15366            if (dpm != null) {
15367                final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent(
15368                        /* callingUserOnly =*/ false);
15369                final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null
15370                        : deviceOwnerComponentName.getPackageName();
15371                // Does the package contains the device owner?
15372                // TODO Do we have to do it even if userId != UserHandle.USER_ALL?  Otherwise,
15373                // this check is probably not needed, since DO should be registered as a device
15374                // admin on some user too. (Original bug for this: b/17657954)
15375                if (packageName.equals(deviceOwnerPackageName)) {
15376                    return true;
15377                }
15378                // Does it contain a device admin for any user?
15379                int[] users;
15380                if (userId == UserHandle.USER_ALL) {
15381                    users = sUserManager.getUserIds();
15382                } else {
15383                    users = new int[]{userId};
15384                }
15385                for (int i = 0; i < users.length; ++i) {
15386                    if (dpm.packageHasActiveAdmins(packageName, users[i])) {
15387                        return true;
15388                    }
15389                }
15390            }
15391        } catch (RemoteException e) {
15392        }
15393        return false;
15394    }
15395
15396    private boolean shouldKeepUninstalledPackageLPr(String packageName) {
15397        return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName);
15398    }
15399
15400    /**
15401     *  This method is an internal method that could be get invoked either
15402     *  to delete an installed package or to clean up a failed installation.
15403     *  After deleting an installed package, a broadcast is sent to notify any
15404     *  listeners that the package has been removed. For cleaning up a failed
15405     *  installation, the broadcast is not necessary since the package's
15406     *  installation wouldn't have sent the initial broadcast either
15407     *  The key steps in deleting a package are
15408     *  deleting the package information in internal structures like mPackages,
15409     *  deleting the packages base directories through installd
15410     *  updating mSettings to reflect current status
15411     *  persisting settings for later use
15412     *  sending a broadcast if necessary
15413     */
15414    private int deletePackageX(String packageName, int userId, int deleteFlags) {
15415        final PackageRemovedInfo info = new PackageRemovedInfo();
15416        final boolean res;
15417
15418        final int removeUser = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0
15419                ? UserHandle.USER_ALL : userId;
15420
15421        if (isPackageDeviceAdmin(packageName, removeUser)) {
15422            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
15423            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
15424        }
15425
15426        PackageSetting uninstalledPs = null;
15427
15428        // for the uninstall-updates case and restricted profiles, remember the per-
15429        // user handle installed state
15430        int[] allUsers;
15431        synchronized (mPackages) {
15432            uninstalledPs = mSettings.mPackages.get(packageName);
15433            if (uninstalledPs == null) {
15434                Slog.w(TAG, "Not removing non-existent package " + packageName);
15435                return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
15436            }
15437            allUsers = sUserManager.getUserIds();
15438            info.origUsers = uninstalledPs.queryInstalledUsers(allUsers, true);
15439        }
15440
15441        final int freezeUser;
15442        if (isUpdatedSystemApp(uninstalledPs)
15443                && ((deleteFlags & PackageManager.DELETE_SYSTEM_APP) == 0)) {
15444            // We're downgrading a system app, which will apply to all users, so
15445            // freeze them all during the downgrade
15446            freezeUser = UserHandle.USER_ALL;
15447        } else {
15448            freezeUser = removeUser;
15449        }
15450
15451        synchronized (mInstallLock) {
15452            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
15453            try (PackageFreezer freezer = freezePackageForDelete(packageName, freezeUser,
15454                    deleteFlags, "deletePackageX")) {
15455                res = deletePackageLIF(packageName, UserHandle.of(removeUser), true, allUsers,
15456                        deleteFlags | REMOVE_CHATTY, info, true, null);
15457            }
15458            synchronized (mPackages) {
15459                if (res) {
15460                    mEphemeralApplicationRegistry.onPackageUninstalledLPw(uninstalledPs.pkg);
15461                }
15462            }
15463        }
15464
15465        if (res) {
15466            final boolean killApp = (deleteFlags & PackageManager.DELETE_DONT_KILL_APP) == 0;
15467            info.sendPackageRemovedBroadcasts(killApp);
15468            info.sendSystemPackageUpdatedBroadcasts();
15469            info.sendSystemPackageAppearedBroadcasts();
15470        }
15471        // Force a gc here.
15472        Runtime.getRuntime().gc();
15473        // Delete the resources here after sending the broadcast to let
15474        // other processes clean up before deleting resources.
15475        if (info.args != null) {
15476            synchronized (mInstallLock) {
15477                info.args.doPostDeleteLI(true);
15478            }
15479        }
15480
15481        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
15482    }
15483
15484    class PackageRemovedInfo {
15485        String removedPackage;
15486        int uid = -1;
15487        int removedAppId = -1;
15488        int[] origUsers;
15489        int[] removedUsers = null;
15490        boolean isRemovedPackageSystemUpdate = false;
15491        boolean isUpdate;
15492        boolean dataRemoved;
15493        boolean removedForAllUsers;
15494        // Clean up resources deleted packages.
15495        InstallArgs args = null;
15496        ArrayMap<String, PackageRemovedInfo> removedChildPackages;
15497        ArrayMap<String, PackageInstalledInfo> appearedChildPackages;
15498
15499        void sendPackageRemovedBroadcasts(boolean killApp) {
15500            sendPackageRemovedBroadcastInternal(killApp);
15501            final int childCount = removedChildPackages != null ? removedChildPackages.size() : 0;
15502            for (int i = 0; i < childCount; i++) {
15503                PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
15504                childInfo.sendPackageRemovedBroadcastInternal(killApp);
15505            }
15506        }
15507
15508        void sendSystemPackageUpdatedBroadcasts() {
15509            if (isRemovedPackageSystemUpdate) {
15510                sendSystemPackageUpdatedBroadcastsInternal();
15511                final int childCount = (removedChildPackages != null)
15512                        ? removedChildPackages.size() : 0;
15513                for (int i = 0; i < childCount; i++) {
15514                    PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
15515                    if (childInfo.isRemovedPackageSystemUpdate) {
15516                        childInfo.sendSystemPackageUpdatedBroadcastsInternal();
15517                    }
15518                }
15519            }
15520        }
15521
15522        void sendSystemPackageAppearedBroadcasts() {
15523            final int packageCount = (appearedChildPackages != null)
15524                    ? appearedChildPackages.size() : 0;
15525            for (int i = 0; i < packageCount; i++) {
15526                PackageInstalledInfo installedInfo = appearedChildPackages.valueAt(i);
15527                for (int userId : installedInfo.newUsers) {
15528                    sendPackageAddedForUser(installedInfo.name, true,
15529                            UserHandle.getAppId(installedInfo.uid), userId);
15530                }
15531            }
15532        }
15533
15534        private void sendSystemPackageUpdatedBroadcastsInternal() {
15535            Bundle extras = new Bundle(2);
15536            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
15537            extras.putBoolean(Intent.EXTRA_REPLACING, true);
15538            sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, removedPackage,
15539                    extras, 0, null, null, null);
15540            sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, removedPackage,
15541                    extras, 0, null, null, null);
15542            sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null,
15543                    null, 0, removedPackage, null, null);
15544        }
15545
15546        private void sendPackageRemovedBroadcastInternal(boolean killApp) {
15547            Bundle extras = new Bundle(2);
15548            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0  ? removedAppId : uid);
15549            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, dataRemoved);
15550            extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, !killApp);
15551            if (isUpdate || isRemovedPackageSystemUpdate) {
15552                extras.putBoolean(Intent.EXTRA_REPLACING, true);
15553            }
15554            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
15555            if (removedPackage != null) {
15556                sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
15557                        extras, 0, null, null, removedUsers);
15558                if (dataRemoved && !isRemovedPackageSystemUpdate) {
15559                    sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED,
15560                            removedPackage, extras, 0, null, null, removedUsers);
15561                }
15562            }
15563            if (removedAppId >= 0) {
15564                sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, 0, null, null,
15565                        removedUsers);
15566            }
15567        }
15568    }
15569
15570    /*
15571     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
15572     * flag is not set, the data directory is removed as well.
15573     * make sure this flag is set for partially installed apps. If not its meaningless to
15574     * delete a partially installed application.
15575     */
15576    private void removePackageDataLIF(PackageSetting ps, int[] allUserHandles,
15577            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
15578        String packageName = ps.name;
15579        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
15580        // Retrieve object to delete permissions for shared user later on
15581        final PackageParser.Package deletedPkg;
15582        final PackageSetting deletedPs;
15583        // reader
15584        synchronized (mPackages) {
15585            deletedPkg = mPackages.get(packageName);
15586            deletedPs = mSettings.mPackages.get(packageName);
15587            if (outInfo != null) {
15588                outInfo.removedPackage = packageName;
15589                outInfo.removedUsers = deletedPs != null
15590                        ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true)
15591                        : null;
15592            }
15593        }
15594
15595        removePackageLI(ps, (flags & REMOVE_CHATTY) != 0);
15596
15597        if ((flags & PackageManager.DELETE_KEEP_DATA) == 0) {
15598            final PackageParser.Package resolvedPkg;
15599            if (deletedPkg != null) {
15600                resolvedPkg = deletedPkg;
15601            } else {
15602                // We don't have a parsed package when it lives on an ejected
15603                // adopted storage device, so fake something together
15604                resolvedPkg = new PackageParser.Package(ps.name);
15605                resolvedPkg.setVolumeUuid(ps.volumeUuid);
15606            }
15607            destroyAppDataLIF(resolvedPkg, UserHandle.USER_ALL,
15608                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
15609            destroyAppProfilesLIF(resolvedPkg, UserHandle.USER_ALL);
15610            if (outInfo != null) {
15611                outInfo.dataRemoved = true;
15612            }
15613            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
15614        }
15615
15616        // writer
15617        synchronized (mPackages) {
15618            if (deletedPs != null) {
15619                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
15620                    clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL);
15621                    clearDefaultBrowserIfNeeded(packageName);
15622                    if (outInfo != null) {
15623                        mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
15624                        outInfo.removedAppId = mSettings.removePackageLPw(packageName);
15625                    }
15626                    updatePermissionsLPw(deletedPs.name, null, 0);
15627                    if (deletedPs.sharedUser != null) {
15628                        // Remove permissions associated with package. Since runtime
15629                        // permissions are per user we have to kill the removed package
15630                        // or packages running under the shared user of the removed
15631                        // package if revoking the permissions requested only by the removed
15632                        // package is successful and this causes a change in gids.
15633                        for (int userId : UserManagerService.getInstance().getUserIds()) {
15634                            final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs,
15635                                    userId);
15636                            if (userIdToKill == UserHandle.USER_ALL
15637                                    || userIdToKill >= UserHandle.USER_SYSTEM) {
15638                                // If gids changed for this user, kill all affected packages.
15639                                mHandler.post(new Runnable() {
15640                                    @Override
15641                                    public void run() {
15642                                        // This has to happen with no lock held.
15643                                        killApplication(deletedPs.name, deletedPs.appId,
15644                                                KILL_APP_REASON_GIDS_CHANGED);
15645                                    }
15646                                });
15647                                break;
15648                            }
15649                        }
15650                    }
15651                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
15652                }
15653                // make sure to preserve per-user disabled state if this removal was just
15654                // a downgrade of a system app to the factory package
15655                if (allUserHandles != null && outInfo != null && outInfo.origUsers != null) {
15656                    if (DEBUG_REMOVE) {
15657                        Slog.d(TAG, "Propagating install state across downgrade");
15658                    }
15659                    for (int userId : allUserHandles) {
15660                        final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
15661                        if (DEBUG_REMOVE) {
15662                            Slog.d(TAG, "    user " + userId + " => " + installed);
15663                        }
15664                        ps.setInstalled(installed, userId);
15665                    }
15666                }
15667            }
15668            // can downgrade to reader
15669            if (writeSettings) {
15670                // Save settings now
15671                mSettings.writeLPr();
15672            }
15673        }
15674        if (outInfo != null) {
15675            // A user ID was deleted here. Go through all users and remove it
15676            // from KeyStore.
15677            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId);
15678        }
15679    }
15680
15681    static boolean locationIsPrivileged(File path) {
15682        try {
15683            final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
15684                    .getCanonicalPath();
15685            return path.getCanonicalPath().startsWith(privilegedAppDir);
15686        } catch (IOException e) {
15687            Slog.e(TAG, "Unable to access code path " + path);
15688        }
15689        return false;
15690    }
15691
15692    /*
15693     * Tries to delete system package.
15694     */
15695    private boolean deleteSystemPackageLIF(PackageParser.Package deletedPkg,
15696            PackageSetting deletedPs, int[] allUserHandles, int flags, PackageRemovedInfo outInfo,
15697            boolean writeSettings) {
15698        if (deletedPs.parentPackageName != null) {
15699            Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName);
15700            return false;
15701        }
15702
15703        final boolean applyUserRestrictions
15704                = (allUserHandles != null) && (outInfo.origUsers != null);
15705        final PackageSetting disabledPs;
15706        // Confirm if the system package has been updated
15707        // An updated system app can be deleted. This will also have to restore
15708        // the system pkg from system partition
15709        // reader
15710        synchronized (mPackages) {
15711            disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPs.name);
15712        }
15713
15714        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName
15715                + " disabledPs=" + disabledPs);
15716
15717        if (disabledPs == null) {
15718            Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName);
15719            return false;
15720        } else if (DEBUG_REMOVE) {
15721            Slog.d(TAG, "Deleting system pkg from data partition");
15722        }
15723
15724        if (DEBUG_REMOVE) {
15725            if (applyUserRestrictions) {
15726                Slog.d(TAG, "Remembering install states:");
15727                for (int userId : allUserHandles) {
15728                    final boolean finstalled = ArrayUtils.contains(outInfo.origUsers, userId);
15729                    Slog.d(TAG, "   u=" + userId + " inst=" + finstalled);
15730                }
15731            }
15732        }
15733
15734        // Delete the updated package
15735        outInfo.isRemovedPackageSystemUpdate = true;
15736        if (outInfo.removedChildPackages != null) {
15737            final int childCount = (deletedPs.childPackageNames != null)
15738                    ? deletedPs.childPackageNames.size() : 0;
15739            for (int i = 0; i < childCount; i++) {
15740                String childPackageName = deletedPs.childPackageNames.get(i);
15741                if (disabledPs.childPackageNames != null && disabledPs.childPackageNames
15742                        .contains(childPackageName)) {
15743                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
15744                            childPackageName);
15745                    if (childInfo != null) {
15746                        childInfo.isRemovedPackageSystemUpdate = true;
15747                    }
15748                }
15749            }
15750        }
15751
15752        if (disabledPs.versionCode < deletedPs.versionCode) {
15753            // Delete data for downgrades
15754            flags &= ~PackageManager.DELETE_KEEP_DATA;
15755        } else {
15756            // Preserve data by setting flag
15757            flags |= PackageManager.DELETE_KEEP_DATA;
15758        }
15759
15760        boolean ret = deleteInstalledPackageLIF(deletedPs, true, flags, allUserHandles,
15761                outInfo, writeSettings, disabledPs.pkg);
15762        if (!ret) {
15763            return false;
15764        }
15765
15766        // writer
15767        synchronized (mPackages) {
15768            // Reinstate the old system package
15769            enableSystemPackageLPw(disabledPs.pkg);
15770            // Remove any native libraries from the upgraded package.
15771            removeNativeBinariesLI(deletedPs);
15772        }
15773
15774        // Install the system package
15775        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
15776        int parseFlags = mDefParseFlags
15777                | PackageParser.PARSE_MUST_BE_APK
15778                | PackageParser.PARSE_IS_SYSTEM
15779                | PackageParser.PARSE_IS_SYSTEM_DIR;
15780        if (locationIsPrivileged(disabledPs.codePath)) {
15781            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
15782        }
15783
15784        final PackageParser.Package newPkg;
15785        try {
15786            newPkg = scanPackageTracedLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null);
15787        } catch (PackageManagerException e) {
15788            Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": "
15789                    + e.getMessage());
15790            return false;
15791        }
15792
15793        prepareAppDataAfterInstallLIF(newPkg);
15794
15795        // writer
15796        synchronized (mPackages) {
15797            PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
15798
15799            // Propagate the permissions state as we do not want to drop on the floor
15800            // runtime permissions. The update permissions method below will take
15801            // care of removing obsolete permissions and grant install permissions.
15802            ps.getPermissionsState().copyFrom(deletedPs.getPermissionsState());
15803            updatePermissionsLPw(newPkg.packageName, newPkg,
15804                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
15805
15806            if (applyUserRestrictions) {
15807                if (DEBUG_REMOVE) {
15808                    Slog.d(TAG, "Propagating install state across reinstall");
15809                }
15810                for (int userId : allUserHandles) {
15811                    final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
15812                    if (DEBUG_REMOVE) {
15813                        Slog.d(TAG, "    user " + userId + " => " + installed);
15814                    }
15815                    ps.setInstalled(installed, userId);
15816
15817                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
15818                }
15819                // Regardless of writeSettings we need to ensure that this restriction
15820                // state propagation is persisted
15821                mSettings.writeAllUsersPackageRestrictionsLPr();
15822            }
15823            // can downgrade to reader here
15824            if (writeSettings) {
15825                mSettings.writeLPr();
15826            }
15827        }
15828        return true;
15829    }
15830
15831    private boolean deleteInstalledPackageLIF(PackageSetting ps,
15832            boolean deleteCodeAndResources, int flags, int[] allUserHandles,
15833            PackageRemovedInfo outInfo, boolean writeSettings,
15834            PackageParser.Package replacingPackage) {
15835        synchronized (mPackages) {
15836            if (outInfo != null) {
15837                outInfo.uid = ps.appId;
15838            }
15839
15840            if (outInfo != null && outInfo.removedChildPackages != null) {
15841                final int childCount = (ps.childPackageNames != null)
15842                        ? ps.childPackageNames.size() : 0;
15843                for (int i = 0; i < childCount; i++) {
15844                    String childPackageName = ps.childPackageNames.get(i);
15845                    PackageSetting childPs = mSettings.mPackages.get(childPackageName);
15846                    if (childPs == null) {
15847                        return false;
15848                    }
15849                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
15850                            childPackageName);
15851                    if (childInfo != null) {
15852                        childInfo.uid = childPs.appId;
15853                    }
15854                }
15855            }
15856        }
15857
15858        // Delete package data from internal structures and also remove data if flag is set
15859        removePackageDataLIF(ps, allUserHandles, outInfo, flags, writeSettings);
15860
15861        // Delete the child packages data
15862        final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
15863        for (int i = 0; i < childCount; i++) {
15864            PackageSetting childPs;
15865            synchronized (mPackages) {
15866                childPs = mSettings.peekPackageLPr(ps.childPackageNames.get(i));
15867            }
15868            if (childPs != null) {
15869                PackageRemovedInfo childOutInfo = (outInfo != null
15870                        && outInfo.removedChildPackages != null)
15871                        ? outInfo.removedChildPackages.get(childPs.name) : null;
15872                final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0
15873                        && (replacingPackage != null
15874                        && !replacingPackage.hasChildPackage(childPs.name))
15875                        ? flags & ~DELETE_KEEP_DATA : flags;
15876                removePackageDataLIF(childPs, allUserHandles, childOutInfo,
15877                        deleteFlags, writeSettings);
15878            }
15879        }
15880
15881        // Delete application code and resources only for parent packages
15882        if (ps.parentPackageName == null) {
15883            if (deleteCodeAndResources && (outInfo != null)) {
15884                outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
15885                        ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
15886                if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
15887            }
15888        }
15889
15890        return true;
15891    }
15892
15893    @Override
15894    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
15895            int userId) {
15896        mContext.enforceCallingOrSelfPermission(
15897                android.Manifest.permission.DELETE_PACKAGES, null);
15898        synchronized (mPackages) {
15899            PackageSetting ps = mSettings.mPackages.get(packageName);
15900            if (ps == null) {
15901                Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName);
15902                return false;
15903            }
15904            if (!ps.getInstalled(userId)) {
15905                // Can't block uninstall for an app that is not installed or enabled.
15906                Log.i(TAG, "Package not installed in set block uninstall " + packageName);
15907                return false;
15908            }
15909            ps.setBlockUninstall(blockUninstall, userId);
15910            mSettings.writePackageRestrictionsLPr(userId);
15911        }
15912        return true;
15913    }
15914
15915    @Override
15916    public boolean getBlockUninstallForUser(String packageName, int userId) {
15917        synchronized (mPackages) {
15918            PackageSetting ps = mSettings.mPackages.get(packageName);
15919            if (ps == null) {
15920                Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName);
15921                return false;
15922            }
15923            return ps.getBlockUninstall(userId);
15924        }
15925    }
15926
15927    @Override
15928    public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) {
15929        int callingUid = Binder.getCallingUid();
15930        if (callingUid != Process.SYSTEM_UID && callingUid != Process.ROOT_UID) {
15931            throw new SecurityException(
15932                    "setRequiredForSystemUser can only be run by the system or root");
15933        }
15934        synchronized (mPackages) {
15935            PackageSetting ps = mSettings.mPackages.get(packageName);
15936            if (ps == null) {
15937                Log.w(TAG, "Package doesn't exist: " + packageName);
15938                return false;
15939            }
15940            if (systemUserApp) {
15941                ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
15942            } else {
15943                ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
15944            }
15945            mSettings.writeLPr();
15946        }
15947        return true;
15948    }
15949
15950    /*
15951     * This method handles package deletion in general
15952     */
15953    private boolean deletePackageLIF(String packageName, UserHandle user,
15954            boolean deleteCodeAndResources, int[] allUserHandles, int flags,
15955            PackageRemovedInfo outInfo, boolean writeSettings,
15956            PackageParser.Package replacingPackage) {
15957        if (packageName == null) {
15958            Slog.w(TAG, "Attempt to delete null packageName.");
15959            return false;
15960        }
15961
15962        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
15963
15964        PackageSetting ps;
15965
15966        synchronized (mPackages) {
15967            ps = mSettings.mPackages.get(packageName);
15968            if (ps == null) {
15969                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
15970                return false;
15971            }
15972
15973            if (ps.parentPackageName != null && (!isSystemApp(ps)
15974                    || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) {
15975                if (DEBUG_REMOVE) {
15976                    Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:"
15977                            + ((user == null) ? UserHandle.USER_ALL : user));
15978                }
15979                final int removedUserId = (user != null) ? user.getIdentifier()
15980                        : UserHandle.USER_ALL;
15981                if (!clearPackageStateForUserLIF(ps, removedUserId, outInfo)) {
15982                    return false;
15983                }
15984                markPackageUninstalledForUserLPw(ps, user);
15985                scheduleWritePackageRestrictionsLocked(user);
15986                return true;
15987            }
15988        }
15989
15990        if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
15991                && user.getIdentifier() != UserHandle.USER_ALL)) {
15992            // The caller is asking that the package only be deleted for a single
15993            // user.  To do this, we just mark its uninstalled state and delete
15994            // its data. If this is a system app, we only allow this to happen if
15995            // they have set the special DELETE_SYSTEM_APP which requests different
15996            // semantics than normal for uninstalling system apps.
15997            markPackageUninstalledForUserLPw(ps, user);
15998
15999            if (!isSystemApp(ps)) {
16000                // Do not uninstall the APK if an app should be cached
16001                boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName);
16002                if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) {
16003                    // Other user still have this package installed, so all
16004                    // we need to do is clear this user's data and save that
16005                    // it is uninstalled.
16006                    if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
16007                    if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
16008                        return false;
16009                    }
16010                    scheduleWritePackageRestrictionsLocked(user);
16011                    return true;
16012                } else {
16013                    // We need to set it back to 'installed' so the uninstall
16014                    // broadcasts will be sent correctly.
16015                    if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
16016                    ps.setInstalled(true, user.getIdentifier());
16017                }
16018            } else {
16019                // This is a system app, so we assume that the
16020                // other users still have this package installed, so all
16021                // we need to do is clear this user's data and save that
16022                // it is uninstalled.
16023                if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
16024                if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
16025                    return false;
16026                }
16027                scheduleWritePackageRestrictionsLocked(user);
16028                return true;
16029            }
16030        }
16031
16032        // If we are deleting a composite package for all users, keep track
16033        // of result for each child.
16034        if (ps.childPackageNames != null && outInfo != null) {
16035            synchronized (mPackages) {
16036                final int childCount = ps.childPackageNames.size();
16037                outInfo.removedChildPackages = new ArrayMap<>(childCount);
16038                for (int i = 0; i < childCount; i++) {
16039                    String childPackageName = ps.childPackageNames.get(i);
16040                    PackageRemovedInfo childInfo = new PackageRemovedInfo();
16041                    childInfo.removedPackage = childPackageName;
16042                    outInfo.removedChildPackages.put(childPackageName, childInfo);
16043                    PackageSetting childPs = mSettings.peekPackageLPr(childPackageName);
16044                    if (childPs != null) {
16045                        childInfo.origUsers = childPs.queryInstalledUsers(allUserHandles, true);
16046                    }
16047                }
16048            }
16049        }
16050
16051        boolean ret = false;
16052        if (isSystemApp(ps)) {
16053            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name);
16054            // When an updated system application is deleted we delete the existing resources
16055            // as well and fall back to existing code in system partition
16056            ret = deleteSystemPackageLIF(ps.pkg, ps, allUserHandles, flags, outInfo, writeSettings);
16057        } else {
16058            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name);
16059            ret = deleteInstalledPackageLIF(ps, deleteCodeAndResources, flags, allUserHandles,
16060                    outInfo, writeSettings, replacingPackage);
16061        }
16062
16063        // Take a note whether we deleted the package for all users
16064        if (outInfo != null) {
16065            outInfo.removedForAllUsers = mPackages.get(ps.name) == null;
16066            if (outInfo.removedChildPackages != null) {
16067                synchronized (mPackages) {
16068                    final int childCount = outInfo.removedChildPackages.size();
16069                    for (int i = 0; i < childCount; i++) {
16070                        PackageRemovedInfo childInfo = outInfo.removedChildPackages.valueAt(i);
16071                        if (childInfo != null) {
16072                            childInfo.removedForAllUsers = mPackages.get(
16073                                    childInfo.removedPackage) == null;
16074                        }
16075                    }
16076                }
16077            }
16078            // If we uninstalled an update to a system app there may be some
16079            // child packages that appeared as they are declared in the system
16080            // app but were not declared in the update.
16081            if (isSystemApp(ps)) {
16082                synchronized (mPackages) {
16083                    PackageSetting updatedPs = mSettings.peekPackageLPr(ps.name);
16084                    final int childCount = (updatedPs.childPackageNames != null)
16085                            ? updatedPs.childPackageNames.size() : 0;
16086                    for (int i = 0; i < childCount; i++) {
16087                        String childPackageName = updatedPs.childPackageNames.get(i);
16088                        if (outInfo.removedChildPackages == null
16089                                || outInfo.removedChildPackages.indexOfKey(childPackageName) < 0) {
16090                            PackageSetting childPs = mSettings.peekPackageLPr(childPackageName);
16091                            if (childPs == null) {
16092                                continue;
16093                            }
16094                            PackageInstalledInfo installRes = new PackageInstalledInfo();
16095                            installRes.name = childPackageName;
16096                            installRes.newUsers = childPs.queryInstalledUsers(allUserHandles, true);
16097                            installRes.pkg = mPackages.get(childPackageName);
16098                            installRes.uid = childPs.pkg.applicationInfo.uid;
16099                            if (outInfo.appearedChildPackages == null) {
16100                                outInfo.appearedChildPackages = new ArrayMap<>();
16101                            }
16102                            outInfo.appearedChildPackages.put(childPackageName, installRes);
16103                        }
16104                    }
16105                }
16106            }
16107        }
16108
16109        return ret;
16110    }
16111
16112    private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) {
16113        final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL)
16114                ? sUserManager.getUserIds() : new int[] {user.getIdentifier()};
16115        for (int nextUserId : userIds) {
16116            if (DEBUG_REMOVE) {
16117                Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId);
16118            }
16119            ps.setUserState(nextUserId, 0, COMPONENT_ENABLED_STATE_DEFAULT,
16120                    false /*installed*/, true /*stopped*/, true /*notLaunched*/,
16121                    false /*hidden*/, false /*suspended*/, null, null, null,
16122                    false /*blockUninstall*/,
16123                    ps.readUserState(nextUserId).domainVerificationStatus, 0);
16124        }
16125    }
16126
16127    private boolean clearPackageStateForUserLIF(PackageSetting ps, int userId,
16128            PackageRemovedInfo outInfo) {
16129        final PackageParser.Package pkg;
16130        synchronized (mPackages) {
16131            pkg = mPackages.get(ps.name);
16132        }
16133
16134        final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds()
16135                : new int[] {userId};
16136        for (int nextUserId : userIds) {
16137            if (DEBUG_REMOVE) {
16138                Slog.d(TAG, "Updating package:" + ps.name + " install state for user:"
16139                        + nextUserId);
16140            }
16141
16142            destroyAppDataLIF(pkg, userId,
16143                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
16144            destroyAppProfilesLIF(pkg, userId);
16145            removeKeystoreDataIfNeeded(nextUserId, ps.appId);
16146            schedulePackageCleaning(ps.name, nextUserId, false);
16147            synchronized (mPackages) {
16148                if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) {
16149                    scheduleWritePackageRestrictionsLocked(nextUserId);
16150                }
16151                resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId);
16152            }
16153        }
16154
16155        if (outInfo != null) {
16156            outInfo.removedPackage = ps.name;
16157            outInfo.removedAppId = ps.appId;
16158            outInfo.removedUsers = userIds;
16159        }
16160
16161        return true;
16162    }
16163
16164    private final class ClearStorageConnection implements ServiceConnection {
16165        IMediaContainerService mContainerService;
16166
16167        @Override
16168        public void onServiceConnected(ComponentName name, IBinder service) {
16169            synchronized (this) {
16170                mContainerService = IMediaContainerService.Stub.asInterface(service);
16171                notifyAll();
16172            }
16173        }
16174
16175        @Override
16176        public void onServiceDisconnected(ComponentName name) {
16177        }
16178    }
16179
16180    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
16181        if (DEFAULT_CONTAINER_PACKAGE.equals(packageName)) return;
16182
16183        final boolean mounted;
16184        if (Environment.isExternalStorageEmulated()) {
16185            mounted = true;
16186        } else {
16187            final String status = Environment.getExternalStorageState();
16188
16189            mounted = status.equals(Environment.MEDIA_MOUNTED)
16190                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
16191        }
16192
16193        if (!mounted) {
16194            return;
16195        }
16196
16197        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
16198        int[] users;
16199        if (userId == UserHandle.USER_ALL) {
16200            users = sUserManager.getUserIds();
16201        } else {
16202            users = new int[] { userId };
16203        }
16204        final ClearStorageConnection conn = new ClearStorageConnection();
16205        if (mContext.bindServiceAsUser(
16206                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
16207            try {
16208                for (int curUser : users) {
16209                    long timeout = SystemClock.uptimeMillis() + 5000;
16210                    synchronized (conn) {
16211                        long now;
16212                        while (conn.mContainerService == null &&
16213                                (now = SystemClock.uptimeMillis()) < timeout) {
16214                            try {
16215                                conn.wait(timeout - now);
16216                            } catch (InterruptedException e) {
16217                            }
16218                        }
16219                    }
16220                    if (conn.mContainerService == null) {
16221                        return;
16222                    }
16223
16224                    final UserEnvironment userEnv = new UserEnvironment(curUser);
16225                    clearDirectory(conn.mContainerService,
16226                            userEnv.buildExternalStorageAppCacheDirs(packageName));
16227                    if (allData) {
16228                        clearDirectory(conn.mContainerService,
16229                                userEnv.buildExternalStorageAppDataDirs(packageName));
16230                        clearDirectory(conn.mContainerService,
16231                                userEnv.buildExternalStorageAppMediaDirs(packageName));
16232                    }
16233                }
16234            } finally {
16235                mContext.unbindService(conn);
16236            }
16237        }
16238    }
16239
16240    @Override
16241    public void clearApplicationProfileData(String packageName) {
16242        enforceSystemOrRoot("Only the system can clear all profile data");
16243
16244        final PackageParser.Package pkg;
16245        synchronized (mPackages) {
16246            pkg = mPackages.get(packageName);
16247        }
16248
16249        try (PackageFreezer freezer = freezePackage(packageName, "clearApplicationProfileData")) {
16250            synchronized (mInstallLock) {
16251                clearAppProfilesLIF(pkg, UserHandle.USER_ALL);
16252                destroyAppReferenceProfileLeafLIF(pkg, UserHandle.USER_ALL,
16253                        true /* removeBaseMarker */);
16254            }
16255        }
16256    }
16257
16258    @Override
16259    public void clearApplicationUserData(final String packageName,
16260            final IPackageDataObserver observer, final int userId) {
16261        mContext.enforceCallingOrSelfPermission(
16262                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
16263
16264        enforceCrossUserPermission(Binder.getCallingUid(), userId,
16265                true /* requireFullPermission */, false /* checkShell */, "clear application data");
16266
16267        if (mProtectedPackages.canPackageBeWiped(userId, packageName)) {
16268            throw new SecurityException("Cannot clear data for a device owner or a profile owner");
16269        }
16270        // Queue up an async operation since the package deletion may take a little while.
16271        mHandler.post(new Runnable() {
16272            public void run() {
16273                mHandler.removeCallbacks(this);
16274                final boolean succeeded;
16275                try (PackageFreezer freezer = freezePackage(packageName,
16276                        "clearApplicationUserData")) {
16277                    synchronized (mInstallLock) {
16278                        succeeded = clearApplicationUserDataLIF(packageName, userId);
16279                    }
16280                    clearExternalStorageDataSync(packageName, userId, true);
16281                }
16282                if (succeeded) {
16283                    // invoke DeviceStorageMonitor's update method to clear any notifications
16284                    DeviceStorageMonitorInternal dsm = LocalServices
16285                            .getService(DeviceStorageMonitorInternal.class);
16286                    if (dsm != null) {
16287                        dsm.checkMemory();
16288                    }
16289                }
16290                if(observer != null) {
16291                    try {
16292                        observer.onRemoveCompleted(packageName, succeeded);
16293                    } catch (RemoteException e) {
16294                        Log.i(TAG, "Observer no longer exists.");
16295                    }
16296                } //end if observer
16297            } //end run
16298        });
16299    }
16300
16301    private boolean clearApplicationUserDataLIF(String packageName, int userId) {
16302        if (packageName == null) {
16303            Slog.w(TAG, "Attempt to delete null packageName.");
16304            return false;
16305        }
16306
16307        // Try finding details about the requested package
16308        PackageParser.Package pkg;
16309        synchronized (mPackages) {
16310            pkg = mPackages.get(packageName);
16311            if (pkg == null) {
16312                final PackageSetting ps = mSettings.mPackages.get(packageName);
16313                if (ps != null) {
16314                    pkg = ps.pkg;
16315                }
16316            }
16317
16318            if (pkg == null) {
16319                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
16320                return false;
16321            }
16322
16323            PackageSetting ps = (PackageSetting) pkg.mExtras;
16324            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
16325        }
16326
16327        clearAppDataLIF(pkg, userId,
16328                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
16329
16330        final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
16331        removeKeystoreDataIfNeeded(userId, appId);
16332
16333        UserManagerInternal umInternal = getUserManagerInternal();
16334        final int flags;
16335        if (umInternal.isUserUnlockingOrUnlocked(userId)) {
16336            flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
16337        } else if (umInternal.isUserRunning(userId)) {
16338            flags = StorageManager.FLAG_STORAGE_DE;
16339        } else {
16340            flags = 0;
16341        }
16342        prepareAppDataContentsLIF(pkg, userId, flags);
16343
16344        return true;
16345    }
16346
16347    /**
16348     * Reverts user permission state changes (permissions and flags) in
16349     * all packages for a given user.
16350     *
16351     * @param userId The device user for which to do a reset.
16352     */
16353    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) {
16354        final int packageCount = mPackages.size();
16355        for (int i = 0; i < packageCount; i++) {
16356            PackageParser.Package pkg = mPackages.valueAt(i);
16357            PackageSetting ps = (PackageSetting) pkg.mExtras;
16358            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
16359        }
16360    }
16361
16362    private void resetNetworkPolicies(int userId) {
16363        LocalServices.getService(NetworkPolicyManagerInternal.class).resetUserState(userId);
16364    }
16365
16366    /**
16367     * Reverts user permission state changes (permissions and flags).
16368     *
16369     * @param ps The package for which to reset.
16370     * @param userId The device user for which to do a reset.
16371     */
16372    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(
16373            final PackageSetting ps, final int userId) {
16374        if (ps.pkg == null) {
16375            return;
16376        }
16377
16378        // These are flags that can change base on user actions.
16379        final int userSettableMask = FLAG_PERMISSION_USER_SET
16380                | FLAG_PERMISSION_USER_FIXED
16381                | FLAG_PERMISSION_REVOKE_ON_UPGRADE
16382                | FLAG_PERMISSION_REVIEW_REQUIRED;
16383
16384        final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED
16385                | FLAG_PERMISSION_POLICY_FIXED;
16386
16387        boolean writeInstallPermissions = false;
16388        boolean writeRuntimePermissions = false;
16389
16390        final int permissionCount = ps.pkg.requestedPermissions.size();
16391        for (int i = 0; i < permissionCount; i++) {
16392            String permission = ps.pkg.requestedPermissions.get(i);
16393
16394            BasePermission bp = mSettings.mPermissions.get(permission);
16395            if (bp == null) {
16396                continue;
16397            }
16398
16399            // If shared user we just reset the state to which only this app contributed.
16400            if (ps.sharedUser != null) {
16401                boolean used = false;
16402                final int packageCount = ps.sharedUser.packages.size();
16403                for (int j = 0; j < packageCount; j++) {
16404                    PackageSetting pkg = ps.sharedUser.packages.valueAt(j);
16405                    if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName)
16406                            && pkg.pkg.requestedPermissions.contains(permission)) {
16407                        used = true;
16408                        break;
16409                    }
16410                }
16411                if (used) {
16412                    continue;
16413                }
16414            }
16415
16416            PermissionsState permissionsState = ps.getPermissionsState();
16417
16418            final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId);
16419
16420            // Always clear the user settable flags.
16421            final boolean hasInstallState = permissionsState.getInstallPermissionState(
16422                    bp.name) != null;
16423            // If permission review is enabled and this is a legacy app, mark the
16424            // permission as requiring a review as this is the initial state.
16425            int flags = 0;
16426            if (Build.PERMISSIONS_REVIEW_REQUIRED
16427                    && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
16428                flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
16429            }
16430            if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) {
16431                if (hasInstallState) {
16432                    writeInstallPermissions = true;
16433                } else {
16434                    writeRuntimePermissions = true;
16435                }
16436            }
16437
16438            // Below is only runtime permission handling.
16439            if (!bp.isRuntime()) {
16440                continue;
16441            }
16442
16443            // Never clobber system or policy.
16444            if ((oldFlags & policyOrSystemFlags) != 0) {
16445                continue;
16446            }
16447
16448            // If this permission was granted by default, make sure it is.
16449            if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) {
16450                if (permissionsState.grantRuntimePermission(bp, userId)
16451                        != PERMISSION_OPERATION_FAILURE) {
16452                    writeRuntimePermissions = true;
16453                }
16454            // If permission review is enabled the permissions for a legacy apps
16455            // are represented as constantly granted runtime ones, so don't revoke.
16456            } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
16457                // Otherwise, reset the permission.
16458                final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId);
16459                switch (revokeResult) {
16460                    case PERMISSION_OPERATION_SUCCESS:
16461                    case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
16462                        writeRuntimePermissions = true;
16463                        final int appId = ps.appId;
16464                        mHandler.post(new Runnable() {
16465                            @Override
16466                            public void run() {
16467                                killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
16468                            }
16469                        });
16470                    } break;
16471                }
16472            }
16473        }
16474
16475        // Synchronously write as we are taking permissions away.
16476        if (writeRuntimePermissions) {
16477            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
16478        }
16479
16480        // Synchronously write as we are taking permissions away.
16481        if (writeInstallPermissions) {
16482            mSettings.writeLPr();
16483        }
16484    }
16485
16486    /**
16487     * Remove entries from the keystore daemon. Will only remove it if the
16488     * {@code appId} is valid.
16489     */
16490    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
16491        if (appId < 0) {
16492            return;
16493        }
16494
16495        final KeyStore keyStore = KeyStore.getInstance();
16496        if (keyStore != null) {
16497            if (userId == UserHandle.USER_ALL) {
16498                for (final int individual : sUserManager.getUserIds()) {
16499                    keyStore.clearUid(UserHandle.getUid(individual, appId));
16500                }
16501            } else {
16502                keyStore.clearUid(UserHandle.getUid(userId, appId));
16503            }
16504        } else {
16505            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
16506        }
16507    }
16508
16509    @Override
16510    public void deleteApplicationCacheFiles(final String packageName,
16511            final IPackageDataObserver observer) {
16512        final int userId = UserHandle.getCallingUserId();
16513        deleteApplicationCacheFilesAsUser(packageName, userId, observer);
16514    }
16515
16516    @Override
16517    public void deleteApplicationCacheFilesAsUser(final String packageName, final int userId,
16518            final IPackageDataObserver observer) {
16519        mContext.enforceCallingOrSelfPermission(
16520                android.Manifest.permission.DELETE_CACHE_FILES, null);
16521        enforceCrossUserPermission(Binder.getCallingUid(), userId,
16522                /* requireFullPermission= */ true, /* checkShell= */ false,
16523                "delete application cache files");
16524
16525        final PackageParser.Package pkg;
16526        synchronized (mPackages) {
16527            pkg = mPackages.get(packageName);
16528        }
16529
16530        // Queue up an async operation since the package deletion may take a little while.
16531        mHandler.post(new Runnable() {
16532            public void run() {
16533                synchronized (mInstallLock) {
16534                    final int flags = StorageManager.FLAG_STORAGE_DE
16535                            | StorageManager.FLAG_STORAGE_CE;
16536                    // We're only clearing cache files, so we don't care if the
16537                    // app is unfrozen and still able to run
16538                    clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CACHE_ONLY);
16539                    clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
16540                }
16541                clearExternalStorageDataSync(packageName, userId, false);
16542                if (observer != null) {
16543                    try {
16544                        observer.onRemoveCompleted(packageName, true);
16545                    } catch (RemoteException e) {
16546                        Log.i(TAG, "Observer no longer exists.");
16547                    }
16548                }
16549            }
16550        });
16551    }
16552
16553    @Override
16554    public void getPackageSizeInfo(final String packageName, int userHandle,
16555            final IPackageStatsObserver observer) {
16556        mContext.enforceCallingOrSelfPermission(
16557                android.Manifest.permission.GET_PACKAGE_SIZE, null);
16558        if (packageName == null) {
16559            throw new IllegalArgumentException("Attempt to get size of null packageName");
16560        }
16561
16562        PackageStats stats = new PackageStats(packageName, userHandle);
16563
16564        /*
16565         * Queue up an async operation since the package measurement may take a
16566         * little while.
16567         */
16568        Message msg = mHandler.obtainMessage(INIT_COPY);
16569        msg.obj = new MeasureParams(stats, observer);
16570        mHandler.sendMessage(msg);
16571    }
16572
16573    private boolean getPackageSizeInfoLI(String packageName, int userId, PackageStats stats) {
16574        final PackageSetting ps;
16575        synchronized (mPackages) {
16576            ps = mSettings.mPackages.get(packageName);
16577            if (ps == null) {
16578                Slog.w(TAG, "Failed to find settings for " + packageName);
16579                return false;
16580            }
16581        }
16582        try {
16583            mInstaller.getAppSize(ps.volumeUuid, packageName, userId,
16584                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE,
16585                    ps.getCeDataInode(userId), ps.codePathString, stats);
16586        } catch (InstallerException e) {
16587            Slog.w(TAG, String.valueOf(e));
16588            return false;
16589        }
16590
16591        // For now, ignore code size of packages on system partition
16592        if (isSystemApp(ps) && !isUpdatedSystemApp(ps)) {
16593            stats.codeSize = 0;
16594        }
16595
16596        return true;
16597    }
16598
16599    private int getUidTargetSdkVersionLockedLPr(int uid) {
16600        Object obj = mSettings.getUserIdLPr(uid);
16601        if (obj instanceof SharedUserSetting) {
16602            final SharedUserSetting sus = (SharedUserSetting) obj;
16603            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
16604            final Iterator<PackageSetting> it = sus.packages.iterator();
16605            while (it.hasNext()) {
16606                final PackageSetting ps = it.next();
16607                if (ps.pkg != null) {
16608                    int v = ps.pkg.applicationInfo.targetSdkVersion;
16609                    if (v < vers) vers = v;
16610                }
16611            }
16612            return vers;
16613        } else if (obj instanceof PackageSetting) {
16614            final PackageSetting ps = (PackageSetting) obj;
16615            if (ps.pkg != null) {
16616                return ps.pkg.applicationInfo.targetSdkVersion;
16617            }
16618        }
16619        return Build.VERSION_CODES.CUR_DEVELOPMENT;
16620    }
16621
16622    @Override
16623    public void addPreferredActivity(IntentFilter filter, int match,
16624            ComponentName[] set, ComponentName activity, int userId) {
16625        addPreferredActivityInternal(filter, match, set, activity, true, userId,
16626                "Adding preferred");
16627    }
16628
16629    private void addPreferredActivityInternal(IntentFilter filter, int match,
16630            ComponentName[] set, ComponentName activity, boolean always, int userId,
16631            String opname) {
16632        // writer
16633        int callingUid = Binder.getCallingUid();
16634        enforceCrossUserPermission(callingUid, userId,
16635                true /* requireFullPermission */, false /* checkShell */, "add preferred activity");
16636        if (filter.countActions() == 0) {
16637            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
16638            return;
16639        }
16640        synchronized (mPackages) {
16641            if (mContext.checkCallingOrSelfPermission(
16642                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
16643                    != PackageManager.PERMISSION_GRANTED) {
16644                if (getUidTargetSdkVersionLockedLPr(callingUid)
16645                        < Build.VERSION_CODES.FROYO) {
16646                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
16647                            + callingUid);
16648                    return;
16649                }
16650                mContext.enforceCallingOrSelfPermission(
16651                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
16652            }
16653
16654            PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
16655            Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
16656                    + userId + ":");
16657            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
16658            pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
16659            scheduleWritePackageRestrictionsLocked(userId);
16660        }
16661    }
16662
16663    @Override
16664    public void replacePreferredActivity(IntentFilter filter, int match,
16665            ComponentName[] set, ComponentName activity, int userId) {
16666        if (filter.countActions() != 1) {
16667            throw new IllegalArgumentException(
16668                    "replacePreferredActivity expects filter to have only 1 action.");
16669        }
16670        if (filter.countDataAuthorities() != 0
16671                || filter.countDataPaths() != 0
16672                || filter.countDataSchemes() > 1
16673                || filter.countDataTypes() != 0) {
16674            throw new IllegalArgumentException(
16675                    "replacePreferredActivity expects filter to have no data authorities, " +
16676                    "paths, or types; and at most one scheme.");
16677        }
16678
16679        final int callingUid = Binder.getCallingUid();
16680        enforceCrossUserPermission(callingUid, userId,
16681                true /* requireFullPermission */, false /* checkShell */,
16682                "replace preferred activity");
16683        synchronized (mPackages) {
16684            if (mContext.checkCallingOrSelfPermission(
16685                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
16686                    != PackageManager.PERMISSION_GRANTED) {
16687                if (getUidTargetSdkVersionLockedLPr(callingUid)
16688                        < Build.VERSION_CODES.FROYO) {
16689                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
16690                            + Binder.getCallingUid());
16691                    return;
16692                }
16693                mContext.enforceCallingOrSelfPermission(
16694                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
16695            }
16696
16697            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
16698            if (pir != null) {
16699                // Get all of the existing entries that exactly match this filter.
16700                ArrayList<PreferredActivity> existing = pir.findFilters(filter);
16701                if (existing != null && existing.size() == 1) {
16702                    PreferredActivity cur = existing.get(0);
16703                    if (DEBUG_PREFERRED) {
16704                        Slog.i(TAG, "Checking replace of preferred:");
16705                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
16706                        if (!cur.mPref.mAlways) {
16707                            Slog.i(TAG, "  -- CUR; not mAlways!");
16708                        } else {
16709                            Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
16710                            Slog.i(TAG, "  -- CUR: mSet="
16711                                    + Arrays.toString(cur.mPref.mSetComponents));
16712                            Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
16713                            Slog.i(TAG, "  -- NEW: mMatch="
16714                                    + (match&IntentFilter.MATCH_CATEGORY_MASK));
16715                            Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
16716                            Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
16717                        }
16718                    }
16719                    if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
16720                            && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
16721                            && cur.mPref.sameSet(set)) {
16722                        // Setting the preferred activity to what it happens to be already
16723                        if (DEBUG_PREFERRED) {
16724                            Slog.i(TAG, "Replacing with same preferred activity "
16725                                    + cur.mPref.mShortComponent + " for user "
16726                                    + userId + ":");
16727                            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
16728                        }
16729                        return;
16730                    }
16731                }
16732
16733                if (existing != null) {
16734                    if (DEBUG_PREFERRED) {
16735                        Slog.i(TAG, existing.size() + " existing preferred matches for:");
16736                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
16737                    }
16738                    for (int i = 0; i < existing.size(); i++) {
16739                        PreferredActivity pa = existing.get(i);
16740                        if (DEBUG_PREFERRED) {
16741                            Slog.i(TAG, "Removing existing preferred activity "
16742                                    + pa.mPref.mComponent + ":");
16743                            pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
16744                        }
16745                        pir.removeFilter(pa);
16746                    }
16747                }
16748            }
16749            addPreferredActivityInternal(filter, match, set, activity, true, userId,
16750                    "Replacing preferred");
16751        }
16752    }
16753
16754    @Override
16755    public void clearPackagePreferredActivities(String packageName) {
16756        final int uid = Binder.getCallingUid();
16757        // writer
16758        synchronized (mPackages) {
16759            PackageParser.Package pkg = mPackages.get(packageName);
16760            if (pkg == null || pkg.applicationInfo.uid != uid) {
16761                if (mContext.checkCallingOrSelfPermission(
16762                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
16763                        != PackageManager.PERMISSION_GRANTED) {
16764                    if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid())
16765                            < Build.VERSION_CODES.FROYO) {
16766                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
16767                                + Binder.getCallingUid());
16768                        return;
16769                    }
16770                    mContext.enforceCallingOrSelfPermission(
16771                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
16772                }
16773            }
16774
16775            int user = UserHandle.getCallingUserId();
16776            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
16777                scheduleWritePackageRestrictionsLocked(user);
16778            }
16779        }
16780    }
16781
16782    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
16783    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
16784        ArrayList<PreferredActivity> removed = null;
16785        boolean changed = false;
16786        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
16787            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
16788            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
16789            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
16790                continue;
16791            }
16792            Iterator<PreferredActivity> it = pir.filterIterator();
16793            while (it.hasNext()) {
16794                PreferredActivity pa = it.next();
16795                // Mark entry for removal only if it matches the package name
16796                // and the entry is of type "always".
16797                if (packageName == null ||
16798                        (pa.mPref.mComponent.getPackageName().equals(packageName)
16799                                && pa.mPref.mAlways)) {
16800                    if (removed == null) {
16801                        removed = new ArrayList<PreferredActivity>();
16802                    }
16803                    removed.add(pa);
16804                }
16805            }
16806            if (removed != null) {
16807                for (int j=0; j<removed.size(); j++) {
16808                    PreferredActivity pa = removed.get(j);
16809                    pir.removeFilter(pa);
16810                }
16811                changed = true;
16812            }
16813        }
16814        return changed;
16815    }
16816
16817    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
16818    private void clearIntentFilterVerificationsLPw(int userId) {
16819        final int packageCount = mPackages.size();
16820        for (int i = 0; i < packageCount; i++) {
16821            PackageParser.Package pkg = mPackages.valueAt(i);
16822            clearIntentFilterVerificationsLPw(pkg.packageName, userId);
16823        }
16824    }
16825
16826    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
16827    void clearIntentFilterVerificationsLPw(String packageName, int userId) {
16828        if (userId == UserHandle.USER_ALL) {
16829            if (mSettings.removeIntentFilterVerificationLPw(packageName,
16830                    sUserManager.getUserIds())) {
16831                for (int oneUserId : sUserManager.getUserIds()) {
16832                    scheduleWritePackageRestrictionsLocked(oneUserId);
16833                }
16834            }
16835        } else {
16836            if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) {
16837                scheduleWritePackageRestrictionsLocked(userId);
16838            }
16839        }
16840    }
16841
16842    void clearDefaultBrowserIfNeeded(String packageName) {
16843        for (int oneUserId : sUserManager.getUserIds()) {
16844            String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId);
16845            if (TextUtils.isEmpty(defaultBrowserPackageName)) continue;
16846            if (packageName.equals(defaultBrowserPackageName)) {
16847                setDefaultBrowserPackageName(null, oneUserId);
16848            }
16849        }
16850    }
16851
16852    @Override
16853    public void resetApplicationPreferences(int userId) {
16854        mContext.enforceCallingOrSelfPermission(
16855                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
16856        final long identity = Binder.clearCallingIdentity();
16857        // writer
16858        try {
16859            synchronized (mPackages) {
16860                clearPackagePreferredActivitiesLPw(null, userId);
16861                mSettings.applyDefaultPreferredAppsLPw(this, userId);
16862                // TODO: We have to reset the default SMS and Phone. This requires
16863                // significant refactoring to keep all default apps in the package
16864                // manager (cleaner but more work) or have the services provide
16865                // callbacks to the package manager to request a default app reset.
16866                applyFactoryDefaultBrowserLPw(userId);
16867                clearIntentFilterVerificationsLPw(userId);
16868                primeDomainVerificationsLPw(userId);
16869                resetUserChangesToRuntimePermissionsAndFlagsLPw(userId);
16870                scheduleWritePackageRestrictionsLocked(userId);
16871            }
16872            resetNetworkPolicies(userId);
16873        } finally {
16874            Binder.restoreCallingIdentity(identity);
16875        }
16876    }
16877
16878    @Override
16879    public int getPreferredActivities(List<IntentFilter> outFilters,
16880            List<ComponentName> outActivities, String packageName) {
16881
16882        int num = 0;
16883        final int userId = UserHandle.getCallingUserId();
16884        // reader
16885        synchronized (mPackages) {
16886            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
16887            if (pir != null) {
16888                final Iterator<PreferredActivity> it = pir.filterIterator();
16889                while (it.hasNext()) {
16890                    final PreferredActivity pa = it.next();
16891                    if (packageName == null
16892                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
16893                                    && pa.mPref.mAlways)) {
16894                        if (outFilters != null) {
16895                            outFilters.add(new IntentFilter(pa));
16896                        }
16897                        if (outActivities != null) {
16898                            outActivities.add(pa.mPref.mComponent);
16899                        }
16900                    }
16901                }
16902            }
16903        }
16904
16905        return num;
16906    }
16907
16908    @Override
16909    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
16910            int userId) {
16911        int callingUid = Binder.getCallingUid();
16912        if (callingUid != Process.SYSTEM_UID) {
16913            throw new SecurityException(
16914                    "addPersistentPreferredActivity can only be run by the system");
16915        }
16916        if (filter.countActions() == 0) {
16917            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
16918            return;
16919        }
16920        synchronized (mPackages) {
16921            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
16922                    ":");
16923            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
16924            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
16925                    new PersistentPreferredActivity(filter, activity));
16926            scheduleWritePackageRestrictionsLocked(userId);
16927        }
16928    }
16929
16930    @Override
16931    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
16932        int callingUid = Binder.getCallingUid();
16933        if (callingUid != Process.SYSTEM_UID) {
16934            throw new SecurityException(
16935                    "clearPackagePersistentPreferredActivities can only be run by the system");
16936        }
16937        ArrayList<PersistentPreferredActivity> removed = null;
16938        boolean changed = false;
16939        synchronized (mPackages) {
16940            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
16941                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
16942                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
16943                        .valueAt(i);
16944                if (userId != thisUserId) {
16945                    continue;
16946                }
16947                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
16948                while (it.hasNext()) {
16949                    PersistentPreferredActivity ppa = it.next();
16950                    // Mark entry for removal only if it matches the package name.
16951                    if (ppa.mComponent.getPackageName().equals(packageName)) {
16952                        if (removed == null) {
16953                            removed = new ArrayList<PersistentPreferredActivity>();
16954                        }
16955                        removed.add(ppa);
16956                    }
16957                }
16958                if (removed != null) {
16959                    for (int j=0; j<removed.size(); j++) {
16960                        PersistentPreferredActivity ppa = removed.get(j);
16961                        ppir.removeFilter(ppa);
16962                    }
16963                    changed = true;
16964                }
16965            }
16966
16967            if (changed) {
16968                scheduleWritePackageRestrictionsLocked(userId);
16969            }
16970        }
16971    }
16972
16973    /**
16974     * Common machinery for picking apart a restored XML blob and passing
16975     * it to a caller-supplied functor to be applied to the running system.
16976     */
16977    private void restoreFromXml(XmlPullParser parser, int userId,
16978            String expectedStartTag, BlobXmlRestorer functor)
16979            throws IOException, XmlPullParserException {
16980        int type;
16981        while ((type = parser.next()) != XmlPullParser.START_TAG
16982                && type != XmlPullParser.END_DOCUMENT) {
16983        }
16984        if (type != XmlPullParser.START_TAG) {
16985            // oops didn't find a start tag?!
16986            if (DEBUG_BACKUP) {
16987                Slog.e(TAG, "Didn't find start tag during restore");
16988            }
16989            return;
16990        }
16991Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName());
16992        // this is supposed to be TAG_PREFERRED_BACKUP
16993        if (!expectedStartTag.equals(parser.getName())) {
16994            if (DEBUG_BACKUP) {
16995                Slog.e(TAG, "Found unexpected tag " + parser.getName());
16996            }
16997            return;
16998        }
16999
17000        // skip interfering stuff, then we're aligned with the backing implementation
17001        while ((type = parser.next()) == XmlPullParser.TEXT) { }
17002Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName());
17003        functor.apply(parser, userId);
17004    }
17005
17006    private interface BlobXmlRestorer {
17007        public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException;
17008    }
17009
17010    /**
17011     * Non-Binder method, support for the backup/restore mechanism: write the
17012     * full set of preferred activities in its canonical XML format.  Returns the
17013     * XML output as a byte array, or null if there is none.
17014     */
17015    @Override
17016    public byte[] getPreferredActivityBackup(int userId) {
17017        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17018            throw new SecurityException("Only the system may call getPreferredActivityBackup()");
17019        }
17020
17021        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
17022        try {
17023            final XmlSerializer serializer = new FastXmlSerializer();
17024            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
17025            serializer.startDocument(null, true);
17026            serializer.startTag(null, TAG_PREFERRED_BACKUP);
17027
17028            synchronized (mPackages) {
17029                mSettings.writePreferredActivitiesLPr(serializer, userId, true);
17030            }
17031
17032            serializer.endTag(null, TAG_PREFERRED_BACKUP);
17033            serializer.endDocument();
17034            serializer.flush();
17035        } catch (Exception e) {
17036            if (DEBUG_BACKUP) {
17037                Slog.e(TAG, "Unable to write preferred activities for backup", e);
17038            }
17039            return null;
17040        }
17041
17042        return dataStream.toByteArray();
17043    }
17044
17045    @Override
17046    public void restorePreferredActivities(byte[] backup, int userId) {
17047        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17048            throw new SecurityException("Only the system may call restorePreferredActivities()");
17049        }
17050
17051        try {
17052            final XmlPullParser parser = Xml.newPullParser();
17053            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
17054            restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP,
17055                    new BlobXmlRestorer() {
17056                        @Override
17057                        public void apply(XmlPullParser parser, int userId)
17058                                throws XmlPullParserException, IOException {
17059                            synchronized (mPackages) {
17060                                mSettings.readPreferredActivitiesLPw(parser, userId);
17061                            }
17062                        }
17063                    } );
17064        } catch (Exception e) {
17065            if (DEBUG_BACKUP) {
17066                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
17067            }
17068        }
17069    }
17070
17071    /**
17072     * Non-Binder method, support for the backup/restore mechanism: write the
17073     * default browser (etc) settings in its canonical XML format.  Returns the default
17074     * browser XML representation as a byte array, or null if there is none.
17075     */
17076    @Override
17077    public byte[] getDefaultAppsBackup(int userId) {
17078        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17079            throw new SecurityException("Only the system may call getDefaultAppsBackup()");
17080        }
17081
17082        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
17083        try {
17084            final XmlSerializer serializer = new FastXmlSerializer();
17085            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
17086            serializer.startDocument(null, true);
17087            serializer.startTag(null, TAG_DEFAULT_APPS);
17088
17089            synchronized (mPackages) {
17090                mSettings.writeDefaultAppsLPr(serializer, userId);
17091            }
17092
17093            serializer.endTag(null, TAG_DEFAULT_APPS);
17094            serializer.endDocument();
17095            serializer.flush();
17096        } catch (Exception e) {
17097            if (DEBUG_BACKUP) {
17098                Slog.e(TAG, "Unable to write default apps for backup", e);
17099            }
17100            return null;
17101        }
17102
17103        return dataStream.toByteArray();
17104    }
17105
17106    @Override
17107    public void restoreDefaultApps(byte[] backup, int userId) {
17108        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17109            throw new SecurityException("Only the system may call restoreDefaultApps()");
17110        }
17111
17112        try {
17113            final XmlPullParser parser = Xml.newPullParser();
17114            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
17115            restoreFromXml(parser, userId, TAG_DEFAULT_APPS,
17116                    new BlobXmlRestorer() {
17117                        @Override
17118                        public void apply(XmlPullParser parser, int userId)
17119                                throws XmlPullParserException, IOException {
17120                            synchronized (mPackages) {
17121                                mSettings.readDefaultAppsLPw(parser, userId);
17122                            }
17123                        }
17124                    } );
17125        } catch (Exception e) {
17126            if (DEBUG_BACKUP) {
17127                Slog.e(TAG, "Exception restoring default apps: " + e.getMessage());
17128            }
17129        }
17130    }
17131
17132    @Override
17133    public byte[] getIntentFilterVerificationBackup(int userId) {
17134        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17135            throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()");
17136        }
17137
17138        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
17139        try {
17140            final XmlSerializer serializer = new FastXmlSerializer();
17141            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
17142            serializer.startDocument(null, true);
17143            serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION);
17144
17145            synchronized (mPackages) {
17146                mSettings.writeAllDomainVerificationsLPr(serializer, userId);
17147            }
17148
17149            serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION);
17150            serializer.endDocument();
17151            serializer.flush();
17152        } catch (Exception e) {
17153            if (DEBUG_BACKUP) {
17154                Slog.e(TAG, "Unable to write default apps for backup", e);
17155            }
17156            return null;
17157        }
17158
17159        return dataStream.toByteArray();
17160    }
17161
17162    @Override
17163    public void restoreIntentFilterVerification(byte[] backup, int userId) {
17164        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17165            throw new SecurityException("Only the system may call restorePreferredActivities()");
17166        }
17167
17168        try {
17169            final XmlPullParser parser = Xml.newPullParser();
17170            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
17171            restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION,
17172                    new BlobXmlRestorer() {
17173                        @Override
17174                        public void apply(XmlPullParser parser, int userId)
17175                                throws XmlPullParserException, IOException {
17176                            synchronized (mPackages) {
17177                                mSettings.readAllDomainVerificationsLPr(parser, userId);
17178                                mSettings.writeLPr();
17179                            }
17180                        }
17181                    } );
17182        } catch (Exception e) {
17183            if (DEBUG_BACKUP) {
17184                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
17185            }
17186        }
17187    }
17188
17189    @Override
17190    public byte[] getPermissionGrantBackup(int userId) {
17191        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17192            throw new SecurityException("Only the system may call getPermissionGrantBackup()");
17193        }
17194
17195        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
17196        try {
17197            final XmlSerializer serializer = new FastXmlSerializer();
17198            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
17199            serializer.startDocument(null, true);
17200            serializer.startTag(null, TAG_PERMISSION_BACKUP);
17201
17202            synchronized (mPackages) {
17203                serializeRuntimePermissionGrantsLPr(serializer, userId);
17204            }
17205
17206            serializer.endTag(null, TAG_PERMISSION_BACKUP);
17207            serializer.endDocument();
17208            serializer.flush();
17209        } catch (Exception e) {
17210            if (DEBUG_BACKUP) {
17211                Slog.e(TAG, "Unable to write default apps for backup", e);
17212            }
17213            return null;
17214        }
17215
17216        return dataStream.toByteArray();
17217    }
17218
17219    @Override
17220    public void restorePermissionGrants(byte[] backup, int userId) {
17221        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17222            throw new SecurityException("Only the system may call restorePermissionGrants()");
17223        }
17224
17225        try {
17226            final XmlPullParser parser = Xml.newPullParser();
17227            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
17228            restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP,
17229                    new BlobXmlRestorer() {
17230                        @Override
17231                        public void apply(XmlPullParser parser, int userId)
17232                                throws XmlPullParserException, IOException {
17233                            synchronized (mPackages) {
17234                                processRestoredPermissionGrantsLPr(parser, userId);
17235                            }
17236                        }
17237                    } );
17238        } catch (Exception e) {
17239            if (DEBUG_BACKUP) {
17240                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
17241            }
17242        }
17243    }
17244
17245    private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId)
17246            throws IOException {
17247        serializer.startTag(null, TAG_ALL_GRANTS);
17248
17249        final int N = mSettings.mPackages.size();
17250        for (int i = 0; i < N; i++) {
17251            final PackageSetting ps = mSettings.mPackages.valueAt(i);
17252            boolean pkgGrantsKnown = false;
17253
17254            PermissionsState packagePerms = ps.getPermissionsState();
17255
17256            for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) {
17257                final int grantFlags = state.getFlags();
17258                // only look at grants that are not system/policy fixed
17259                if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) {
17260                    final boolean isGranted = state.isGranted();
17261                    // And only back up the user-twiddled state bits
17262                    if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) {
17263                        final String packageName = mSettings.mPackages.keyAt(i);
17264                        if (!pkgGrantsKnown) {
17265                            serializer.startTag(null, TAG_GRANT);
17266                            serializer.attribute(null, ATTR_PACKAGE_NAME, packageName);
17267                            pkgGrantsKnown = true;
17268                        }
17269
17270                        final boolean userSet =
17271                                (grantFlags & FLAG_PERMISSION_USER_SET) != 0;
17272                        final boolean userFixed =
17273                                (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0;
17274                        final boolean revoke =
17275                                (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0;
17276
17277                        serializer.startTag(null, TAG_PERMISSION);
17278                        serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName());
17279                        if (isGranted) {
17280                            serializer.attribute(null, ATTR_IS_GRANTED, "true");
17281                        }
17282                        if (userSet) {
17283                            serializer.attribute(null, ATTR_USER_SET, "true");
17284                        }
17285                        if (userFixed) {
17286                            serializer.attribute(null, ATTR_USER_FIXED, "true");
17287                        }
17288                        if (revoke) {
17289                            serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true");
17290                        }
17291                        serializer.endTag(null, TAG_PERMISSION);
17292                    }
17293                }
17294            }
17295
17296            if (pkgGrantsKnown) {
17297                serializer.endTag(null, TAG_GRANT);
17298            }
17299        }
17300
17301        serializer.endTag(null, TAG_ALL_GRANTS);
17302    }
17303
17304    private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId)
17305            throws XmlPullParserException, IOException {
17306        String pkgName = null;
17307        int outerDepth = parser.getDepth();
17308        int type;
17309        while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
17310                && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
17311            if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
17312                continue;
17313            }
17314
17315            final String tagName = parser.getName();
17316            if (tagName.equals(TAG_GRANT)) {
17317                pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME);
17318                if (DEBUG_BACKUP) {
17319                    Slog.v(TAG, "+++ Restoring grants for package " + pkgName);
17320                }
17321            } else if (tagName.equals(TAG_PERMISSION)) {
17322
17323                final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED));
17324                final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME);
17325
17326                int newFlagSet = 0;
17327                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) {
17328                    newFlagSet |= FLAG_PERMISSION_USER_SET;
17329                }
17330                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) {
17331                    newFlagSet |= FLAG_PERMISSION_USER_FIXED;
17332                }
17333                if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) {
17334                    newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE;
17335                }
17336                if (DEBUG_BACKUP) {
17337                    Slog.v(TAG, "  + Restoring grant: pkg=" + pkgName + " perm=" + permName
17338                            + " granted=" + isGranted + " bits=0x" + Integer.toHexString(newFlagSet));
17339                }
17340                final PackageSetting ps = mSettings.mPackages.get(pkgName);
17341                if (ps != null) {
17342                    // Already installed so we apply the grant immediately
17343                    if (DEBUG_BACKUP) {
17344                        Slog.v(TAG, "        + already installed; applying");
17345                    }
17346                    PermissionsState perms = ps.getPermissionsState();
17347                    BasePermission bp = mSettings.mPermissions.get(permName);
17348                    if (bp != null) {
17349                        if (isGranted) {
17350                            perms.grantRuntimePermission(bp, userId);
17351                        }
17352                        if (newFlagSet != 0) {
17353                            perms.updatePermissionFlags(bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet);
17354                        }
17355                    }
17356                } else {
17357                    // Need to wait for post-restore install to apply the grant
17358                    if (DEBUG_BACKUP) {
17359                        Slog.v(TAG, "        - not yet installed; saving for later");
17360                    }
17361                    mSettings.processRestoredPermissionGrantLPr(pkgName, permName,
17362                            isGranted, newFlagSet, userId);
17363                }
17364            } else {
17365                PackageManagerService.reportSettingsProblem(Log.WARN,
17366                        "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName);
17367                XmlUtils.skipCurrentTag(parser);
17368            }
17369        }
17370
17371        scheduleWriteSettingsLocked();
17372        mSettings.writeRuntimePermissionsForUserLPr(userId, false);
17373    }
17374
17375    @Override
17376    public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
17377            int sourceUserId, int targetUserId, int flags) {
17378        mContext.enforceCallingOrSelfPermission(
17379                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
17380        int callingUid = Binder.getCallingUid();
17381        enforceOwnerRights(ownerPackage, callingUid);
17382        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
17383        if (intentFilter.countActions() == 0) {
17384            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
17385            return;
17386        }
17387        synchronized (mPackages) {
17388            CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter,
17389                    ownerPackage, targetUserId, flags);
17390            CrossProfileIntentResolver resolver =
17391                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
17392            ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter);
17393            // We have all those whose filter is equal. Now checking if the rest is equal as well.
17394            if (existing != null) {
17395                int size = existing.size();
17396                for (int i = 0; i < size; i++) {
17397                    if (newFilter.equalsIgnoreFilter(existing.get(i))) {
17398                        return;
17399                    }
17400                }
17401            }
17402            resolver.addFilter(newFilter);
17403            scheduleWritePackageRestrictionsLocked(sourceUserId);
17404        }
17405    }
17406
17407    @Override
17408    public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) {
17409        mContext.enforceCallingOrSelfPermission(
17410                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
17411        int callingUid = Binder.getCallingUid();
17412        enforceOwnerRights(ownerPackage, callingUid);
17413        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
17414        synchronized (mPackages) {
17415            CrossProfileIntentResolver resolver =
17416                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
17417            ArraySet<CrossProfileIntentFilter> set =
17418                    new ArraySet<CrossProfileIntentFilter>(resolver.filterSet());
17419            for (CrossProfileIntentFilter filter : set) {
17420                if (filter.getOwnerPackage().equals(ownerPackage)) {
17421                    resolver.removeFilter(filter);
17422                }
17423            }
17424            scheduleWritePackageRestrictionsLocked(sourceUserId);
17425        }
17426    }
17427
17428    // Enforcing that callingUid is owning pkg on userId
17429    private void enforceOwnerRights(String pkg, int callingUid) {
17430        // The system owns everything.
17431        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
17432            return;
17433        }
17434        int callingUserId = UserHandle.getUserId(callingUid);
17435        PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
17436        if (pi == null) {
17437            throw new IllegalArgumentException("Unknown package " + pkg + " on user "
17438                    + callingUserId);
17439        }
17440        if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
17441            throw new SecurityException("Calling uid " + callingUid
17442                    + " does not own package " + pkg);
17443        }
17444    }
17445
17446    @Override
17447    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
17448        return getHomeActivitiesAsUser(allHomeCandidates, UserHandle.getCallingUserId());
17449    }
17450
17451    private Intent getHomeIntent() {
17452        Intent intent = new Intent(Intent.ACTION_MAIN);
17453        intent.addCategory(Intent.CATEGORY_HOME);
17454        return intent;
17455    }
17456
17457    private IntentFilter getHomeFilter() {
17458        IntentFilter filter = new IntentFilter(Intent.ACTION_MAIN);
17459        filter.addCategory(Intent.CATEGORY_HOME);
17460        filter.addCategory(Intent.CATEGORY_DEFAULT);
17461        return filter;
17462    }
17463
17464    ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
17465            int userId) {
17466        Intent intent  = getHomeIntent();
17467        List<ResolveInfo> list = queryIntentActivitiesInternal(intent, null,
17468                PackageManager.GET_META_DATA, userId);
17469        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
17470                true, false, false, userId);
17471
17472        allHomeCandidates.clear();
17473        if (list != null) {
17474            for (ResolveInfo ri : list) {
17475                allHomeCandidates.add(ri);
17476            }
17477        }
17478        return (preferred == null || preferred.activityInfo == null)
17479                ? null
17480                : new ComponentName(preferred.activityInfo.packageName,
17481                        preferred.activityInfo.name);
17482    }
17483
17484    @Override
17485    public void setHomeActivity(ComponentName comp, int userId) {
17486        ArrayList<ResolveInfo> homeActivities = new ArrayList<>();
17487        getHomeActivitiesAsUser(homeActivities, userId);
17488
17489        boolean found = false;
17490
17491        final int size = homeActivities.size();
17492        final ComponentName[] set = new ComponentName[size];
17493        for (int i = 0; i < size; i++) {
17494            final ResolveInfo candidate = homeActivities.get(i);
17495            final ActivityInfo info = candidate.activityInfo;
17496            final ComponentName activityName = new ComponentName(info.packageName, info.name);
17497            set[i] = activityName;
17498            if (!found && activityName.equals(comp)) {
17499                found = true;
17500            }
17501        }
17502        if (!found) {
17503            throw new IllegalArgumentException("Component " + comp + " cannot be home on user "
17504                    + userId);
17505        }
17506        replacePreferredActivity(getHomeFilter(), IntentFilter.MATCH_CATEGORY_EMPTY,
17507                set, comp, userId);
17508    }
17509
17510    private @Nullable String getSetupWizardPackageName() {
17511        final Intent intent = new Intent(Intent.ACTION_MAIN);
17512        intent.addCategory(Intent.CATEGORY_SETUP_WIZARD);
17513
17514        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
17515                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
17516                        | MATCH_DISABLED_COMPONENTS,
17517                UserHandle.myUserId());
17518        if (matches.size() == 1) {
17519            return matches.get(0).getComponentInfo().packageName;
17520        } else {
17521            Slog.e(TAG, "There should probably be exactly one setup wizard; found " + matches.size()
17522                    + ": matches=" + matches);
17523            return null;
17524        }
17525    }
17526
17527    @Override
17528    public void setApplicationEnabledSetting(String appPackageName,
17529            int newState, int flags, int userId, String callingPackage) {
17530        if (!sUserManager.exists(userId)) return;
17531        if (callingPackage == null) {
17532            callingPackage = Integer.toString(Binder.getCallingUid());
17533        }
17534        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
17535    }
17536
17537    @Override
17538    public void setComponentEnabledSetting(ComponentName componentName,
17539            int newState, int flags, int userId) {
17540        if (!sUserManager.exists(userId)) return;
17541        setEnabledSetting(componentName.getPackageName(),
17542                componentName.getClassName(), newState, flags, userId, null);
17543    }
17544
17545    private void setEnabledSetting(final String packageName, String className, int newState,
17546            final int flags, int userId, String callingPackage) {
17547        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
17548              || newState == COMPONENT_ENABLED_STATE_ENABLED
17549              || newState == COMPONENT_ENABLED_STATE_DISABLED
17550              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
17551              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
17552            throw new IllegalArgumentException("Invalid new component state: "
17553                    + newState);
17554        }
17555        PackageSetting pkgSetting;
17556        final int uid = Binder.getCallingUid();
17557        final int permission;
17558        if (uid == Process.SYSTEM_UID) {
17559            permission = PackageManager.PERMISSION_GRANTED;
17560        } else {
17561            permission = mContext.checkCallingOrSelfPermission(
17562                    android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
17563        }
17564        enforceCrossUserPermission(uid, userId,
17565                false /* requireFullPermission */, true /* checkShell */, "set enabled");
17566        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
17567        boolean sendNow = false;
17568        boolean isApp = (className == null);
17569        String componentName = isApp ? packageName : className;
17570        int packageUid = -1;
17571        ArrayList<String> components;
17572
17573        // writer
17574        synchronized (mPackages) {
17575            pkgSetting = mSettings.mPackages.get(packageName);
17576            if (pkgSetting == null) {
17577                if (className == null) {
17578                    throw new IllegalArgumentException("Unknown package: " + packageName);
17579                }
17580                throw new IllegalArgumentException(
17581                        "Unknown component: " + packageName + "/" + className);
17582            }
17583        }
17584
17585        // Limit who can change which apps
17586        if (!UserHandle.isSameApp(uid, pkgSetting.appId)) {
17587            // Don't allow apps that don't have permission to modify other apps
17588            if (!allowedByPermission) {
17589                throw new SecurityException(
17590                        "Permission Denial: attempt to change component state from pid="
17591                        + Binder.getCallingPid()
17592                        + ", uid=" + uid + ", package uid=" + pkgSetting.appId);
17593            }
17594            // Don't allow changing profile and device owners.
17595            if (mProtectedPackages.canPackageStateBeChanged(userId, packageName)) {
17596                throw new SecurityException("Cannot disable a device owner or a profile owner");
17597            }
17598        }
17599
17600        synchronized (mPackages) {
17601            if (uid == Process.SHELL_UID) {
17602                // Shell can only change whole packages between ENABLED and DISABLED_USER states
17603                int oldState = pkgSetting.getEnabled(userId);
17604                if (className == null
17605                    &&
17606                    (oldState == COMPONENT_ENABLED_STATE_DISABLED_USER
17607                     || oldState == COMPONENT_ENABLED_STATE_DEFAULT
17608                     || oldState == COMPONENT_ENABLED_STATE_ENABLED)
17609                    &&
17610                    (newState == COMPONENT_ENABLED_STATE_DISABLED_USER
17611                     || newState == COMPONENT_ENABLED_STATE_DEFAULT
17612                     || newState == COMPONENT_ENABLED_STATE_ENABLED)) {
17613                    // ok
17614                } else {
17615                    throw new SecurityException(
17616                            "Shell cannot change component state for " + packageName + "/"
17617                            + className + " to " + newState);
17618                }
17619            }
17620            if (className == null) {
17621                // We're dealing with an application/package level state change
17622                if (pkgSetting.getEnabled(userId) == newState) {
17623                    // Nothing to do
17624                    return;
17625                }
17626                if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
17627                    || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
17628                    // Don't care about who enables an app.
17629                    callingPackage = null;
17630                }
17631                pkgSetting.setEnabled(newState, userId, callingPackage);
17632                // pkgSetting.pkg.mSetEnabled = newState;
17633            } else {
17634                // We're dealing with a component level state change
17635                // First, verify that this is a valid class name.
17636                PackageParser.Package pkg = pkgSetting.pkg;
17637                if (pkg == null || !pkg.hasComponentClassName(className)) {
17638                    if (pkg != null &&
17639                            pkg.applicationInfo.targetSdkVersion >=
17640                                    Build.VERSION_CODES.JELLY_BEAN) {
17641                        throw new IllegalArgumentException("Component class " + className
17642                                + " does not exist in " + packageName);
17643                    } else {
17644                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
17645                                + className + " does not exist in " + packageName);
17646                    }
17647                }
17648                switch (newState) {
17649                case COMPONENT_ENABLED_STATE_ENABLED:
17650                    if (!pkgSetting.enableComponentLPw(className, userId)) {
17651                        return;
17652                    }
17653                    break;
17654                case COMPONENT_ENABLED_STATE_DISABLED:
17655                    if (!pkgSetting.disableComponentLPw(className, userId)) {
17656                        return;
17657                    }
17658                    break;
17659                case COMPONENT_ENABLED_STATE_DEFAULT:
17660                    if (!pkgSetting.restoreComponentLPw(className, userId)) {
17661                        return;
17662                    }
17663                    break;
17664                default:
17665                    Slog.e(TAG, "Invalid new component state: " + newState);
17666                    return;
17667                }
17668            }
17669            scheduleWritePackageRestrictionsLocked(userId);
17670            components = mPendingBroadcasts.get(userId, packageName);
17671            final boolean newPackage = components == null;
17672            if (newPackage) {
17673                components = new ArrayList<String>();
17674            }
17675            if (!components.contains(componentName)) {
17676                components.add(componentName);
17677            }
17678            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
17679                sendNow = true;
17680                // Purge entry from pending broadcast list if another one exists already
17681                // since we are sending one right away.
17682                mPendingBroadcasts.remove(userId, packageName);
17683            } else {
17684                if (newPackage) {
17685                    mPendingBroadcasts.put(userId, packageName, components);
17686                }
17687                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
17688                    // Schedule a message
17689                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
17690                }
17691            }
17692        }
17693
17694        long callingId = Binder.clearCallingIdentity();
17695        try {
17696            if (sendNow) {
17697                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
17698                sendPackageChangedBroadcast(packageName,
17699                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
17700            }
17701        } finally {
17702            Binder.restoreCallingIdentity(callingId);
17703        }
17704    }
17705
17706    @Override
17707    public void flushPackageRestrictionsAsUser(int userId) {
17708        if (!sUserManager.exists(userId)) {
17709            return;
17710        }
17711        enforceCrossUserPermission(Binder.getCallingUid(), userId, false /* requireFullPermission*/,
17712                false /* checkShell */, "flushPackageRestrictions");
17713        synchronized (mPackages) {
17714            mSettings.writePackageRestrictionsLPr(userId);
17715            mDirtyUsers.remove(userId);
17716            if (mDirtyUsers.isEmpty()) {
17717                mHandler.removeMessages(WRITE_PACKAGE_RESTRICTIONS);
17718            }
17719        }
17720    }
17721
17722    private void sendPackageChangedBroadcast(String packageName,
17723            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
17724        if (DEBUG_INSTALL)
17725            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
17726                    + componentNames);
17727        Bundle extras = new Bundle(4);
17728        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
17729        String nameList[] = new String[componentNames.size()];
17730        componentNames.toArray(nameList);
17731        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
17732        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
17733        extras.putInt(Intent.EXTRA_UID, packageUid);
17734        // If this is not reporting a change of the overall package, then only send it
17735        // to registered receivers.  We don't want to launch a swath of apps for every
17736        // little component state change.
17737        final int flags = !componentNames.contains(packageName)
17738                ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0;
17739        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, flags, null, null,
17740                new int[] {UserHandle.getUserId(packageUid)});
17741    }
17742
17743    @Override
17744    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
17745        if (!sUserManager.exists(userId)) return;
17746        final int uid = Binder.getCallingUid();
17747        final int permission = mContext.checkCallingOrSelfPermission(
17748                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
17749        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
17750        enforceCrossUserPermission(uid, userId,
17751                true /* requireFullPermission */, true /* checkShell */, "stop package");
17752        // writer
17753        synchronized (mPackages) {
17754            if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped,
17755                    allowedByPermission, uid, userId)) {
17756                scheduleWritePackageRestrictionsLocked(userId);
17757            }
17758        }
17759    }
17760
17761    @Override
17762    public String getInstallerPackageName(String packageName) {
17763        // reader
17764        synchronized (mPackages) {
17765            return mSettings.getInstallerPackageNameLPr(packageName);
17766        }
17767    }
17768
17769    public boolean isOrphaned(String packageName) {
17770        // reader
17771        synchronized (mPackages) {
17772            return mSettings.isOrphaned(packageName);
17773        }
17774    }
17775
17776    @Override
17777    public int getApplicationEnabledSetting(String packageName, int userId) {
17778        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
17779        int uid = Binder.getCallingUid();
17780        enforceCrossUserPermission(uid, userId,
17781                false /* requireFullPermission */, false /* checkShell */, "get enabled");
17782        // reader
17783        synchronized (mPackages) {
17784            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
17785        }
17786    }
17787
17788    @Override
17789    public int getComponentEnabledSetting(ComponentName componentName, int userId) {
17790        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
17791        int uid = Binder.getCallingUid();
17792        enforceCrossUserPermission(uid, userId,
17793                false /* requireFullPermission */, false /* checkShell */, "get component enabled");
17794        // reader
17795        synchronized (mPackages) {
17796            return mSettings.getComponentEnabledSettingLPr(componentName, userId);
17797        }
17798    }
17799
17800    @Override
17801    public void enterSafeMode() {
17802        enforceSystemOrRoot("Only the system can request entering safe mode");
17803
17804        if (!mSystemReady) {
17805            mSafeMode = true;
17806        }
17807    }
17808
17809    @Override
17810    public void systemReady() {
17811        mSystemReady = true;
17812
17813        // Read the compatibilty setting when the system is ready.
17814        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
17815                mContext.getContentResolver(),
17816                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
17817        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
17818        if (DEBUG_SETTINGS) {
17819            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
17820        }
17821
17822        int[] grantPermissionsUserIds = EMPTY_INT_ARRAY;
17823
17824        synchronized (mPackages) {
17825            // Verify that all of the preferred activity components actually
17826            // exist.  It is possible for applications to be updated and at
17827            // that point remove a previously declared activity component that
17828            // had been set as a preferred activity.  We try to clean this up
17829            // the next time we encounter that preferred activity, but it is
17830            // possible for the user flow to never be able to return to that
17831            // situation so here we do a sanity check to make sure we haven't
17832            // left any junk around.
17833            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
17834            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
17835                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
17836                removed.clear();
17837                for (PreferredActivity pa : pir.filterSet()) {
17838                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
17839                        removed.add(pa);
17840                    }
17841                }
17842                if (removed.size() > 0) {
17843                    for (int r=0; r<removed.size(); r++) {
17844                        PreferredActivity pa = removed.get(r);
17845                        Slog.w(TAG, "Removing dangling preferred activity: "
17846                                + pa.mPref.mComponent);
17847                        pir.removeFilter(pa);
17848                    }
17849                    mSettings.writePackageRestrictionsLPr(
17850                            mSettings.mPreferredActivities.keyAt(i));
17851                }
17852            }
17853
17854            for (int userId : UserManagerService.getInstance().getUserIds()) {
17855                if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) {
17856                    grantPermissionsUserIds = ArrayUtils.appendInt(
17857                            grantPermissionsUserIds, userId);
17858                }
17859            }
17860        }
17861        sUserManager.systemReady();
17862
17863        // If we upgraded grant all default permissions before kicking off.
17864        for (int userId : grantPermissionsUserIds) {
17865            mDefaultPermissionPolicy.grantDefaultPermissions(userId);
17866        }
17867
17868        // Kick off any messages waiting for system ready
17869        if (mPostSystemReadyMessages != null) {
17870            for (Message msg : mPostSystemReadyMessages) {
17871                msg.sendToTarget();
17872            }
17873            mPostSystemReadyMessages = null;
17874        }
17875
17876        // Watch for external volumes that come and go over time
17877        final StorageManager storage = mContext.getSystemService(StorageManager.class);
17878        storage.registerListener(mStorageListener);
17879
17880        mInstallerService.systemReady();
17881        mPackageDexOptimizer.systemReady();
17882
17883        MountServiceInternal mountServiceInternal = LocalServices.getService(
17884                MountServiceInternal.class);
17885        mountServiceInternal.addExternalStoragePolicy(
17886                new MountServiceInternal.ExternalStorageMountPolicy() {
17887            @Override
17888            public int getMountMode(int uid, String packageName) {
17889                if (Process.isIsolated(uid)) {
17890                    return Zygote.MOUNT_EXTERNAL_NONE;
17891                }
17892                if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) {
17893                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
17894                }
17895                if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
17896                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
17897                }
17898                if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
17899                    return Zygote.MOUNT_EXTERNAL_READ;
17900                }
17901                return Zygote.MOUNT_EXTERNAL_WRITE;
17902            }
17903
17904            @Override
17905            public boolean hasExternalStorage(int uid, String packageName) {
17906                return true;
17907            }
17908        });
17909
17910        // Now that we're mostly running, clean up stale users and apps
17911        reconcileUsers(StorageManager.UUID_PRIVATE_INTERNAL);
17912        reconcileApps(StorageManager.UUID_PRIVATE_INTERNAL);
17913    }
17914
17915    @Override
17916    public boolean isSafeMode() {
17917        return mSafeMode;
17918    }
17919
17920    @Override
17921    public boolean hasSystemUidErrors() {
17922        return mHasSystemUidErrors;
17923    }
17924
17925    static String arrayToString(int[] array) {
17926        StringBuffer buf = new StringBuffer(128);
17927        buf.append('[');
17928        if (array != null) {
17929            for (int i=0; i<array.length; i++) {
17930                if (i > 0) buf.append(", ");
17931                buf.append(array[i]);
17932            }
17933        }
17934        buf.append(']');
17935        return buf.toString();
17936    }
17937
17938    static class DumpState {
17939        public static final int DUMP_LIBS = 1 << 0;
17940        public static final int DUMP_FEATURES = 1 << 1;
17941        public static final int DUMP_ACTIVITY_RESOLVERS = 1 << 2;
17942        public static final int DUMP_SERVICE_RESOLVERS = 1 << 3;
17943        public static final int DUMP_RECEIVER_RESOLVERS = 1 << 4;
17944        public static final int DUMP_CONTENT_RESOLVERS = 1 << 5;
17945        public static final int DUMP_PERMISSIONS = 1 << 6;
17946        public static final int DUMP_PACKAGES = 1 << 7;
17947        public static final int DUMP_SHARED_USERS = 1 << 8;
17948        public static final int DUMP_MESSAGES = 1 << 9;
17949        public static final int DUMP_PROVIDERS = 1 << 10;
17950        public static final int DUMP_VERIFIERS = 1 << 11;
17951        public static final int DUMP_PREFERRED = 1 << 12;
17952        public static final int DUMP_PREFERRED_XML = 1 << 13;
17953        public static final int DUMP_KEYSETS = 1 << 14;
17954        public static final int DUMP_VERSION = 1 << 15;
17955        public static final int DUMP_INSTALLS = 1 << 16;
17956        public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 17;
17957        public static final int DUMP_DOMAIN_PREFERRED = 1 << 18;
17958        public static final int DUMP_FROZEN = 1 << 19;
17959        public static final int DUMP_DEXOPT = 1 << 20;
17960        public static final int DUMP_COMPILER_STATS = 1 << 21;
17961
17962        public static final int OPTION_SHOW_FILTERS = 1 << 0;
17963
17964        private int mTypes;
17965
17966        private int mOptions;
17967
17968        private boolean mTitlePrinted;
17969
17970        private SharedUserSetting mSharedUser;
17971
17972        public boolean isDumping(int type) {
17973            if (mTypes == 0 && type != DUMP_PREFERRED_XML) {
17974                return true;
17975            }
17976
17977            return (mTypes & type) != 0;
17978        }
17979
17980        public void setDump(int type) {
17981            mTypes |= type;
17982        }
17983
17984        public boolean isOptionEnabled(int option) {
17985            return (mOptions & option) != 0;
17986        }
17987
17988        public void setOptionEnabled(int option) {
17989            mOptions |= option;
17990        }
17991
17992        public boolean onTitlePrinted() {
17993            final boolean printed = mTitlePrinted;
17994            mTitlePrinted = true;
17995            return printed;
17996        }
17997
17998        public boolean getTitlePrinted() {
17999            return mTitlePrinted;
18000        }
18001
18002        public void setTitlePrinted(boolean enabled) {
18003            mTitlePrinted = enabled;
18004        }
18005
18006        public SharedUserSetting getSharedUser() {
18007            return mSharedUser;
18008        }
18009
18010        public void setSharedUser(SharedUserSetting user) {
18011            mSharedUser = user;
18012        }
18013    }
18014
18015    @Override
18016    public void onShellCommand(FileDescriptor in, FileDescriptor out,
18017            FileDescriptor err, String[] args, ResultReceiver resultReceiver) {
18018        (new PackageManagerShellCommand(this)).exec(
18019                this, in, out, err, args, resultReceiver);
18020    }
18021
18022    @Override
18023    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
18024        if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
18025                != PackageManager.PERMISSION_GRANTED) {
18026            pw.println("Permission Denial: can't dump ActivityManager from from pid="
18027                    + Binder.getCallingPid()
18028                    + ", uid=" + Binder.getCallingUid()
18029                    + " without permission "
18030                    + android.Manifest.permission.DUMP);
18031            return;
18032        }
18033
18034        DumpState dumpState = new DumpState();
18035        boolean fullPreferred = false;
18036        boolean checkin = false;
18037
18038        String packageName = null;
18039        ArraySet<String> permissionNames = null;
18040
18041        int opti = 0;
18042        while (opti < args.length) {
18043            String opt = args[opti];
18044            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
18045                break;
18046            }
18047            opti++;
18048
18049            if ("-a".equals(opt)) {
18050                // Right now we only know how to print all.
18051            } else if ("-h".equals(opt)) {
18052                pw.println("Package manager dump options:");
18053                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
18054                pw.println("    --checkin: dump for a checkin");
18055                pw.println("    -f: print details of intent filters");
18056                pw.println("    -h: print this help");
18057                pw.println("  cmd may be one of:");
18058                pw.println("    l[ibraries]: list known shared libraries");
18059                pw.println("    f[eatures]: list device features");
18060                pw.println("    k[eysets]: print known keysets");
18061                pw.println("    r[esolvers] [activity|service|receiver|content]: dump intent resolvers");
18062                pw.println("    perm[issions]: dump permissions");
18063                pw.println("    permission [name ...]: dump declaration and use of given permission");
18064                pw.println("    pref[erred]: print preferred package settings");
18065                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
18066                pw.println("    prov[iders]: dump content providers");
18067                pw.println("    p[ackages]: dump installed packages");
18068                pw.println("    s[hared-users]: dump shared user IDs");
18069                pw.println("    m[essages]: print collected runtime messages");
18070                pw.println("    v[erifiers]: print package verifier info");
18071                pw.println("    d[omain-preferred-apps]: print domains preferred apps");
18072                pw.println("    i[ntent-filter-verifiers]|ifv: print intent filter verifier info");
18073                pw.println("    version: print database version info");
18074                pw.println("    write: write current settings now");
18075                pw.println("    installs: details about install sessions");
18076                pw.println("    check-permission <permission> <package> [<user>]: does pkg hold perm?");
18077                pw.println("    dexopt: dump dexopt state");
18078                pw.println("    compiler-stats: dump compiler statistics");
18079                pw.println("    <package.name>: info about given package");
18080                return;
18081            } else if ("--checkin".equals(opt)) {
18082                checkin = true;
18083            } else if ("-f".equals(opt)) {
18084                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
18085            } else {
18086                pw.println("Unknown argument: " + opt + "; use -h for help");
18087            }
18088        }
18089
18090        // Is the caller requesting to dump a particular piece of data?
18091        if (opti < args.length) {
18092            String cmd = args[opti];
18093            opti++;
18094            // Is this a package name?
18095            if ("android".equals(cmd) || cmd.contains(".")) {
18096                packageName = cmd;
18097                // When dumping a single package, we always dump all of its
18098                // filter information since the amount of data will be reasonable.
18099                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
18100            } else if ("check-permission".equals(cmd)) {
18101                if (opti >= args.length) {
18102                    pw.println("Error: check-permission missing permission argument");
18103                    return;
18104                }
18105                String perm = args[opti];
18106                opti++;
18107                if (opti >= args.length) {
18108                    pw.println("Error: check-permission missing package argument");
18109                    return;
18110                }
18111                String pkg = args[opti];
18112                opti++;
18113                int user = UserHandle.getUserId(Binder.getCallingUid());
18114                if (opti < args.length) {
18115                    try {
18116                        user = Integer.parseInt(args[opti]);
18117                    } catch (NumberFormatException e) {
18118                        pw.println("Error: check-permission user argument is not a number: "
18119                                + args[opti]);
18120                        return;
18121                    }
18122                }
18123                pw.println(checkPermission(perm, pkg, user));
18124                return;
18125            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
18126                dumpState.setDump(DumpState.DUMP_LIBS);
18127            } else if ("f".equals(cmd) || "features".equals(cmd)) {
18128                dumpState.setDump(DumpState.DUMP_FEATURES);
18129            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
18130                if (opti >= args.length) {
18131                    dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS
18132                            | DumpState.DUMP_SERVICE_RESOLVERS
18133                            | DumpState.DUMP_RECEIVER_RESOLVERS
18134                            | DumpState.DUMP_CONTENT_RESOLVERS);
18135                } else {
18136                    while (opti < args.length) {
18137                        String name = args[opti];
18138                        if ("a".equals(name) || "activity".equals(name)) {
18139                            dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS);
18140                        } else if ("s".equals(name) || "service".equals(name)) {
18141                            dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS);
18142                        } else if ("r".equals(name) || "receiver".equals(name)) {
18143                            dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS);
18144                        } else if ("c".equals(name) || "content".equals(name)) {
18145                            dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS);
18146                        } else {
18147                            pw.println("Error: unknown resolver table type: " + name);
18148                            return;
18149                        }
18150                        opti++;
18151                    }
18152                }
18153            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
18154                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
18155            } else if ("permission".equals(cmd)) {
18156                if (opti >= args.length) {
18157                    pw.println("Error: permission requires permission name");
18158                    return;
18159                }
18160                permissionNames = new ArraySet<>();
18161                while (opti < args.length) {
18162                    permissionNames.add(args[opti]);
18163                    opti++;
18164                }
18165                dumpState.setDump(DumpState.DUMP_PERMISSIONS
18166                        | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS);
18167            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
18168                dumpState.setDump(DumpState.DUMP_PREFERRED);
18169            } else if ("preferred-xml".equals(cmd)) {
18170                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
18171                if (opti < args.length && "--full".equals(args[opti])) {
18172                    fullPreferred = true;
18173                    opti++;
18174                }
18175            } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) {
18176                dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED);
18177            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
18178                dumpState.setDump(DumpState.DUMP_PACKAGES);
18179            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
18180                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
18181            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
18182                dumpState.setDump(DumpState.DUMP_PROVIDERS);
18183            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
18184                dumpState.setDump(DumpState.DUMP_MESSAGES);
18185            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
18186                dumpState.setDump(DumpState.DUMP_VERIFIERS);
18187            } else if ("i".equals(cmd) || "ifv".equals(cmd)
18188                    || "intent-filter-verifiers".equals(cmd)) {
18189                dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS);
18190            } else if ("version".equals(cmd)) {
18191                dumpState.setDump(DumpState.DUMP_VERSION);
18192            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
18193                dumpState.setDump(DumpState.DUMP_KEYSETS);
18194            } else if ("installs".equals(cmd)) {
18195                dumpState.setDump(DumpState.DUMP_INSTALLS);
18196            } else if ("frozen".equals(cmd)) {
18197                dumpState.setDump(DumpState.DUMP_FROZEN);
18198            } else if ("dexopt".equals(cmd)) {
18199                dumpState.setDump(DumpState.DUMP_DEXOPT);
18200            } else if ("compiler-stats".equals(cmd)) {
18201                dumpState.setDump(DumpState.DUMP_COMPILER_STATS);
18202            } else if ("write".equals(cmd)) {
18203                synchronized (mPackages) {
18204                    mSettings.writeLPr();
18205                    pw.println("Settings written.");
18206                    return;
18207                }
18208            }
18209        }
18210
18211        if (checkin) {
18212            pw.println("vers,1");
18213        }
18214
18215        // reader
18216        synchronized (mPackages) {
18217            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
18218                if (!checkin) {
18219                    if (dumpState.onTitlePrinted())
18220                        pw.println();
18221                    pw.println("Database versions:");
18222                    mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, "  "));
18223                }
18224            }
18225
18226            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
18227                if (!checkin) {
18228                    if (dumpState.onTitlePrinted())
18229                        pw.println();
18230                    pw.println("Verifiers:");
18231                    pw.print("  Required: ");
18232                    pw.print(mRequiredVerifierPackage);
18233                    pw.print(" (uid=");
18234                    pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
18235                            UserHandle.USER_SYSTEM));
18236                    pw.println(")");
18237                } else if (mRequiredVerifierPackage != null) {
18238                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
18239                    pw.print(",");
18240                    pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
18241                            UserHandle.USER_SYSTEM));
18242                }
18243            }
18244
18245            if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) &&
18246                    packageName == null) {
18247                if (mIntentFilterVerifierComponent != null) {
18248                    String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
18249                    if (!checkin) {
18250                        if (dumpState.onTitlePrinted())
18251                            pw.println();
18252                        pw.println("Intent Filter Verifier:");
18253                        pw.print("  Using: ");
18254                        pw.print(verifierPackageName);
18255                        pw.print(" (uid=");
18256                        pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
18257                                UserHandle.USER_SYSTEM));
18258                        pw.println(")");
18259                    } else if (verifierPackageName != null) {
18260                        pw.print("ifv,"); pw.print(verifierPackageName);
18261                        pw.print(",");
18262                        pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
18263                                UserHandle.USER_SYSTEM));
18264                    }
18265                } else {
18266                    pw.println();
18267                    pw.println("No Intent Filter Verifier available!");
18268                }
18269            }
18270
18271            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
18272                boolean printedHeader = false;
18273                final Iterator<String> it = mSharedLibraries.keySet().iterator();
18274                while (it.hasNext()) {
18275                    String name = it.next();
18276                    SharedLibraryEntry ent = mSharedLibraries.get(name);
18277                    if (!checkin) {
18278                        if (!printedHeader) {
18279                            if (dumpState.onTitlePrinted())
18280                                pw.println();
18281                            pw.println("Libraries:");
18282                            printedHeader = true;
18283                        }
18284                        pw.print("  ");
18285                    } else {
18286                        pw.print("lib,");
18287                    }
18288                    pw.print(name);
18289                    if (!checkin) {
18290                        pw.print(" -> ");
18291                    }
18292                    if (ent.path != null) {
18293                        if (!checkin) {
18294                            pw.print("(jar) ");
18295                            pw.print(ent.path);
18296                        } else {
18297                            pw.print(",jar,");
18298                            pw.print(ent.path);
18299                        }
18300                    } else {
18301                        if (!checkin) {
18302                            pw.print("(apk) ");
18303                            pw.print(ent.apk);
18304                        } else {
18305                            pw.print(",apk,");
18306                            pw.print(ent.apk);
18307                        }
18308                    }
18309                    pw.println();
18310                }
18311            }
18312
18313            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
18314                if (dumpState.onTitlePrinted())
18315                    pw.println();
18316                if (!checkin) {
18317                    pw.println("Features:");
18318                }
18319
18320                for (FeatureInfo feat : mAvailableFeatures.values()) {
18321                    if (checkin) {
18322                        pw.print("feat,");
18323                        pw.print(feat.name);
18324                        pw.print(",");
18325                        pw.println(feat.version);
18326                    } else {
18327                        pw.print("  ");
18328                        pw.print(feat.name);
18329                        if (feat.version > 0) {
18330                            pw.print(" version=");
18331                            pw.print(feat.version);
18332                        }
18333                        pw.println();
18334                    }
18335                }
18336            }
18337
18338            if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) {
18339                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
18340                        : "Activity Resolver Table:", "  ", packageName,
18341                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
18342                    dumpState.setTitlePrinted(true);
18343                }
18344            }
18345            if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) {
18346                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
18347                        : "Receiver Resolver Table:", "  ", packageName,
18348                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
18349                    dumpState.setTitlePrinted(true);
18350                }
18351            }
18352            if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) {
18353                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
18354                        : "Service Resolver Table:", "  ", packageName,
18355                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
18356                    dumpState.setTitlePrinted(true);
18357                }
18358            }
18359            if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) {
18360                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
18361                        : "Provider Resolver Table:", "  ", packageName,
18362                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
18363                    dumpState.setTitlePrinted(true);
18364                }
18365            }
18366
18367            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
18368                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
18369                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
18370                    int user = mSettings.mPreferredActivities.keyAt(i);
18371                    if (pir.dump(pw,
18372                            dumpState.getTitlePrinted()
18373                                ? "\nPreferred Activities User " + user + ":"
18374                                : "Preferred Activities User " + user + ":", "  ",
18375                            packageName, true, false)) {
18376                        dumpState.setTitlePrinted(true);
18377                    }
18378                }
18379            }
18380
18381            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
18382                pw.flush();
18383                FileOutputStream fout = new FileOutputStream(fd);
18384                BufferedOutputStream str = new BufferedOutputStream(fout);
18385                XmlSerializer serializer = new FastXmlSerializer();
18386                try {
18387                    serializer.setOutput(str, StandardCharsets.UTF_8.name());
18388                    serializer.startDocument(null, true);
18389                    serializer.setFeature(
18390                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
18391                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
18392                    serializer.endDocument();
18393                    serializer.flush();
18394                } catch (IllegalArgumentException e) {
18395                    pw.println("Failed writing: " + e);
18396                } catch (IllegalStateException e) {
18397                    pw.println("Failed writing: " + e);
18398                } catch (IOException e) {
18399                    pw.println("Failed writing: " + e);
18400                }
18401            }
18402
18403            if (!checkin
18404                    && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)
18405                    && packageName == null) {
18406                pw.println();
18407                int count = mSettings.mPackages.size();
18408                if (count == 0) {
18409                    pw.println("No applications!");
18410                    pw.println();
18411                } else {
18412                    final String prefix = "  ";
18413                    Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values();
18414                    if (allPackageSettings.size() == 0) {
18415                        pw.println("No domain preferred apps!");
18416                        pw.println();
18417                    } else {
18418                        pw.println("App verification status:");
18419                        pw.println();
18420                        count = 0;
18421                        for (PackageSetting ps : allPackageSettings) {
18422                            IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
18423                            if (ivi == null || ivi.getPackageName() == null) continue;
18424                            pw.println(prefix + "Package: " + ivi.getPackageName());
18425                            pw.println(prefix + "Domains: " + ivi.getDomainsString());
18426                            pw.println(prefix + "Status:  " + ivi.getStatusString());
18427                            pw.println();
18428                            count++;
18429                        }
18430                        if (count == 0) {
18431                            pw.println(prefix + "No app verification established.");
18432                            pw.println();
18433                        }
18434                        for (int userId : sUserManager.getUserIds()) {
18435                            pw.println("App linkages for user " + userId + ":");
18436                            pw.println();
18437                            count = 0;
18438                            for (PackageSetting ps : allPackageSettings) {
18439                                final long status = ps.getDomainVerificationStatusForUser(userId);
18440                                if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
18441                                    continue;
18442                                }
18443                                pw.println(prefix + "Package: " + ps.name);
18444                                pw.println(prefix + "Domains: " + dumpDomainString(ps.name));
18445                                String statusStr = IntentFilterVerificationInfo.
18446                                        getStatusStringFromValue(status);
18447                                pw.println(prefix + "Status:  " + statusStr);
18448                                pw.println();
18449                                count++;
18450                            }
18451                            if (count == 0) {
18452                                pw.println(prefix + "No configured app linkages.");
18453                                pw.println();
18454                            }
18455                        }
18456                    }
18457                }
18458            }
18459
18460            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
18461                mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState);
18462                if (packageName == null && permissionNames == null) {
18463                    for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) {
18464                        if (iperm == 0) {
18465                            if (dumpState.onTitlePrinted())
18466                                pw.println();
18467                            pw.println("AppOp Permissions:");
18468                        }
18469                        pw.print("  AppOp Permission ");
18470                        pw.print(mAppOpPermissionPackages.keyAt(iperm));
18471                        pw.println(":");
18472                        ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm);
18473                        for (int ipkg=0; ipkg<pkgs.size(); ipkg++) {
18474                            pw.print("    "); pw.println(pkgs.valueAt(ipkg));
18475                        }
18476                    }
18477                }
18478            }
18479
18480            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
18481                boolean printedSomething = false;
18482                for (PackageParser.Provider p : mProviders.mProviders.values()) {
18483                    if (packageName != null && !packageName.equals(p.info.packageName)) {
18484                        continue;
18485                    }
18486                    if (!printedSomething) {
18487                        if (dumpState.onTitlePrinted())
18488                            pw.println();
18489                        pw.println("Registered ContentProviders:");
18490                        printedSomething = true;
18491                    }
18492                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
18493                    pw.print("    "); pw.println(p.toString());
18494                }
18495                printedSomething = false;
18496                for (Map.Entry<String, PackageParser.Provider> entry :
18497                        mProvidersByAuthority.entrySet()) {
18498                    PackageParser.Provider p = entry.getValue();
18499                    if (packageName != null && !packageName.equals(p.info.packageName)) {
18500                        continue;
18501                    }
18502                    if (!printedSomething) {
18503                        if (dumpState.onTitlePrinted())
18504                            pw.println();
18505                        pw.println("ContentProvider Authorities:");
18506                        printedSomething = true;
18507                    }
18508                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
18509                    pw.print("    "); pw.println(p.toString());
18510                    if (p.info != null && p.info.applicationInfo != null) {
18511                        final String appInfo = p.info.applicationInfo.toString();
18512                        pw.print("      applicationInfo="); pw.println(appInfo);
18513                    }
18514                }
18515            }
18516
18517            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
18518                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
18519            }
18520
18521            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
18522                mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin);
18523            }
18524
18525            if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
18526                mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin);
18527            }
18528
18529            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) {
18530                mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState);
18531            }
18532
18533            if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
18534                // XXX should handle packageName != null by dumping only install data that
18535                // the given package is involved with.
18536                if (dumpState.onTitlePrinted()) pw.println();
18537                mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
18538            }
18539
18540            if (!checkin && dumpState.isDumping(DumpState.DUMP_FROZEN) && packageName == null) {
18541                // XXX should handle packageName != null by dumping only install data that
18542                // the given package is involved with.
18543                if (dumpState.onTitlePrinted()) pw.println();
18544
18545                final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
18546                ipw.println();
18547                ipw.println("Frozen packages:");
18548                ipw.increaseIndent();
18549                if (mFrozenPackages.size() == 0) {
18550                    ipw.println("(none)");
18551                } else {
18552                    for (int i = 0; i < mFrozenPackages.size(); i++) {
18553                        ipw.println(mFrozenPackages.valueAt(i));
18554                    }
18555                }
18556                ipw.decreaseIndent();
18557            }
18558
18559            if (!checkin && dumpState.isDumping(DumpState.DUMP_DEXOPT)) {
18560                if (dumpState.onTitlePrinted()) pw.println();
18561                dumpDexoptStateLPr(pw, packageName);
18562            }
18563
18564            if (!checkin && dumpState.isDumping(DumpState.DUMP_COMPILER_STATS)) {
18565                if (dumpState.onTitlePrinted()) pw.println();
18566                dumpCompilerStatsLPr(pw, packageName);
18567            }
18568
18569            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
18570                if (dumpState.onTitlePrinted()) pw.println();
18571                mSettings.dumpReadMessagesLPr(pw, dumpState);
18572
18573                pw.println();
18574                pw.println("Package warning messages:");
18575                BufferedReader in = null;
18576                String line = null;
18577                try {
18578                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
18579                    while ((line = in.readLine()) != null) {
18580                        if (line.contains("ignored: updated version")) continue;
18581                        pw.println(line);
18582                    }
18583                } catch (IOException ignored) {
18584                } finally {
18585                    IoUtils.closeQuietly(in);
18586                }
18587            }
18588
18589            if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) {
18590                BufferedReader in = null;
18591                String line = null;
18592                try {
18593                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
18594                    while ((line = in.readLine()) != null) {
18595                        if (line.contains("ignored: updated version")) continue;
18596                        pw.print("msg,");
18597                        pw.println(line);
18598                    }
18599                } catch (IOException ignored) {
18600                } finally {
18601                    IoUtils.closeQuietly(in);
18602                }
18603            }
18604        }
18605    }
18606
18607    private void dumpDexoptStateLPr(PrintWriter pw, String packageName) {
18608        final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
18609        ipw.println();
18610        ipw.println("Dexopt state:");
18611        ipw.increaseIndent();
18612        Collection<PackageParser.Package> packages = null;
18613        if (packageName != null) {
18614            PackageParser.Package targetPackage = mPackages.get(packageName);
18615            if (targetPackage != null) {
18616                packages = Collections.singletonList(targetPackage);
18617            } else {
18618                ipw.println("Unable to find package: " + packageName);
18619                return;
18620            }
18621        } else {
18622            packages = mPackages.values();
18623        }
18624
18625        for (PackageParser.Package pkg : packages) {
18626            ipw.println("[" + pkg.packageName + "]");
18627            ipw.increaseIndent();
18628            mPackageDexOptimizer.dumpDexoptState(ipw, pkg);
18629            ipw.decreaseIndent();
18630        }
18631    }
18632
18633    private void dumpCompilerStatsLPr(PrintWriter pw, String packageName) {
18634        final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
18635        ipw.println();
18636        ipw.println("Compiler stats:");
18637        ipw.increaseIndent();
18638        Collection<PackageParser.Package> packages = null;
18639        if (packageName != null) {
18640            PackageParser.Package targetPackage = mPackages.get(packageName);
18641            if (targetPackage != null) {
18642                packages = Collections.singletonList(targetPackage);
18643            } else {
18644                ipw.println("Unable to find package: " + packageName);
18645                return;
18646            }
18647        } else {
18648            packages = mPackages.values();
18649        }
18650
18651        for (PackageParser.Package pkg : packages) {
18652            ipw.println("[" + pkg.packageName + "]");
18653            ipw.increaseIndent();
18654
18655            CompilerStats.PackageStats stats = getCompilerPackageStats(pkg.packageName);
18656            if (stats == null) {
18657                ipw.println("(No recorded stats)");
18658            } else {
18659                stats.dump(ipw);
18660            }
18661            ipw.decreaseIndent();
18662        }
18663    }
18664
18665    private String dumpDomainString(String packageName) {
18666        List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName)
18667                .getList();
18668        List<IntentFilter> filters = getAllIntentFilters(packageName).getList();
18669
18670        ArraySet<String> result = new ArraySet<>();
18671        if (iviList.size() > 0) {
18672            for (IntentFilterVerificationInfo ivi : iviList) {
18673                for (String host : ivi.getDomains()) {
18674                    result.add(host);
18675                }
18676            }
18677        }
18678        if (filters != null && filters.size() > 0) {
18679            for (IntentFilter filter : filters) {
18680                if (filter.hasCategory(Intent.CATEGORY_BROWSABLE)
18681                        && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
18682                                filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) {
18683                    result.addAll(filter.getHostsList());
18684                }
18685            }
18686        }
18687
18688        StringBuilder sb = new StringBuilder(result.size() * 16);
18689        for (String domain : result) {
18690            if (sb.length() > 0) sb.append(" ");
18691            sb.append(domain);
18692        }
18693        return sb.toString();
18694    }
18695
18696    // ------- apps on sdcard specific code -------
18697    static final boolean DEBUG_SD_INSTALL = false;
18698
18699    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
18700
18701    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
18702
18703    private boolean mMediaMounted = false;
18704
18705    static String getEncryptKey() {
18706        try {
18707            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
18708                    SD_ENCRYPTION_KEYSTORE_NAME);
18709            if (sdEncKey == null) {
18710                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
18711                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
18712                if (sdEncKey == null) {
18713                    Slog.e(TAG, "Failed to create encryption keys");
18714                    return null;
18715                }
18716            }
18717            return sdEncKey;
18718        } catch (NoSuchAlgorithmException nsae) {
18719            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
18720            return null;
18721        } catch (IOException ioe) {
18722            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
18723            return null;
18724        }
18725    }
18726
18727    /*
18728     * Update media status on PackageManager.
18729     */
18730    @Override
18731    public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
18732        int callingUid = Binder.getCallingUid();
18733        if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
18734            throw new SecurityException("Media status can only be updated by the system");
18735        }
18736        // reader; this apparently protects mMediaMounted, but should probably
18737        // be a different lock in that case.
18738        synchronized (mPackages) {
18739            Log.i(TAG, "Updating external media status from "
18740                    + (mMediaMounted ? "mounted" : "unmounted") + " to "
18741                    + (mediaStatus ? "mounted" : "unmounted"));
18742            if (DEBUG_SD_INSTALL)
18743                Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
18744                        + ", mMediaMounted=" + mMediaMounted);
18745            if (mediaStatus == mMediaMounted) {
18746                final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
18747                        : 0, -1);
18748                mHandler.sendMessage(msg);
18749                return;
18750            }
18751            mMediaMounted = mediaStatus;
18752        }
18753        // Queue up an async operation since the package installation may take a
18754        // little while.
18755        mHandler.post(new Runnable() {
18756            public void run() {
18757                updateExternalMediaStatusInner(mediaStatus, reportStatus, true);
18758            }
18759        });
18760    }
18761
18762    /**
18763     * Called by MountService when the initial ASECs to scan are available.
18764     * Should block until all the ASEC containers are finished being scanned.
18765     */
18766    public void scanAvailableAsecs() {
18767        updateExternalMediaStatusInner(true, false, false);
18768    }
18769
18770    /*
18771     * Collect information of applications on external media, map them against
18772     * existing containers and update information based on current mount status.
18773     * Please note that we always have to report status if reportStatus has been
18774     * set to true especially when unloading packages.
18775     */
18776    private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus,
18777            boolean externalStorage) {
18778        ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>();
18779        int[] uidArr = EmptyArray.INT;
18780
18781        final String[] list = PackageHelper.getSecureContainerList();
18782        if (ArrayUtils.isEmpty(list)) {
18783            Log.i(TAG, "No secure containers found");
18784        } else {
18785            // Process list of secure containers and categorize them
18786            // as active or stale based on their package internal state.
18787
18788            // reader
18789            synchronized (mPackages) {
18790                for (String cid : list) {
18791                    // Leave stages untouched for now; installer service owns them
18792                    if (PackageInstallerService.isStageName(cid)) continue;
18793
18794                    if (DEBUG_SD_INSTALL)
18795                        Log.i(TAG, "Processing container " + cid);
18796                    String pkgName = getAsecPackageName(cid);
18797                    if (pkgName == null) {
18798                        Slog.i(TAG, "Found stale container " + cid + " with no package name");
18799                        continue;
18800                    }
18801                    if (DEBUG_SD_INSTALL)
18802                        Log.i(TAG, "Looking for pkg : " + pkgName);
18803
18804                    final PackageSetting ps = mSettings.mPackages.get(pkgName);
18805                    if (ps == null) {
18806                        Slog.i(TAG, "Found stale container " + cid + " with no matching settings");
18807                        continue;
18808                    }
18809
18810                    /*
18811                     * Skip packages that are not external if we're unmounting
18812                     * external storage.
18813                     */
18814                    if (externalStorage && !isMounted && !isExternal(ps)) {
18815                        continue;
18816                    }
18817
18818                    final AsecInstallArgs args = new AsecInstallArgs(cid,
18819                            getAppDexInstructionSets(ps), ps.isForwardLocked());
18820                    // The package status is changed only if the code path
18821                    // matches between settings and the container id.
18822                    if (ps.codePathString != null
18823                            && ps.codePathString.startsWith(args.getCodePath())) {
18824                        if (DEBUG_SD_INSTALL) {
18825                            Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
18826                                    + " at code path: " + ps.codePathString);
18827                        }
18828
18829                        // We do have a valid package installed on sdcard
18830                        processCids.put(args, ps.codePathString);
18831                        final int uid = ps.appId;
18832                        if (uid != -1) {
18833                            uidArr = ArrayUtils.appendInt(uidArr, uid);
18834                        }
18835                    } else {
18836                        Slog.i(TAG, "Found stale container " + cid + ": expected codePath="
18837                                + ps.codePathString);
18838                    }
18839                }
18840            }
18841
18842            Arrays.sort(uidArr);
18843        }
18844
18845        // Process packages with valid entries.
18846        if (isMounted) {
18847            if (DEBUG_SD_INSTALL)
18848                Log.i(TAG, "Loading packages");
18849            loadMediaPackages(processCids, uidArr, externalStorage);
18850            startCleaningPackages();
18851            mInstallerService.onSecureContainersAvailable();
18852        } else {
18853            if (DEBUG_SD_INSTALL)
18854                Log.i(TAG, "Unloading packages");
18855            unloadMediaPackages(processCids, uidArr, reportStatus);
18856        }
18857    }
18858
18859    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
18860            ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) {
18861        final int size = infos.size();
18862        final String[] packageNames = new String[size];
18863        final int[] packageUids = new int[size];
18864        for (int i = 0; i < size; i++) {
18865            final ApplicationInfo info = infos.get(i);
18866            packageNames[i] = info.packageName;
18867            packageUids[i] = info.uid;
18868        }
18869        sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids,
18870                finishedReceiver);
18871    }
18872
18873    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
18874            ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
18875        sendResourcesChangedBroadcast(mediaStatus, replacing,
18876                pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver);
18877    }
18878
18879    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
18880            String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
18881        int size = pkgList.length;
18882        if (size > 0) {
18883            // Send broadcasts here
18884            Bundle extras = new Bundle();
18885            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
18886            if (uidArr != null) {
18887                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
18888            }
18889            if (replacing) {
18890                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
18891            }
18892            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
18893                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
18894            sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null);
18895        }
18896    }
18897
18898   /*
18899     * Look at potentially valid container ids from processCids If package
18900     * information doesn't match the one on record or package scanning fails,
18901     * the cid is added to list of removeCids. We currently don't delete stale
18902     * containers.
18903     */
18904    private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr,
18905            boolean externalStorage) {
18906        ArrayList<String> pkgList = new ArrayList<String>();
18907        Set<AsecInstallArgs> keys = processCids.keySet();
18908
18909        for (AsecInstallArgs args : keys) {
18910            String codePath = processCids.get(args);
18911            if (DEBUG_SD_INSTALL)
18912                Log.i(TAG, "Loading container : " + args.cid);
18913            int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
18914            try {
18915                // Make sure there are no container errors first.
18916                if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
18917                    Slog.e(TAG, "Failed to mount cid : " + args.cid
18918                            + " when installing from sdcard");
18919                    continue;
18920                }
18921                // Check code path here.
18922                if (codePath == null || !codePath.startsWith(args.getCodePath())) {
18923                    Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
18924                            + " does not match one in settings " + codePath);
18925                    continue;
18926                }
18927                // Parse package
18928                int parseFlags = mDefParseFlags;
18929                if (args.isExternalAsec()) {
18930                    parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE;
18931                }
18932                if (args.isFwdLocked()) {
18933                    parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
18934                }
18935
18936                synchronized (mInstallLock) {
18937                    PackageParser.Package pkg = null;
18938                    try {
18939                        // Sadly we don't know the package name yet to freeze it
18940                        pkg = scanPackageTracedLI(new File(codePath), parseFlags,
18941                                SCAN_IGNORE_FROZEN, 0, null);
18942                    } catch (PackageManagerException e) {
18943                        Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage());
18944                    }
18945                    // Scan the package
18946                    if (pkg != null) {
18947                        /*
18948                         * TODO why is the lock being held? doPostInstall is
18949                         * called in other places without the lock. This needs
18950                         * to be straightened out.
18951                         */
18952                        // writer
18953                        synchronized (mPackages) {
18954                            retCode = PackageManager.INSTALL_SUCCEEDED;
18955                            pkgList.add(pkg.packageName);
18956                            // Post process args
18957                            args.doPostInstall(PackageManager.INSTALL_SUCCEEDED,
18958                                    pkg.applicationInfo.uid);
18959                        }
18960                    } else {
18961                        Slog.i(TAG, "Failed to install pkg from  " + codePath + " from sdcard");
18962                    }
18963                }
18964
18965            } finally {
18966                if (retCode != PackageManager.INSTALL_SUCCEEDED) {
18967                    Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode);
18968                }
18969            }
18970        }
18971        // writer
18972        synchronized (mPackages) {
18973            // If the platform SDK has changed since the last time we booted,
18974            // we need to re-grant app permission to catch any new ones that
18975            // appear. This is really a hack, and means that apps can in some
18976            // cases get permissions that the user didn't initially explicitly
18977            // allow... it would be nice to have some better way to handle
18978            // this situation.
18979            final VersionInfo ver = externalStorage ? mSettings.getExternalVersion()
18980                    : mSettings.getInternalVersion();
18981            final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL
18982                    : StorageManager.UUID_PRIVATE_INTERNAL;
18983
18984            int updateFlags = UPDATE_PERMISSIONS_ALL;
18985            if (ver.sdkVersion != mSdkVersion) {
18986                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
18987                        + mSdkVersion + "; regranting permissions for external");
18988                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
18989            }
18990            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
18991
18992            // Yay, everything is now upgraded
18993            ver.forceCurrent();
18994
18995            // can downgrade to reader
18996            // Persist settings
18997            mSettings.writeLPr();
18998        }
18999        // Send a broadcast to let everyone know we are done processing
19000        if (pkgList.size() > 0) {
19001            sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
19002        }
19003    }
19004
19005   /*
19006     * Utility method to unload a list of specified containers
19007     */
19008    private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) {
19009        // Just unmount all valid containers.
19010        for (AsecInstallArgs arg : cidArgs) {
19011            synchronized (mInstallLock) {
19012                arg.doPostDeleteLI(false);
19013           }
19014       }
19015   }
19016
19017    /*
19018     * Unload packages mounted on external media. This involves deleting package
19019     * data from internal structures, sending broadcasts about disabled packages,
19020     * gc'ing to free up references, unmounting all secure containers
19021     * corresponding to packages on external media, and posting a
19022     * UPDATED_MEDIA_STATUS message if status has been requested. Please note
19023     * that we always have to post this message if status has been requested no
19024     * matter what.
19025     */
19026    private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[],
19027            final boolean reportStatus) {
19028        if (DEBUG_SD_INSTALL)
19029            Log.i(TAG, "unloading media packages");
19030        ArrayList<String> pkgList = new ArrayList<String>();
19031        ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>();
19032        final Set<AsecInstallArgs> keys = processCids.keySet();
19033        for (AsecInstallArgs args : keys) {
19034            String pkgName = args.getPackageName();
19035            if (DEBUG_SD_INSTALL)
19036                Log.i(TAG, "Trying to unload pkg : " + pkgName);
19037            // Delete package internally
19038            PackageRemovedInfo outInfo = new PackageRemovedInfo();
19039            synchronized (mInstallLock) {
19040                final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
19041                final boolean res;
19042                try (PackageFreezer freezer = freezePackageForDelete(pkgName, deleteFlags,
19043                        "unloadMediaPackages")) {
19044                    res = deletePackageLIF(pkgName, null, false, null, deleteFlags, outInfo, false,
19045                            null);
19046                }
19047                if (res) {
19048                    pkgList.add(pkgName);
19049                } else {
19050                    Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
19051                    failedList.add(args);
19052                }
19053            }
19054        }
19055
19056        // reader
19057        synchronized (mPackages) {
19058            // We didn't update the settings after removing each package;
19059            // write them now for all packages.
19060            mSettings.writeLPr();
19061        }
19062
19063        // We have to absolutely send UPDATED_MEDIA_STATUS only
19064        // after confirming that all the receivers processed the ordered
19065        // broadcast when packages get disabled, force a gc to clean things up.
19066        // and unload all the containers.
19067        if (pkgList.size() > 0) {
19068            sendResourcesChangedBroadcast(false, false, pkgList, uidArr,
19069                    new IIntentReceiver.Stub() {
19070                public void performReceive(Intent intent, int resultCode, String data,
19071                        Bundle extras, boolean ordered, boolean sticky,
19072                        int sendingUser) throws RemoteException {
19073                    Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
19074                            reportStatus ? 1 : 0, 1, keys);
19075                    mHandler.sendMessage(msg);
19076                }
19077            });
19078        } else {
19079            Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
19080                    keys);
19081            mHandler.sendMessage(msg);
19082        }
19083    }
19084
19085    private void loadPrivatePackages(final VolumeInfo vol) {
19086        mHandler.post(new Runnable() {
19087            @Override
19088            public void run() {
19089                loadPrivatePackagesInner(vol);
19090            }
19091        });
19092    }
19093
19094    private void loadPrivatePackagesInner(VolumeInfo vol) {
19095        final String volumeUuid = vol.fsUuid;
19096        if (TextUtils.isEmpty(volumeUuid)) {
19097            Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring");
19098            return;
19099        }
19100
19101        final ArrayList<PackageFreezer> freezers = new ArrayList<>();
19102        final ArrayList<ApplicationInfo> loaded = new ArrayList<>();
19103        final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE;
19104
19105        final VersionInfo ver;
19106        final List<PackageSetting> packages;
19107        synchronized (mPackages) {
19108            ver = mSettings.findOrCreateVersion(volumeUuid);
19109            packages = mSettings.getVolumePackagesLPr(volumeUuid);
19110        }
19111
19112        for (PackageSetting ps : packages) {
19113            freezers.add(freezePackage(ps.name, "loadPrivatePackagesInner"));
19114            synchronized (mInstallLock) {
19115                final PackageParser.Package pkg;
19116                try {
19117                    pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null);
19118                    loaded.add(pkg.applicationInfo);
19119
19120                } catch (PackageManagerException e) {
19121                    Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage());
19122                }
19123
19124                if (!Build.FINGERPRINT.equals(ver.fingerprint)) {
19125                    clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
19126                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
19127                                    | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
19128                }
19129            }
19130        }
19131
19132        // Reconcile app data for all started/unlocked users
19133        final StorageManager sm = mContext.getSystemService(StorageManager.class);
19134        final UserManager um = mContext.getSystemService(UserManager.class);
19135        UserManagerInternal umInternal = getUserManagerInternal();
19136        for (UserInfo user : um.getUsers()) {
19137            final int flags;
19138            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
19139                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
19140            } else if (umInternal.isUserRunning(user.id)) {
19141                flags = StorageManager.FLAG_STORAGE_DE;
19142            } else {
19143                continue;
19144            }
19145
19146            try {
19147                sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags);
19148                synchronized (mInstallLock) {
19149                    reconcileAppsDataLI(volumeUuid, user.id, flags);
19150                }
19151            } catch (IllegalStateException e) {
19152                // Device was probably ejected, and we'll process that event momentarily
19153                Slog.w(TAG, "Failed to prepare storage: " + e);
19154            }
19155        }
19156
19157        synchronized (mPackages) {
19158            int updateFlags = UPDATE_PERMISSIONS_ALL;
19159            if (ver.sdkVersion != mSdkVersion) {
19160                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
19161                        + mSdkVersion + "; regranting permissions for " + volumeUuid);
19162                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
19163            }
19164            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
19165
19166            // Yay, everything is now upgraded
19167            ver.forceCurrent();
19168
19169            mSettings.writeLPr();
19170        }
19171
19172        for (PackageFreezer freezer : freezers) {
19173            freezer.close();
19174        }
19175
19176        if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded);
19177        sendResourcesChangedBroadcast(true, false, loaded, null);
19178    }
19179
19180    private void unloadPrivatePackages(final VolumeInfo vol) {
19181        mHandler.post(new Runnable() {
19182            @Override
19183            public void run() {
19184                unloadPrivatePackagesInner(vol);
19185            }
19186        });
19187    }
19188
19189    private void unloadPrivatePackagesInner(VolumeInfo vol) {
19190        final String volumeUuid = vol.fsUuid;
19191        if (TextUtils.isEmpty(volumeUuid)) {
19192            Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring");
19193            return;
19194        }
19195
19196        final ArrayList<ApplicationInfo> unloaded = new ArrayList<>();
19197        synchronized (mInstallLock) {
19198        synchronized (mPackages) {
19199            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid);
19200            for (PackageSetting ps : packages) {
19201                if (ps.pkg == null) continue;
19202
19203                final ApplicationInfo info = ps.pkg.applicationInfo;
19204                final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
19205                final PackageRemovedInfo outInfo = new PackageRemovedInfo();
19206
19207                try (PackageFreezer freezer = freezePackageForDelete(ps.name, deleteFlags,
19208                        "unloadPrivatePackagesInner")) {
19209                    if (deletePackageLIF(ps.name, null, false, null, deleteFlags, outInfo,
19210                            false, null)) {
19211                        unloaded.add(info);
19212                    } else {
19213                        Slog.w(TAG, "Failed to unload " + ps.codePath);
19214                    }
19215                }
19216
19217                // Try very hard to release any references to this package
19218                // so we don't risk the system server being killed due to
19219                // open FDs
19220                AttributeCache.instance().removePackage(ps.name);
19221            }
19222
19223            mSettings.writeLPr();
19224        }
19225        }
19226
19227        if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded);
19228        sendResourcesChangedBroadcast(false, false, unloaded, null);
19229
19230        // Try very hard to release any references to this path so we don't risk
19231        // the system server being killed due to open FDs
19232        ResourcesManager.getInstance().invalidatePath(vol.getPath().getAbsolutePath());
19233
19234        for (int i = 0; i < 3; i++) {
19235            System.gc();
19236            System.runFinalization();
19237        }
19238    }
19239
19240    /**
19241     * Prepare storage areas for given user on all mounted devices.
19242     */
19243    void prepareUserData(int userId, int userSerial, int flags) {
19244        synchronized (mInstallLock) {
19245            final StorageManager storage = mContext.getSystemService(StorageManager.class);
19246            for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
19247                final String volumeUuid = vol.getFsUuid();
19248                prepareUserDataLI(volumeUuid, userId, userSerial, flags, true);
19249            }
19250        }
19251    }
19252
19253    private void prepareUserDataLI(String volumeUuid, int userId, int userSerial, int flags,
19254            boolean allowRecover) {
19255        // Prepare storage and verify that serial numbers are consistent; if
19256        // there's a mismatch we need to destroy to avoid leaking data
19257        final StorageManager storage = mContext.getSystemService(StorageManager.class);
19258        try {
19259            storage.prepareUserStorage(volumeUuid, userId, userSerial, flags);
19260
19261            if ((flags & StorageManager.FLAG_STORAGE_DE) != 0 && !mOnlyCore) {
19262                UserManagerService.enforceSerialNumber(
19263                        Environment.getDataUserDeDirectory(volumeUuid, userId), userSerial);
19264                if (Objects.equals(volumeUuid, StorageManager.UUID_PRIVATE_INTERNAL)) {
19265                    UserManagerService.enforceSerialNumber(
19266                            Environment.getDataSystemDeDirectory(userId), userSerial);
19267                }
19268            }
19269            if ((flags & StorageManager.FLAG_STORAGE_CE) != 0 && !mOnlyCore) {
19270                UserManagerService.enforceSerialNumber(
19271                        Environment.getDataUserCeDirectory(volumeUuid, userId), userSerial);
19272                if (Objects.equals(volumeUuid, StorageManager.UUID_PRIVATE_INTERNAL)) {
19273                    UserManagerService.enforceSerialNumber(
19274                            Environment.getDataSystemCeDirectory(userId), userSerial);
19275                }
19276            }
19277
19278            synchronized (mInstallLock) {
19279                mInstaller.createUserData(volumeUuid, userId, userSerial, flags);
19280            }
19281        } catch (Exception e) {
19282            logCriticalInfo(Log.WARN, "Destroying user " + userId + " on volume " + volumeUuid
19283                    + " because we failed to prepare: " + e);
19284            destroyUserDataLI(volumeUuid, userId,
19285                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
19286
19287            if (allowRecover) {
19288                // Try one last time; if we fail again we're really in trouble
19289                prepareUserDataLI(volumeUuid, userId, userSerial, flags, false);
19290            }
19291        }
19292    }
19293
19294    /**
19295     * Destroy storage areas for given user on all mounted devices.
19296     */
19297    void destroyUserData(int userId, int flags) {
19298        synchronized (mInstallLock) {
19299            final StorageManager storage = mContext.getSystemService(StorageManager.class);
19300            for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
19301                final String volumeUuid = vol.getFsUuid();
19302                destroyUserDataLI(volumeUuid, userId, flags);
19303            }
19304        }
19305    }
19306
19307    private void destroyUserDataLI(String volumeUuid, int userId, int flags) {
19308        final StorageManager storage = mContext.getSystemService(StorageManager.class);
19309        try {
19310            // Clean up app data, profile data, and media data
19311            mInstaller.destroyUserData(volumeUuid, userId, flags);
19312
19313            // Clean up system data
19314            if (Objects.equals(volumeUuid, StorageManager.UUID_PRIVATE_INTERNAL)) {
19315                if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) {
19316                    FileUtils.deleteContentsAndDir(Environment.getUserSystemDirectory(userId));
19317                    FileUtils.deleteContentsAndDir(Environment.getDataSystemDeDirectory(userId));
19318                }
19319                if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
19320                    FileUtils.deleteContentsAndDir(Environment.getDataSystemCeDirectory(userId));
19321                }
19322            }
19323
19324            // Data with special labels is now gone, so finish the job
19325            storage.destroyUserStorage(volumeUuid, userId, flags);
19326
19327        } catch (Exception e) {
19328            logCriticalInfo(Log.WARN,
19329                    "Failed to destroy user " + userId + " on volume " + volumeUuid + ": " + e);
19330        }
19331    }
19332
19333    /**
19334     * Examine all users present on given mounted volume, and destroy data
19335     * belonging to users that are no longer valid, or whose user ID has been
19336     * recycled.
19337     */
19338    private void reconcileUsers(String volumeUuid) {
19339        final List<File> files = new ArrayList<>();
19340        Collections.addAll(files, FileUtils
19341                .listFilesOrEmpty(Environment.getDataUserDeDirectory(volumeUuid)));
19342        Collections.addAll(files, FileUtils
19343                .listFilesOrEmpty(Environment.getDataUserCeDirectory(volumeUuid)));
19344        Collections.addAll(files, FileUtils
19345                .listFilesOrEmpty(Environment.getDataSystemDeDirectory()));
19346        Collections.addAll(files, FileUtils
19347                .listFilesOrEmpty(Environment.getDataSystemCeDirectory()));
19348        for (File file : files) {
19349            if (!file.isDirectory()) continue;
19350
19351            final int userId;
19352            final UserInfo info;
19353            try {
19354                userId = Integer.parseInt(file.getName());
19355                info = sUserManager.getUserInfo(userId);
19356            } catch (NumberFormatException e) {
19357                Slog.w(TAG, "Invalid user directory " + file);
19358                continue;
19359            }
19360
19361            boolean destroyUser = false;
19362            if (info == null) {
19363                logCriticalInfo(Log.WARN, "Destroying user directory " + file
19364                        + " because no matching user was found");
19365                destroyUser = true;
19366            } else if (!mOnlyCore) {
19367                try {
19368                    UserManagerService.enforceSerialNumber(file, info.serialNumber);
19369                } catch (IOException e) {
19370                    logCriticalInfo(Log.WARN, "Destroying user directory " + file
19371                            + " because we failed to enforce serial number: " + e);
19372                    destroyUser = true;
19373                }
19374            }
19375
19376            if (destroyUser) {
19377                synchronized (mInstallLock) {
19378                    destroyUserDataLI(volumeUuid, userId,
19379                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
19380                }
19381            }
19382        }
19383    }
19384
19385    private void assertPackageKnown(String volumeUuid, String packageName)
19386            throws PackageManagerException {
19387        synchronized (mPackages) {
19388            final PackageSetting ps = mSettings.mPackages.get(packageName);
19389            if (ps == null) {
19390                throw new PackageManagerException("Package " + packageName + " is unknown");
19391            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
19392                throw new PackageManagerException(
19393                        "Package " + packageName + " found on unknown volume " + volumeUuid
19394                                + "; expected volume " + ps.volumeUuid);
19395            }
19396        }
19397    }
19398
19399    private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId)
19400            throws PackageManagerException {
19401        synchronized (mPackages) {
19402            final PackageSetting ps = mSettings.mPackages.get(packageName);
19403            if (ps == null) {
19404                throw new PackageManagerException("Package " + packageName + " is unknown");
19405            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
19406                throw new PackageManagerException(
19407                        "Package " + packageName + " found on unknown volume " + volumeUuid
19408                                + "; expected volume " + ps.volumeUuid);
19409            } else if (!ps.getInstalled(userId)) {
19410                throw new PackageManagerException(
19411                        "Package " + packageName + " not installed for user " + userId);
19412            }
19413        }
19414    }
19415
19416    /**
19417     * Examine all apps present on given mounted volume, and destroy apps that
19418     * aren't expected, either due to uninstallation or reinstallation on
19419     * another volume.
19420     */
19421    private void reconcileApps(String volumeUuid) {
19422        final File[] files = FileUtils
19423                .listFilesOrEmpty(Environment.getDataAppDirectory(volumeUuid));
19424        for (File file : files) {
19425            final boolean isPackage = (isApkFile(file) || file.isDirectory())
19426                    && !PackageInstallerService.isStageName(file.getName());
19427            if (!isPackage) {
19428                // Ignore entries which are not packages
19429                continue;
19430            }
19431
19432            try {
19433                final PackageLite pkg = PackageParser.parsePackageLite(file,
19434                        PackageParser.PARSE_MUST_BE_APK);
19435                assertPackageKnown(volumeUuid, pkg.packageName);
19436
19437            } catch (PackageParserException | PackageManagerException e) {
19438                logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
19439                synchronized (mInstallLock) {
19440                    removeCodePathLI(file);
19441                }
19442            }
19443        }
19444    }
19445
19446    /**
19447     * Reconcile all app data for the given user.
19448     * <p>
19449     * Verifies that directories exist and that ownership and labeling is
19450     * correct for all installed apps on all mounted volumes.
19451     */
19452    void reconcileAppsData(int userId, int flags) {
19453        final StorageManager storage = mContext.getSystemService(StorageManager.class);
19454        for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
19455            final String volumeUuid = vol.getFsUuid();
19456            synchronized (mInstallLock) {
19457                reconcileAppsDataLI(volumeUuid, userId, flags);
19458            }
19459        }
19460    }
19461
19462    /**
19463     * Reconcile all app data on given mounted volume.
19464     * <p>
19465     * Destroys app data that isn't expected, either due to uninstallation or
19466     * reinstallation on another volume.
19467     * <p>
19468     * Verifies that directories exist and that ownership and labeling is
19469     * correct for all installed apps.
19470     */
19471    private void reconcileAppsDataLI(String volumeUuid, int userId, int flags) {
19472        Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x"
19473                + Integer.toHexString(flags));
19474
19475        final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId);
19476        final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId);
19477
19478        boolean restoreconNeeded = false;
19479
19480        // First look for stale data that doesn't belong, and check if things
19481        // have changed since we did our last restorecon
19482        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
19483            if (StorageManager.isFileEncryptedNativeOrEmulated()
19484                    && !StorageManager.isUserKeyUnlocked(userId)) {
19485                throw new RuntimeException(
19486                        "Yikes, someone asked us to reconcile CE storage while " + userId
19487                                + " was still locked; this would have caused massive data loss!");
19488            }
19489
19490            restoreconNeeded |= SELinuxMMAC.isRestoreconNeeded(ceDir);
19491
19492            final File[] files = FileUtils.listFilesOrEmpty(ceDir);
19493            for (File file : files) {
19494                final String packageName = file.getName();
19495                try {
19496                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
19497                } catch (PackageManagerException e) {
19498                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
19499                    try {
19500                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
19501                                StorageManager.FLAG_STORAGE_CE, 0);
19502                    } catch (InstallerException e2) {
19503                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
19504                    }
19505                }
19506            }
19507        }
19508        if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) {
19509            restoreconNeeded |= SELinuxMMAC.isRestoreconNeeded(deDir);
19510
19511            final File[] files = FileUtils.listFilesOrEmpty(deDir);
19512            for (File file : files) {
19513                final String packageName = file.getName();
19514                try {
19515                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
19516                } catch (PackageManagerException e) {
19517                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
19518                    try {
19519                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
19520                                StorageManager.FLAG_STORAGE_DE, 0);
19521                    } catch (InstallerException e2) {
19522                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
19523                    }
19524                }
19525            }
19526        }
19527
19528        // Ensure that data directories are ready to roll for all packages
19529        // installed for this volume and user
19530        final List<PackageSetting> packages;
19531        synchronized (mPackages) {
19532            packages = mSettings.getVolumePackagesLPr(volumeUuid);
19533        }
19534        int preparedCount = 0;
19535        for (PackageSetting ps : packages) {
19536            final String packageName = ps.name;
19537            if (ps.pkg == null) {
19538                Slog.w(TAG, "Odd, missing scanned package " + packageName);
19539                // TODO: might be due to legacy ASEC apps; we should circle back
19540                // and reconcile again once they're scanned
19541                continue;
19542            }
19543
19544            if (ps.getInstalled(userId)) {
19545                prepareAppDataLIF(ps.pkg, userId, flags, restoreconNeeded);
19546
19547                if (maybeMigrateAppDataLIF(ps.pkg, userId)) {
19548                    // We may have just shuffled around app data directories, so
19549                    // prepare them one more time
19550                    prepareAppDataLIF(ps.pkg, userId, flags, restoreconNeeded);
19551                }
19552
19553                preparedCount++;
19554            }
19555        }
19556
19557        if (restoreconNeeded) {
19558            if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
19559                SELinuxMMAC.setRestoreconDone(ceDir);
19560            }
19561            if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) {
19562                SELinuxMMAC.setRestoreconDone(deDir);
19563            }
19564        }
19565
19566        Slog.v(TAG, "reconcileAppsData finished " + preparedCount
19567                + " packages; restoreconNeeded was " + restoreconNeeded);
19568    }
19569
19570    /**
19571     * Prepare app data for the given app just after it was installed or
19572     * upgraded. This method carefully only touches users that it's installed
19573     * for, and it forces a restorecon to handle any seinfo changes.
19574     * <p>
19575     * Verifies that directories exist and that ownership and labeling is
19576     * correct for all installed apps. If there is an ownership mismatch, it
19577     * will try recovering system apps by wiping data; third-party app data is
19578     * left intact.
19579     * <p>
19580     * <em>Note: To avoid a deadlock, do not call this method with {@code mPackages} lock held</em>
19581     */
19582    private void prepareAppDataAfterInstallLIF(PackageParser.Package pkg) {
19583        final PackageSetting ps;
19584        synchronized (mPackages) {
19585            ps = mSettings.mPackages.get(pkg.packageName);
19586            mSettings.writeKernelMappingLPr(ps);
19587        }
19588
19589        final UserManager um = mContext.getSystemService(UserManager.class);
19590        UserManagerInternal umInternal = getUserManagerInternal();
19591        for (UserInfo user : um.getUsers()) {
19592            final int flags;
19593            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
19594                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
19595            } else if (umInternal.isUserRunning(user.id)) {
19596                flags = StorageManager.FLAG_STORAGE_DE;
19597            } else {
19598                continue;
19599            }
19600
19601            if (ps.getInstalled(user.id)) {
19602                // Whenever an app changes, force a restorecon of its data
19603                // TODO: when user data is locked, mark that we're still dirty
19604                prepareAppDataLIF(pkg, user.id, flags, true);
19605            }
19606        }
19607    }
19608
19609    /**
19610     * Prepare app data for the given app.
19611     * <p>
19612     * Verifies that directories exist and that ownership and labeling is
19613     * correct for all installed apps. If there is an ownership mismatch, this
19614     * will try recovering system apps by wiping data; third-party app data is
19615     * left intact.
19616     */
19617    private void prepareAppDataLIF(PackageParser.Package pkg, int userId, int flags,
19618            boolean restoreconNeeded) {
19619        if (pkg == null) {
19620            Slog.wtf(TAG, "Package was null!", new Throwable());
19621            return;
19622        }
19623        prepareAppDataLeafLIF(pkg, userId, flags, restoreconNeeded);
19624        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
19625        for (int i = 0; i < childCount; i++) {
19626            prepareAppDataLeafLIF(pkg.childPackages.get(i), userId, flags, restoreconNeeded);
19627        }
19628    }
19629
19630    private void prepareAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags,
19631            boolean restoreconNeeded) {
19632        if (DEBUG_APP_DATA) {
19633            Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x"
19634                    + Integer.toHexString(flags) + (restoreconNeeded ? " restoreconNeeded" : ""));
19635        }
19636
19637        final String volumeUuid = pkg.volumeUuid;
19638        final String packageName = pkg.packageName;
19639        final ApplicationInfo app = pkg.applicationInfo;
19640        final int appId = UserHandle.getAppId(app.uid);
19641
19642        Preconditions.checkNotNull(app.seinfo);
19643
19644        try {
19645            mInstaller.createAppData(volumeUuid, packageName, userId, flags,
19646                    appId, app.seinfo, app.targetSdkVersion);
19647        } catch (InstallerException e) {
19648            if (app.isSystemApp()) {
19649                logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName
19650                        + ", but trying to recover: " + e);
19651                destroyAppDataLeafLIF(pkg, userId, flags);
19652                try {
19653                    mInstaller.createAppData(volumeUuid, packageName, userId, flags,
19654                            appId, app.seinfo, app.targetSdkVersion);
19655                    logCriticalInfo(Log.DEBUG, "Recovery succeeded!");
19656                } catch (InstallerException e2) {
19657                    logCriticalInfo(Log.DEBUG, "Recovery failed!");
19658                }
19659            } else {
19660                Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e);
19661            }
19662        }
19663
19664        if (restoreconNeeded) {
19665            try {
19666                mInstaller.restoreconAppData(volumeUuid, packageName, userId, flags, appId,
19667                        app.seinfo);
19668            } catch (InstallerException e) {
19669                Slog.e(TAG, "Failed to restorecon for " + packageName + ": " + e);
19670            }
19671        }
19672
19673        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
19674            try {
19675                // CE storage is unlocked right now, so read out the inode and
19676                // remember for use later when it's locked
19677                // TODO: mark this structure as dirty so we persist it!
19678                final long ceDataInode = mInstaller.getAppDataInode(volumeUuid, packageName, userId,
19679                        StorageManager.FLAG_STORAGE_CE);
19680                synchronized (mPackages) {
19681                    final PackageSetting ps = mSettings.mPackages.get(packageName);
19682                    if (ps != null) {
19683                        ps.setCeDataInode(ceDataInode, userId);
19684                    }
19685                }
19686            } catch (InstallerException e) {
19687                Slog.e(TAG, "Failed to find inode for " + packageName + ": " + e);
19688            }
19689        }
19690
19691        prepareAppDataContentsLeafLIF(pkg, userId, flags);
19692    }
19693
19694    private void prepareAppDataContentsLIF(PackageParser.Package pkg, int userId, int flags) {
19695        if (pkg == null) {
19696            Slog.wtf(TAG, "Package was null!", new Throwable());
19697            return;
19698        }
19699        prepareAppDataContentsLeafLIF(pkg, userId, flags);
19700        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
19701        for (int i = 0; i < childCount; i++) {
19702            prepareAppDataContentsLeafLIF(pkg.childPackages.get(i), userId, flags);
19703        }
19704    }
19705
19706    private void prepareAppDataContentsLeafLIF(PackageParser.Package pkg, int userId, int flags) {
19707        final String volumeUuid = pkg.volumeUuid;
19708        final String packageName = pkg.packageName;
19709        final ApplicationInfo app = pkg.applicationInfo;
19710
19711        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
19712            // Create a native library symlink only if we have native libraries
19713            // and if the native libraries are 32 bit libraries. We do not provide
19714            // this symlink for 64 bit libraries.
19715            if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) {
19716                final String nativeLibPath = app.nativeLibraryDir;
19717                try {
19718                    mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName,
19719                            nativeLibPath, userId);
19720                } catch (InstallerException e) {
19721                    Slog.e(TAG, "Failed to link native for " + packageName + ": " + e);
19722                }
19723            }
19724        }
19725    }
19726
19727    /**
19728     * For system apps on non-FBE devices, this method migrates any existing
19729     * CE/DE data to match the {@code defaultToDeviceProtectedStorage} flag
19730     * requested by the app.
19731     */
19732    private boolean maybeMigrateAppDataLIF(PackageParser.Package pkg, int userId) {
19733        if (pkg.isSystemApp() && !StorageManager.isFileEncryptedNativeOrEmulated()
19734                && PackageManager.APPLY_DEFAULT_TO_DEVICE_PROTECTED_STORAGE) {
19735            final int storageTarget = pkg.applicationInfo.isDefaultToDeviceProtectedStorage()
19736                    ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE;
19737            try {
19738                mInstaller.migrateAppData(pkg.volumeUuid, pkg.packageName, userId,
19739                        storageTarget);
19740            } catch (InstallerException e) {
19741                logCriticalInfo(Log.WARN,
19742                        "Failed to migrate " + pkg.packageName + ": " + e.getMessage());
19743            }
19744            return true;
19745        } else {
19746            return false;
19747        }
19748    }
19749
19750    public PackageFreezer freezePackage(String packageName, String killReason) {
19751        return freezePackage(packageName, UserHandle.USER_ALL, killReason);
19752    }
19753
19754    public PackageFreezer freezePackage(String packageName, int userId, String killReason) {
19755        return new PackageFreezer(packageName, userId, killReason);
19756    }
19757
19758    public PackageFreezer freezePackageForInstall(String packageName, int installFlags,
19759            String killReason) {
19760        return freezePackageForInstall(packageName, UserHandle.USER_ALL, installFlags, killReason);
19761    }
19762
19763    public PackageFreezer freezePackageForInstall(String packageName, int userId, int installFlags,
19764            String killReason) {
19765        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
19766            return new PackageFreezer();
19767        } else {
19768            return freezePackage(packageName, userId, killReason);
19769        }
19770    }
19771
19772    public PackageFreezer freezePackageForDelete(String packageName, int deleteFlags,
19773            String killReason) {
19774        return freezePackageForDelete(packageName, UserHandle.USER_ALL, deleteFlags, killReason);
19775    }
19776
19777    public PackageFreezer freezePackageForDelete(String packageName, int userId, int deleteFlags,
19778            String killReason) {
19779        if ((deleteFlags & PackageManager.DELETE_DONT_KILL_APP) != 0) {
19780            return new PackageFreezer();
19781        } else {
19782            return freezePackage(packageName, userId, killReason);
19783        }
19784    }
19785
19786    /**
19787     * Class that freezes and kills the given package upon creation, and
19788     * unfreezes it upon closing. This is typically used when doing surgery on
19789     * app code/data to prevent the app from running while you're working.
19790     */
19791    private class PackageFreezer implements AutoCloseable {
19792        private final String mPackageName;
19793        private final PackageFreezer[] mChildren;
19794
19795        private final boolean mWeFroze;
19796
19797        private final AtomicBoolean mClosed = new AtomicBoolean();
19798        private final CloseGuard mCloseGuard = CloseGuard.get();
19799
19800        /**
19801         * Create and return a stub freezer that doesn't actually do anything,
19802         * typically used when someone requested
19803         * {@link PackageManager#INSTALL_DONT_KILL_APP} or
19804         * {@link PackageManager#DELETE_DONT_KILL_APP}.
19805         */
19806        public PackageFreezer() {
19807            mPackageName = null;
19808            mChildren = null;
19809            mWeFroze = false;
19810            mCloseGuard.open("close");
19811        }
19812
19813        public PackageFreezer(String packageName, int userId, String killReason) {
19814            synchronized (mPackages) {
19815                mPackageName = packageName;
19816                mWeFroze = mFrozenPackages.add(mPackageName);
19817
19818                final PackageSetting ps = mSettings.mPackages.get(mPackageName);
19819                if (ps != null) {
19820                    killApplication(ps.name, ps.appId, userId, killReason);
19821                }
19822
19823                final PackageParser.Package p = mPackages.get(packageName);
19824                if (p != null && p.childPackages != null) {
19825                    final int N = p.childPackages.size();
19826                    mChildren = new PackageFreezer[N];
19827                    for (int i = 0; i < N; i++) {
19828                        mChildren[i] = new PackageFreezer(p.childPackages.get(i).packageName,
19829                                userId, killReason);
19830                    }
19831                } else {
19832                    mChildren = null;
19833                }
19834            }
19835            mCloseGuard.open("close");
19836        }
19837
19838        @Override
19839        protected void finalize() throws Throwable {
19840            try {
19841                mCloseGuard.warnIfOpen();
19842                close();
19843            } finally {
19844                super.finalize();
19845            }
19846        }
19847
19848        @Override
19849        public void close() {
19850            mCloseGuard.close();
19851            if (mClosed.compareAndSet(false, true)) {
19852                synchronized (mPackages) {
19853                    if (mWeFroze) {
19854                        mFrozenPackages.remove(mPackageName);
19855                    }
19856
19857                    if (mChildren != null) {
19858                        for (PackageFreezer freezer : mChildren) {
19859                            freezer.close();
19860                        }
19861                    }
19862                }
19863            }
19864        }
19865    }
19866
19867    /**
19868     * Verify that given package is currently frozen.
19869     */
19870    private void checkPackageFrozen(String packageName) {
19871        synchronized (mPackages) {
19872            if (!mFrozenPackages.contains(packageName)) {
19873                Slog.wtf(TAG, "Expected " + packageName + " to be frozen!", new Throwable());
19874            }
19875        }
19876    }
19877
19878    @Override
19879    public int movePackage(final String packageName, final String volumeUuid) {
19880        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
19881
19882        final UserHandle user = new UserHandle(UserHandle.getCallingUserId());
19883        final int moveId = mNextMoveId.getAndIncrement();
19884        mHandler.post(new Runnable() {
19885            @Override
19886            public void run() {
19887                try {
19888                    movePackageInternal(packageName, volumeUuid, moveId, user);
19889                } catch (PackageManagerException e) {
19890                    Slog.w(TAG, "Failed to move " + packageName, e);
19891                    mMoveCallbacks.notifyStatusChanged(moveId,
19892                            PackageManager.MOVE_FAILED_INTERNAL_ERROR);
19893                }
19894            }
19895        });
19896        return moveId;
19897    }
19898
19899    private void movePackageInternal(final String packageName, final String volumeUuid,
19900            final int moveId, UserHandle user) throws PackageManagerException {
19901        final StorageManager storage = mContext.getSystemService(StorageManager.class);
19902        final PackageManager pm = mContext.getPackageManager();
19903
19904        final boolean currentAsec;
19905        final String currentVolumeUuid;
19906        final File codeFile;
19907        final String installerPackageName;
19908        final String packageAbiOverride;
19909        final int appId;
19910        final String seinfo;
19911        final String label;
19912        final int targetSdkVersion;
19913        final PackageFreezer freezer;
19914        final int[] installedUserIds;
19915
19916        // reader
19917        synchronized (mPackages) {
19918            final PackageParser.Package pkg = mPackages.get(packageName);
19919            final PackageSetting ps = mSettings.mPackages.get(packageName);
19920            if (pkg == null || ps == null) {
19921                throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package");
19922            }
19923
19924            if (pkg.applicationInfo.isSystemApp()) {
19925                throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE,
19926                        "Cannot move system application");
19927            }
19928
19929            if (pkg.applicationInfo.isExternalAsec()) {
19930                currentAsec = true;
19931                currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL;
19932            } else if (pkg.applicationInfo.isForwardLocked()) {
19933                currentAsec = true;
19934                currentVolumeUuid = "forward_locked";
19935            } else {
19936                currentAsec = false;
19937                currentVolumeUuid = ps.volumeUuid;
19938
19939                final File probe = new File(pkg.codePath);
19940                final File probeOat = new File(probe, "oat");
19941                if (!probe.isDirectory() || !probeOat.isDirectory()) {
19942                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
19943                            "Move only supported for modern cluster style installs");
19944                }
19945            }
19946
19947            if (Objects.equals(currentVolumeUuid, volumeUuid)) {
19948                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
19949                        "Package already moved to " + volumeUuid);
19950            }
19951            if (pkg.applicationInfo.isInternal() && isPackageDeviceAdminOnAnyUser(packageName)) {
19952                throw new PackageManagerException(MOVE_FAILED_DEVICE_ADMIN,
19953                        "Device admin cannot be moved");
19954            }
19955
19956            if (mFrozenPackages.contains(packageName)) {
19957                throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING,
19958                        "Failed to move already frozen package");
19959            }
19960
19961            codeFile = new File(pkg.codePath);
19962            installerPackageName = ps.installerPackageName;
19963            packageAbiOverride = ps.cpuAbiOverrideString;
19964            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
19965            seinfo = pkg.applicationInfo.seinfo;
19966            label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo));
19967            targetSdkVersion = pkg.applicationInfo.targetSdkVersion;
19968            freezer = freezePackage(packageName, "movePackageInternal");
19969            installedUserIds = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
19970        }
19971
19972        final Bundle extras = new Bundle();
19973        extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName);
19974        extras.putString(Intent.EXTRA_TITLE, label);
19975        mMoveCallbacks.notifyCreated(moveId, extras);
19976
19977        int installFlags;
19978        final boolean moveCompleteApp;
19979        final File measurePath;
19980
19981        if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) {
19982            installFlags = INSTALL_INTERNAL;
19983            moveCompleteApp = !currentAsec;
19984            measurePath = Environment.getDataAppDirectory(volumeUuid);
19985        } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) {
19986            installFlags = INSTALL_EXTERNAL;
19987            moveCompleteApp = false;
19988            measurePath = storage.getPrimaryPhysicalVolume().getPath();
19989        } else {
19990            final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid);
19991            if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE
19992                    || !volume.isMountedWritable()) {
19993                freezer.close();
19994                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
19995                        "Move location not mounted private volume");
19996            }
19997
19998            Preconditions.checkState(!currentAsec);
19999
20000            installFlags = INSTALL_INTERNAL;
20001            moveCompleteApp = true;
20002            measurePath = Environment.getDataAppDirectory(volumeUuid);
20003        }
20004
20005        final PackageStats stats = new PackageStats(null, -1);
20006        synchronized (mInstaller) {
20007            for (int userId : installedUserIds) {
20008                if (!getPackageSizeInfoLI(packageName, userId, stats)) {
20009                    freezer.close();
20010                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
20011                            "Failed to measure package size");
20012                }
20013            }
20014        }
20015
20016        if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size "
20017                + stats.dataSize);
20018
20019        final long startFreeBytes = measurePath.getFreeSpace();
20020        final long sizeBytes;
20021        if (moveCompleteApp) {
20022            sizeBytes = stats.codeSize + stats.dataSize;
20023        } else {
20024            sizeBytes = stats.codeSize;
20025        }
20026
20027        if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) {
20028            freezer.close();
20029            throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
20030                    "Not enough free space to move");
20031        }
20032
20033        mMoveCallbacks.notifyStatusChanged(moveId, 10);
20034
20035        final CountDownLatch installedLatch = new CountDownLatch(1);
20036        final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
20037            @Override
20038            public void onUserActionRequired(Intent intent) throws RemoteException {
20039                throw new IllegalStateException();
20040            }
20041
20042            @Override
20043            public void onPackageInstalled(String basePackageName, int returnCode, String msg,
20044                    Bundle extras) throws RemoteException {
20045                if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: "
20046                        + PackageManager.installStatusToString(returnCode, msg));
20047
20048                installedLatch.countDown();
20049                freezer.close();
20050
20051                final int status = PackageManager.installStatusToPublicStatus(returnCode);
20052                switch (status) {
20053                    case PackageInstaller.STATUS_SUCCESS:
20054                        mMoveCallbacks.notifyStatusChanged(moveId,
20055                                PackageManager.MOVE_SUCCEEDED);
20056                        break;
20057                    case PackageInstaller.STATUS_FAILURE_STORAGE:
20058                        mMoveCallbacks.notifyStatusChanged(moveId,
20059                                PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
20060                        break;
20061                    default:
20062                        mMoveCallbacks.notifyStatusChanged(moveId,
20063                                PackageManager.MOVE_FAILED_INTERNAL_ERROR);
20064                        break;
20065                }
20066            }
20067        };
20068
20069        final MoveInfo move;
20070        if (moveCompleteApp) {
20071            // Kick off a thread to report progress estimates
20072            new Thread() {
20073                @Override
20074                public void run() {
20075                    while (true) {
20076                        try {
20077                            if (installedLatch.await(1, TimeUnit.SECONDS)) {
20078                                break;
20079                            }
20080                        } catch (InterruptedException ignored) {
20081                        }
20082
20083                        final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace();
20084                        final int progress = 10 + (int) MathUtils.constrain(
20085                                ((deltaFreeBytes * 80) / sizeBytes), 0, 80);
20086                        mMoveCallbacks.notifyStatusChanged(moveId, progress);
20087                    }
20088                }
20089            }.start();
20090
20091            final String dataAppName = codeFile.getName();
20092            move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName,
20093                    dataAppName, appId, seinfo, targetSdkVersion);
20094        } else {
20095            move = null;
20096        }
20097
20098        installFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
20099
20100        final Message msg = mHandler.obtainMessage(INIT_COPY);
20101        final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
20102        final InstallParams params = new InstallParams(origin, move, installObserver, installFlags,
20103                installerPackageName, volumeUuid, null /*verificationInfo*/, user,
20104                packageAbiOverride, null /*grantedPermissions*/, null /*certificates*/);
20105        params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params));
20106        msg.obj = params;
20107
20108        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage",
20109                System.identityHashCode(msg.obj));
20110        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
20111                System.identityHashCode(msg.obj));
20112
20113        mHandler.sendMessage(msg);
20114    }
20115
20116    @Override
20117    public int movePrimaryStorage(String volumeUuid) throws RemoteException {
20118        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
20119
20120        final int realMoveId = mNextMoveId.getAndIncrement();
20121        final Bundle extras = new Bundle();
20122        extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid);
20123        mMoveCallbacks.notifyCreated(realMoveId, extras);
20124
20125        final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() {
20126            @Override
20127            public void onCreated(int moveId, Bundle extras) {
20128                // Ignored
20129            }
20130
20131            @Override
20132            public void onStatusChanged(int moveId, int status, long estMillis) {
20133                mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis);
20134            }
20135        };
20136
20137        final StorageManager storage = mContext.getSystemService(StorageManager.class);
20138        storage.setPrimaryStorageUuid(volumeUuid, callback);
20139        return realMoveId;
20140    }
20141
20142    @Override
20143    public int getMoveStatus(int moveId) {
20144        mContext.enforceCallingOrSelfPermission(
20145                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
20146        return mMoveCallbacks.mLastStatus.get(moveId);
20147    }
20148
20149    @Override
20150    public void registerMoveCallback(IPackageMoveObserver callback) {
20151        mContext.enforceCallingOrSelfPermission(
20152                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
20153        mMoveCallbacks.register(callback);
20154    }
20155
20156    @Override
20157    public void unregisterMoveCallback(IPackageMoveObserver callback) {
20158        mContext.enforceCallingOrSelfPermission(
20159                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
20160        mMoveCallbacks.unregister(callback);
20161    }
20162
20163    @Override
20164    public boolean setInstallLocation(int loc) {
20165        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
20166                null);
20167        if (getInstallLocation() == loc) {
20168            return true;
20169        }
20170        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
20171                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
20172            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
20173                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
20174            return true;
20175        }
20176        return false;
20177   }
20178
20179    @Override
20180    public int getInstallLocation() {
20181        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
20182                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
20183                PackageHelper.APP_INSTALL_AUTO);
20184    }
20185
20186    /** Called by UserManagerService */
20187    void cleanUpUser(UserManagerService userManager, int userHandle) {
20188        synchronized (mPackages) {
20189            mDirtyUsers.remove(userHandle);
20190            mUserNeedsBadging.delete(userHandle);
20191            mSettings.removeUserLPw(userHandle);
20192            mPendingBroadcasts.remove(userHandle);
20193            mEphemeralApplicationRegistry.onUserRemovedLPw(userHandle);
20194            removeUnusedPackagesLPw(userManager, userHandle);
20195        }
20196    }
20197
20198    /**
20199     * We're removing userHandle and would like to remove any downloaded packages
20200     * that are no longer in use by any other user.
20201     * @param userHandle the user being removed
20202     */
20203    private void removeUnusedPackagesLPw(UserManagerService userManager, final int userHandle) {
20204        final boolean DEBUG_CLEAN_APKS = false;
20205        int [] users = userManager.getUserIds();
20206        Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
20207        while (psit.hasNext()) {
20208            PackageSetting ps = psit.next();
20209            if (ps.pkg == null) {
20210                continue;
20211            }
20212            final String packageName = ps.pkg.packageName;
20213            // Skip over if system app
20214            if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
20215                continue;
20216            }
20217            if (DEBUG_CLEAN_APKS) {
20218                Slog.i(TAG, "Checking package " + packageName);
20219            }
20220            boolean keep = shouldKeepUninstalledPackageLPr(packageName);
20221            if (keep) {
20222                if (DEBUG_CLEAN_APKS) {
20223                    Slog.i(TAG, "  Keeping package " + packageName + " - requested by DO");
20224                }
20225            } else {
20226                for (int i = 0; i < users.length; i++) {
20227                    if (users[i] != userHandle && ps.getInstalled(users[i])) {
20228                        keep = true;
20229                        if (DEBUG_CLEAN_APKS) {
20230                            Slog.i(TAG, "  Keeping package " + packageName + " for user "
20231                                    + users[i]);
20232                        }
20233                        break;
20234                    }
20235                }
20236            }
20237            if (!keep) {
20238                if (DEBUG_CLEAN_APKS) {
20239                    Slog.i(TAG, "  Removing package " + packageName);
20240                }
20241                mHandler.post(new Runnable() {
20242                    public void run() {
20243                        deletePackageX(packageName, userHandle, 0);
20244                    } //end run
20245                });
20246            }
20247        }
20248    }
20249
20250    /** Called by UserManagerService */
20251    void createNewUser(int userId) {
20252        synchronized (mInstallLock) {
20253            mSettings.createNewUserLI(this, mInstaller, userId);
20254        }
20255        synchronized (mPackages) {
20256            scheduleWritePackageRestrictionsLocked(userId);
20257            scheduleWritePackageListLocked(userId);
20258            applyFactoryDefaultBrowserLPw(userId);
20259            primeDomainVerificationsLPw(userId);
20260        }
20261    }
20262
20263    void onBeforeUserStartUninitialized(final int userId) {
20264        synchronized (mPackages) {
20265            if (mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) {
20266                return;
20267            }
20268        }
20269        mDefaultPermissionPolicy.grantDefaultPermissions(userId);
20270        // If permission review for legacy apps is required, we represent
20271        // dagerous permissions for such apps as always granted runtime
20272        // permissions to keep per user flag state whether review is needed.
20273        // Hence, if a new user is added we have to propagate dangerous
20274        // permission grants for these legacy apps.
20275        if (Build.PERMISSIONS_REVIEW_REQUIRED) {
20276            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
20277                    | UPDATE_PERMISSIONS_REPLACE_ALL);
20278        }
20279    }
20280
20281    @Override
20282    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
20283        mContext.enforceCallingOrSelfPermission(
20284                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
20285                "Only package verification agents can read the verifier device identity");
20286
20287        synchronized (mPackages) {
20288            return mSettings.getVerifierDeviceIdentityLPw();
20289        }
20290    }
20291
20292    @Override
20293    public void setPermissionEnforced(String permission, boolean enforced) {
20294        // TODO: Now that we no longer change GID for storage, this should to away.
20295        mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
20296                "setPermissionEnforced");
20297        if (READ_EXTERNAL_STORAGE.equals(permission)) {
20298            synchronized (mPackages) {
20299                if (mSettings.mReadExternalStorageEnforced == null
20300                        || mSettings.mReadExternalStorageEnforced != enforced) {
20301                    mSettings.mReadExternalStorageEnforced = enforced;
20302                    mSettings.writeLPr();
20303                }
20304            }
20305            // kill any non-foreground processes so we restart them and
20306            // grant/revoke the GID.
20307            final IActivityManager am = ActivityManagerNative.getDefault();
20308            if (am != null) {
20309                final long token = Binder.clearCallingIdentity();
20310                try {
20311                    am.killProcessesBelowForeground("setPermissionEnforcement");
20312                } catch (RemoteException e) {
20313                } finally {
20314                    Binder.restoreCallingIdentity(token);
20315                }
20316            }
20317        } else {
20318            throw new IllegalArgumentException("No selective enforcement for " + permission);
20319        }
20320    }
20321
20322    @Override
20323    @Deprecated
20324    public boolean isPermissionEnforced(String permission) {
20325        return true;
20326    }
20327
20328    @Override
20329    public boolean isStorageLow() {
20330        final long token = Binder.clearCallingIdentity();
20331        try {
20332            final DeviceStorageMonitorInternal
20333                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
20334            if (dsm != null) {
20335                return dsm.isMemoryLow();
20336            } else {
20337                return false;
20338            }
20339        } finally {
20340            Binder.restoreCallingIdentity(token);
20341        }
20342    }
20343
20344    @Override
20345    public IPackageInstaller getPackageInstaller() {
20346        return mInstallerService;
20347    }
20348
20349    private boolean userNeedsBadging(int userId) {
20350        int index = mUserNeedsBadging.indexOfKey(userId);
20351        if (index < 0) {
20352            final UserInfo userInfo;
20353            final long token = Binder.clearCallingIdentity();
20354            try {
20355                userInfo = sUserManager.getUserInfo(userId);
20356            } finally {
20357                Binder.restoreCallingIdentity(token);
20358            }
20359            final boolean b;
20360            if (userInfo != null && userInfo.isManagedProfile()) {
20361                b = true;
20362            } else {
20363                b = false;
20364            }
20365            mUserNeedsBadging.put(userId, b);
20366            return b;
20367        }
20368        return mUserNeedsBadging.valueAt(index);
20369    }
20370
20371    @Override
20372    public KeySet getKeySetByAlias(String packageName, String alias) {
20373        if (packageName == null || alias == null) {
20374            return null;
20375        }
20376        synchronized(mPackages) {
20377            final PackageParser.Package pkg = mPackages.get(packageName);
20378            if (pkg == null) {
20379                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
20380                throw new IllegalArgumentException("Unknown package: " + packageName);
20381            }
20382            KeySetManagerService ksms = mSettings.mKeySetManagerService;
20383            return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
20384        }
20385    }
20386
20387    @Override
20388    public KeySet getSigningKeySet(String packageName) {
20389        if (packageName == null) {
20390            return null;
20391        }
20392        synchronized(mPackages) {
20393            final PackageParser.Package pkg = mPackages.get(packageName);
20394            if (pkg == null) {
20395                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
20396                throw new IllegalArgumentException("Unknown package: " + packageName);
20397            }
20398            if (pkg.applicationInfo.uid != Binder.getCallingUid()
20399                    && Process.SYSTEM_UID != Binder.getCallingUid()) {
20400                throw new SecurityException("May not access signing KeySet of other apps.");
20401            }
20402            KeySetManagerService ksms = mSettings.mKeySetManagerService;
20403            return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
20404        }
20405    }
20406
20407    @Override
20408    public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
20409        if (packageName == null || ks == null) {
20410            return false;
20411        }
20412        synchronized(mPackages) {
20413            final PackageParser.Package pkg = mPackages.get(packageName);
20414            if (pkg == null) {
20415                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
20416                throw new IllegalArgumentException("Unknown package: " + packageName);
20417            }
20418            IBinder ksh = ks.getToken();
20419            if (ksh instanceof KeySetHandle) {
20420                KeySetManagerService ksms = mSettings.mKeySetManagerService;
20421                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
20422            }
20423            return false;
20424        }
20425    }
20426
20427    @Override
20428    public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
20429        if (packageName == null || ks == null) {
20430            return false;
20431        }
20432        synchronized(mPackages) {
20433            final PackageParser.Package pkg = mPackages.get(packageName);
20434            if (pkg == null) {
20435                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
20436                throw new IllegalArgumentException("Unknown package: " + packageName);
20437            }
20438            IBinder ksh = ks.getToken();
20439            if (ksh instanceof KeySetHandle) {
20440                KeySetManagerService ksms = mSettings.mKeySetManagerService;
20441                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
20442            }
20443            return false;
20444        }
20445    }
20446
20447    private void deletePackageIfUnusedLPr(final String packageName) {
20448        PackageSetting ps = mSettings.mPackages.get(packageName);
20449        if (ps == null) {
20450            return;
20451        }
20452        if (!ps.isAnyInstalled(sUserManager.getUserIds())) {
20453            // TODO Implement atomic delete if package is unused
20454            // It is currently possible that the package will be deleted even if it is installed
20455            // after this method returns.
20456            mHandler.post(new Runnable() {
20457                public void run() {
20458                    deletePackageX(packageName, 0, PackageManager.DELETE_ALL_USERS);
20459                }
20460            });
20461        }
20462    }
20463
20464    /**
20465     * Check and throw if the given before/after packages would be considered a
20466     * downgrade.
20467     */
20468    private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after)
20469            throws PackageManagerException {
20470        if (after.versionCode < before.mVersionCode) {
20471            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
20472                    "Update version code " + after.versionCode + " is older than current "
20473                    + before.mVersionCode);
20474        } else if (after.versionCode == before.mVersionCode) {
20475            if (after.baseRevisionCode < before.baseRevisionCode) {
20476                throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
20477                        "Update base revision code " + after.baseRevisionCode
20478                        + " is older than current " + before.baseRevisionCode);
20479            }
20480
20481            if (!ArrayUtils.isEmpty(after.splitNames)) {
20482                for (int i = 0; i < after.splitNames.length; i++) {
20483                    final String splitName = after.splitNames[i];
20484                    final int j = ArrayUtils.indexOf(before.splitNames, splitName);
20485                    if (j != -1) {
20486                        if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) {
20487                            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
20488                                    "Update split " + splitName + " revision code "
20489                                    + after.splitRevisionCodes[i] + " is older than current "
20490                                    + before.splitRevisionCodes[j]);
20491                        }
20492                    }
20493                }
20494            }
20495        }
20496    }
20497
20498    private static class MoveCallbacks extends Handler {
20499        private static final int MSG_CREATED = 1;
20500        private static final int MSG_STATUS_CHANGED = 2;
20501
20502        private final RemoteCallbackList<IPackageMoveObserver>
20503                mCallbacks = new RemoteCallbackList<>();
20504
20505        private final SparseIntArray mLastStatus = new SparseIntArray();
20506
20507        public MoveCallbacks(Looper looper) {
20508            super(looper);
20509        }
20510
20511        public void register(IPackageMoveObserver callback) {
20512            mCallbacks.register(callback);
20513        }
20514
20515        public void unregister(IPackageMoveObserver callback) {
20516            mCallbacks.unregister(callback);
20517        }
20518
20519        @Override
20520        public void handleMessage(Message msg) {
20521            final SomeArgs args = (SomeArgs) msg.obj;
20522            final int n = mCallbacks.beginBroadcast();
20523            for (int i = 0; i < n; i++) {
20524                final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i);
20525                try {
20526                    invokeCallback(callback, msg.what, args);
20527                } catch (RemoteException ignored) {
20528                }
20529            }
20530            mCallbacks.finishBroadcast();
20531            args.recycle();
20532        }
20533
20534        private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args)
20535                throws RemoteException {
20536            switch (what) {
20537                case MSG_CREATED: {
20538                    callback.onCreated(args.argi1, (Bundle) args.arg2);
20539                    break;
20540                }
20541                case MSG_STATUS_CHANGED: {
20542                    callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3);
20543                    break;
20544                }
20545            }
20546        }
20547
20548        private void notifyCreated(int moveId, Bundle extras) {
20549            Slog.v(TAG, "Move " + moveId + " created " + extras.toString());
20550
20551            final SomeArgs args = SomeArgs.obtain();
20552            args.argi1 = moveId;
20553            args.arg2 = extras;
20554            obtainMessage(MSG_CREATED, args).sendToTarget();
20555        }
20556
20557        private void notifyStatusChanged(int moveId, int status) {
20558            notifyStatusChanged(moveId, status, -1);
20559        }
20560
20561        private void notifyStatusChanged(int moveId, int status, long estMillis) {
20562            Slog.v(TAG, "Move " + moveId + " status " + status);
20563
20564            final SomeArgs args = SomeArgs.obtain();
20565            args.argi1 = moveId;
20566            args.argi2 = status;
20567            args.arg3 = estMillis;
20568            obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget();
20569
20570            synchronized (mLastStatus) {
20571                mLastStatus.put(moveId, status);
20572            }
20573        }
20574    }
20575
20576    private final static class OnPermissionChangeListeners extends Handler {
20577        private static final int MSG_ON_PERMISSIONS_CHANGED = 1;
20578
20579        private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners =
20580                new RemoteCallbackList<>();
20581
20582        public OnPermissionChangeListeners(Looper looper) {
20583            super(looper);
20584        }
20585
20586        @Override
20587        public void handleMessage(Message msg) {
20588            switch (msg.what) {
20589                case MSG_ON_PERMISSIONS_CHANGED: {
20590                    final int uid = msg.arg1;
20591                    handleOnPermissionsChanged(uid);
20592                } break;
20593            }
20594        }
20595
20596        public void addListenerLocked(IOnPermissionsChangeListener listener) {
20597            mPermissionListeners.register(listener);
20598
20599        }
20600
20601        public void removeListenerLocked(IOnPermissionsChangeListener listener) {
20602            mPermissionListeners.unregister(listener);
20603        }
20604
20605        public void onPermissionsChanged(int uid) {
20606            if (mPermissionListeners.getRegisteredCallbackCount() > 0) {
20607                obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget();
20608            }
20609        }
20610
20611        private void handleOnPermissionsChanged(int uid) {
20612            final int count = mPermissionListeners.beginBroadcast();
20613            try {
20614                for (int i = 0; i < count; i++) {
20615                    IOnPermissionsChangeListener callback = mPermissionListeners
20616                            .getBroadcastItem(i);
20617                    try {
20618                        callback.onPermissionsChanged(uid);
20619                    } catch (RemoteException e) {
20620                        Log.e(TAG, "Permission listener is dead", e);
20621                    }
20622                }
20623            } finally {
20624                mPermissionListeners.finishBroadcast();
20625            }
20626        }
20627    }
20628
20629    private class PackageManagerInternalImpl extends PackageManagerInternal {
20630        @Override
20631        public void setLocationPackagesProvider(PackagesProvider provider) {
20632            synchronized (mPackages) {
20633                mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider);
20634            }
20635        }
20636
20637        @Override
20638        public void setVoiceInteractionPackagesProvider(PackagesProvider provider) {
20639            synchronized (mPackages) {
20640                mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider);
20641            }
20642        }
20643
20644        @Override
20645        public void setSmsAppPackagesProvider(PackagesProvider provider) {
20646            synchronized (mPackages) {
20647                mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider);
20648            }
20649        }
20650
20651        @Override
20652        public void setDialerAppPackagesProvider(PackagesProvider provider) {
20653            synchronized (mPackages) {
20654                mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider);
20655            }
20656        }
20657
20658        @Override
20659        public void setSimCallManagerPackagesProvider(PackagesProvider provider) {
20660            synchronized (mPackages) {
20661                mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider);
20662            }
20663        }
20664
20665        @Override
20666        public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) {
20667            synchronized (mPackages) {
20668                mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider);
20669            }
20670        }
20671
20672        @Override
20673        public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) {
20674            synchronized (mPackages) {
20675                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr(
20676                        packageName, userId);
20677            }
20678        }
20679
20680        @Override
20681        public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) {
20682            synchronized (mPackages) {
20683                mSettings.setDefaultDialerPackageNameLPw(packageName, userId);
20684                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr(
20685                        packageName, userId);
20686            }
20687        }
20688
20689        @Override
20690        public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) {
20691            synchronized (mPackages) {
20692                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr(
20693                        packageName, userId);
20694            }
20695        }
20696
20697        @Override
20698        public void setKeepUninstalledPackages(final List<String> packageList) {
20699            Preconditions.checkNotNull(packageList);
20700            List<String> removedFromList = null;
20701            synchronized (mPackages) {
20702                if (mKeepUninstalledPackages != null) {
20703                    final int packagesCount = mKeepUninstalledPackages.size();
20704                    for (int i = 0; i < packagesCount; i++) {
20705                        String oldPackage = mKeepUninstalledPackages.get(i);
20706                        if (packageList != null && packageList.contains(oldPackage)) {
20707                            continue;
20708                        }
20709                        if (removedFromList == null) {
20710                            removedFromList = new ArrayList<>();
20711                        }
20712                        removedFromList.add(oldPackage);
20713                    }
20714                }
20715                mKeepUninstalledPackages = new ArrayList<>(packageList);
20716                if (removedFromList != null) {
20717                    final int removedCount = removedFromList.size();
20718                    for (int i = 0; i < removedCount; i++) {
20719                        deletePackageIfUnusedLPr(removedFromList.get(i));
20720                    }
20721                }
20722            }
20723        }
20724
20725        @Override
20726        public boolean isPermissionsReviewRequired(String packageName, int userId) {
20727            synchronized (mPackages) {
20728                // If we do not support permission review, done.
20729                if (!Build.PERMISSIONS_REVIEW_REQUIRED) {
20730                    return false;
20731                }
20732
20733                PackageSetting packageSetting = mSettings.mPackages.get(packageName);
20734                if (packageSetting == null) {
20735                    return false;
20736                }
20737
20738                // Permission review applies only to apps not supporting the new permission model.
20739                if (packageSetting.pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.M) {
20740                    return false;
20741                }
20742
20743                // Legacy apps have the permission and get user consent on launch.
20744                PermissionsState permissionsState = packageSetting.getPermissionsState();
20745                return permissionsState.isPermissionReviewRequired(userId);
20746            }
20747        }
20748
20749        @Override
20750        public ApplicationInfo getApplicationInfo(String packageName, int userId) {
20751            return PackageManagerService.this.getApplicationInfo(packageName, 0 /*flags*/, userId);
20752        }
20753
20754        @Override
20755        public ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
20756                int userId) {
20757            return PackageManagerService.this.getHomeActivitiesAsUser(allHomeCandidates, userId);
20758        }
20759
20760        @Override
20761        public void setDeviceAndProfileOwnerPackages(
20762                int deviceOwnerUserId, String deviceOwnerPackage,
20763                SparseArray<String> profileOwnerPackages) {
20764            mProtectedPackages.setDeviceAndProfileOwnerPackages(
20765                    deviceOwnerUserId, deviceOwnerPackage, profileOwnerPackages);
20766        }
20767
20768        @Override
20769        public boolean canPackageBeWiped(int userId, String packageName) {
20770            return mProtectedPackages.canPackageBeWiped(userId,
20771                    packageName);
20772        }
20773    }
20774
20775    @Override
20776    public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) {
20777        enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps");
20778        synchronized (mPackages) {
20779            final long identity = Binder.clearCallingIdentity();
20780            try {
20781                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr(
20782                        packageNames, userId);
20783            } finally {
20784                Binder.restoreCallingIdentity(identity);
20785            }
20786        }
20787    }
20788
20789    private static void enforceSystemOrPhoneCaller(String tag) {
20790        int callingUid = Binder.getCallingUid();
20791        if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) {
20792            throw new SecurityException(
20793                    "Cannot call " + tag + " from UID " + callingUid);
20794        }
20795    }
20796
20797    boolean isHistoricalPackageUsageAvailable() {
20798        return mPackageUsage.isHistoricalPackageUsageAvailable();
20799    }
20800
20801    /**
20802     * Return a <b>copy</b> of the collection of packages known to the package manager.
20803     * @return A copy of the values of mPackages.
20804     */
20805    Collection<PackageParser.Package> getPackages() {
20806        synchronized (mPackages) {
20807            return new ArrayList<>(mPackages.values());
20808        }
20809    }
20810
20811    /**
20812     * Logs process start information (including base APK hash) to the security log.
20813     * @hide
20814     */
20815    public void logAppProcessStartIfNeeded(String processName, int uid, String seinfo,
20816            String apkFile, int pid) {
20817        if (!SecurityLog.isLoggingEnabled()) {
20818            return;
20819        }
20820        Bundle data = new Bundle();
20821        data.putLong("startTimestamp", System.currentTimeMillis());
20822        data.putString("processName", processName);
20823        data.putInt("uid", uid);
20824        data.putString("seinfo", seinfo);
20825        data.putString("apkFile", apkFile);
20826        data.putInt("pid", pid);
20827        Message msg = mProcessLoggingHandler.obtainMessage(
20828                ProcessLoggingHandler.LOG_APP_PROCESS_START_MSG);
20829        msg.setData(data);
20830        mProcessLoggingHandler.sendMessage(msg);
20831    }
20832
20833    public CompilerStats.PackageStats getCompilerPackageStats(String pkgName) {
20834        return mCompilerStats.getPackageStats(pkgName);
20835    }
20836
20837    public CompilerStats.PackageStats getOrCreateCompilerPackageStats(PackageParser.Package pkg) {
20838        return getOrCreateCompilerPackageStats(pkg.packageName);
20839    }
20840
20841    public CompilerStats.PackageStats getOrCreateCompilerPackageStats(String pkgName) {
20842        return mCompilerStats.getOrCreatePackageStats(pkgName);
20843    }
20844
20845    public void deleteCompilerPackageStats(String pkgName) {
20846        mCompilerStats.deletePackageStats(pkgName);
20847    }
20848}
20849