PackageManagerService.java revision 069ed7003b3de1f87d28413cc2debc9042386d3c
1/*
2 * Copyright (C) 2006 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server.pm;
18
19import static android.Manifest.permission.READ_EXTERNAL_STORAGE;
20import static android.Manifest.permission.WRITE_EXTERNAL_STORAGE;
21import static android.Manifest.permission.WRITE_MEDIA_STORAGE;
22import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DEFAULT;
23import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED;
24import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED;
25import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER;
26import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_ENABLED;
27import static android.content.pm.PackageManager.DELETE_KEEP_DATA;
28import static android.content.pm.PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
29import static android.content.pm.PackageManager.FLAG_PERMISSION_POLICY_FIXED;
30import static android.content.pm.PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
31import static android.content.pm.PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE;
32import static android.content.pm.PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
33import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_FIXED;
34import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_SET;
35import static android.content.pm.PackageManager.INSTALL_EXTERNAL;
36import static android.content.pm.PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
37import static android.content.pm.PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER;
38import static android.content.pm.PackageManager.INSTALL_FAILED_DEXOPT;
39import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
40import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION;
41import static android.content.pm.PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID;
42import static android.content.pm.PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
43import static android.content.pm.PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
44import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_APK;
45import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
46import static android.content.pm.PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY;
47import static android.content.pm.PackageManager.INSTALL_FAILED_PACKAGE_CHANGED;
48import static android.content.pm.PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
49import static android.content.pm.PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE;
50import static android.content.pm.PackageManager.INSTALL_FAILED_TEST_ONLY;
51import static android.content.pm.PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE;
52import static android.content.pm.PackageManager.INSTALL_FAILED_USER_RESTRICTED;
53import static android.content.pm.PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
54import static android.content.pm.PackageManager.INSTALL_FORWARD_LOCK;
55import static android.content.pm.PackageManager.INSTALL_INTERNAL;
56import static android.content.pm.PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
57import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
58import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK;
59import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
60import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER;
61import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
62import static android.content.pm.PackageManager.MATCH_ALL;
63import static android.content.pm.PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
64import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_AWARE;
65import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_UNAWARE;
66import static android.content.pm.PackageManager.MATCH_DISABLED_COMPONENTS;
67import static android.content.pm.PackageManager.MATCH_FACTORY_ONLY;
68import static android.content.pm.PackageManager.MATCH_SYSTEM_ONLY;
69import static android.content.pm.PackageManager.MATCH_UNINSTALLED_PACKAGES;
70import static android.content.pm.PackageManager.MOVE_FAILED_DEVICE_ADMIN;
71import static android.content.pm.PackageManager.MOVE_FAILED_DOESNT_EXIST;
72import static android.content.pm.PackageManager.MOVE_FAILED_INTERNAL_ERROR;
73import static android.content.pm.PackageManager.MOVE_FAILED_OPERATION_PENDING;
74import static android.content.pm.PackageManager.MOVE_FAILED_SYSTEM_PACKAGE;
75import static android.content.pm.PackageManager.PERMISSION_DENIED;
76import static android.content.pm.PackageManager.PERMISSION_GRANTED;
77import static android.content.pm.PackageParser.PARSE_IS_PRIVILEGED;
78import static android.content.pm.PackageParser.isApkFile;
79import static android.os.Process.PACKAGE_INFO_GID;
80import static android.os.Process.SYSTEM_UID;
81import static android.os.Trace.TRACE_TAG_PACKAGE_MANAGER;
82import static android.system.OsConstants.O_CREAT;
83import static android.system.OsConstants.O_RDWR;
84
85import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE;
86import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_PARENT;
87import static com.android.internal.content.NativeLibraryHelper.LIB64_DIR_NAME;
88import static com.android.internal.content.NativeLibraryHelper.LIB_DIR_NAME;
89import static com.android.internal.util.ArrayUtils.appendInt;
90import static com.android.server.pm.Installer.DEXOPT_PUBLIC;
91import static com.android.server.pm.InstructionSets.getAppDexInstructionSets;
92import static com.android.server.pm.InstructionSets.getDexCodeInstructionSet;
93import static com.android.server.pm.InstructionSets.getDexCodeInstructionSets;
94import static com.android.server.pm.InstructionSets.getPreferredInstructionSet;
95import static com.android.server.pm.InstructionSets.getPrimaryInstructionSet;
96import static com.android.server.pm.PackageManagerServiceCompilerMapping.getCompilerFilterForReason;
97import static com.android.server.pm.PackageManagerServiceCompilerMapping.getFullCompilerFilter;
98import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_FAILURE;
99import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS;
100import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED;
101
102import android.Manifest;
103import android.annotation.NonNull;
104import android.annotation.Nullable;
105import android.app.ActivityManager;
106import android.app.ActivityManagerNative;
107import android.app.IActivityManager;
108import android.app.admin.DevicePolicyManagerInternal;
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.storage.IMountService;
193import android.os.storage.MountServiceInternal;
194import android.os.storage.StorageEventListener;
195import android.os.storage.StorageManager;
196import android.os.storage.VolumeInfo;
197import android.os.storage.VolumeRecord;
198import android.security.KeyStore;
199import android.security.SystemKeyStore;
200import android.system.ErrnoException;
201import android.system.Os;
202import android.text.TextUtils;
203import android.text.format.DateUtils;
204import android.util.ArrayMap;
205import android.util.ArraySet;
206import android.util.AtomicFile;
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.os.IParcelFileDescriptorFactory;
229import com.android.internal.os.InstallerConnection.InstallerException;
230import com.android.internal.os.SomeArgs;
231import com.android.internal.os.Zygote;
232import com.android.internal.telephony.CarrierAppUtils;
233import com.android.internal.util.ArrayUtils;
234import com.android.internal.util.FastPrintWriter;
235import com.android.internal.util.FastXmlSerializer;
236import com.android.internal.util.IndentingPrintWriter;
237import com.android.internal.util.Preconditions;
238import com.android.internal.util.XmlUtils;
239import com.android.server.EventLogTags;
240import com.android.server.FgThread;
241import com.android.server.IntentResolver;
242import com.android.server.LocalServices;
243import com.android.server.ServiceThread;
244import com.android.server.SystemConfig;
245import com.android.server.Watchdog;
246import com.android.server.pm.PermissionsState.PermissionState;
247import com.android.server.pm.Settings.DatabaseVersion;
248import com.android.server.pm.Settings.VersionInfo;
249import com.android.server.storage.DeviceStorageMonitorInternal;
250
251import dalvik.system.CloseGuard;
252import dalvik.system.DexFile;
253import dalvik.system.VMRuntime;
254
255import libcore.io.IoUtils;
256import libcore.util.EmptyArray;
257
258import org.xmlpull.v1.XmlPullParser;
259import org.xmlpull.v1.XmlPullParserException;
260import org.xmlpull.v1.XmlSerializer;
261
262import java.io.BufferedInputStream;
263import java.io.BufferedOutputStream;
264import java.io.BufferedReader;
265import java.io.ByteArrayInputStream;
266import java.io.ByteArrayOutputStream;
267import java.io.File;
268import java.io.FileDescriptor;
269import java.io.FileNotFoundException;
270import java.io.FileOutputStream;
271import java.io.FileReader;
272import java.io.FilenameFilter;
273import java.io.IOException;
274import java.io.InputStream;
275import java.io.PrintWriter;
276import java.nio.charset.StandardCharsets;
277import java.security.MessageDigest;
278import java.security.NoSuchAlgorithmException;
279import java.security.PublicKey;
280import java.security.cert.Certificate;
281import java.security.cert.CertificateEncodingException;
282import java.security.cert.CertificateException;
283import java.text.SimpleDateFormat;
284import java.util.ArrayList;
285import java.util.Arrays;
286import java.util.Collection;
287import java.util.Collections;
288import java.util.Comparator;
289import java.util.Date;
290import java.util.HashSet;
291import java.util.Iterator;
292import java.util.List;
293import java.util.Map;
294import java.util.Objects;
295import java.util.Set;
296import java.util.concurrent.CountDownLatch;
297import java.util.concurrent.TimeUnit;
298import java.util.concurrent.atomic.AtomicBoolean;
299import java.util.concurrent.atomic.AtomicInteger;
300import java.util.concurrent.atomic.AtomicLong;
301
302/**
303 * Keep track of all those APKs everywhere.
304 * <p>
305 * Internally there are two important locks:
306 * <ul>
307 * <li>{@link #mPackages} is used to guard all in-memory parsed package details
308 * and other related state. It is a fine-grained lock that should only be held
309 * momentarily, as it's one of the most contended locks in the system.
310 * <li>{@link #mInstallLock} is used to guard all {@code installd} access, whose
311 * operations typically involve heavy lifting of application data on disk. Since
312 * {@code installd} is single-threaded, and it's operations can often be slow,
313 * this lock should never be acquired while already holding {@link #mPackages}.
314 * Conversely, it's safe to acquire {@link #mPackages} momentarily while already
315 * holding {@link #mInstallLock}.
316 * </ul>
317 * Many internal methods rely on the caller to hold the appropriate locks, and
318 * this contract is expressed through method name suffixes:
319 * <ul>
320 * <li>fooLI(): the caller must hold {@link #mInstallLock}
321 * <li>fooLIF(): the caller must hold {@link #mInstallLock} and the package
322 * being modified must be frozen
323 * <li>fooLPr(): the caller must hold {@link #mPackages} for reading
324 * <li>fooLPw(): the caller must hold {@link #mPackages} for writing
325 * </ul>
326 * <p>
327 * Because this class is very central to the platform's security; please run all
328 * CTS and unit tests whenever making modifications:
329 *
330 * <pre>
331 * $ runtest -c android.content.pm.PackageManagerTests frameworks-core
332 * $ cts-tradefed run commandAndExit cts -m AppSecurityTests
333 * </pre>
334 */
335public class PackageManagerService extends IPackageManager.Stub {
336    static final String TAG = "PackageManager";
337    static final boolean DEBUG_SETTINGS = false;
338    static final boolean DEBUG_PREFERRED = false;
339    static final boolean DEBUG_UPGRADE = false;
340    static final boolean DEBUG_DOMAIN_VERIFICATION = false;
341    private static final boolean DEBUG_BACKUP = false;
342    private static final boolean DEBUG_INSTALL = false;
343    private static final boolean DEBUG_REMOVE = false;
344    private static final boolean DEBUG_BROADCASTS = false;
345    private static final boolean DEBUG_SHOW_INFO = false;
346    private static final boolean DEBUG_PACKAGE_INFO = false;
347    private static final boolean DEBUG_INTENT_MATCHING = false;
348    private static final boolean DEBUG_PACKAGE_SCANNING = false;
349    private static final boolean DEBUG_VERIFY = false;
350    private static final boolean DEBUG_FILTERS = false;
351
352    // Debug output for dexopting. This is shared between PackageManagerService, OtaDexoptService
353    // and PackageDexOptimizer. All these classes have their own flag to allow switching a single
354    // user, but by default initialize to this.
355    static final boolean DEBUG_DEXOPT = false;
356
357    private static final boolean DEBUG_ABI_SELECTION = false;
358    private static final boolean DEBUG_EPHEMERAL = false;
359    private static final boolean DEBUG_TRIAGED_MISSING = false;
360    private static final boolean DEBUG_APP_DATA = false;
361
362    static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = false;
363
364    private static final boolean DISABLE_EPHEMERAL_APPS = true;
365
366    private static final int RADIO_UID = Process.PHONE_UID;
367    private static final int LOG_UID = Process.LOG_UID;
368    private static final int NFC_UID = Process.NFC_UID;
369    private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID;
370    private static final int SHELL_UID = Process.SHELL_UID;
371
372    // Cap the size of permission trees that 3rd party apps can define
373    private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768;     // characters of text
374
375    // Suffix used during package installation when copying/moving
376    // package apks to install directory.
377    private static final String INSTALL_PACKAGE_SUFFIX = "-";
378
379    static final int SCAN_NO_DEX = 1<<1;
380    static final int SCAN_FORCE_DEX = 1<<2;
381    static final int SCAN_UPDATE_SIGNATURE = 1<<3;
382    static final int SCAN_NEW_INSTALL = 1<<4;
383    static final int SCAN_NO_PATHS = 1<<5;
384    static final int SCAN_UPDATE_TIME = 1<<6;
385    static final int SCAN_DEFER_DEX = 1<<7;
386    static final int SCAN_BOOTING = 1<<8;
387    static final int SCAN_TRUSTED_OVERLAY = 1<<9;
388    static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<10;
389    static final int SCAN_REPLACING = 1<<11;
390    static final int SCAN_REQUIRE_KNOWN = 1<<12;
391    static final int SCAN_MOVE = 1<<13;
392    static final int SCAN_INITIAL = 1<<14;
393    static final int SCAN_CHECK_ONLY = 1<<15;
394    static final int SCAN_DONT_KILL_APP = 1<<17;
395    static final int SCAN_IGNORE_FROZEN = 1<<18;
396
397    static final int REMOVE_CHATTY = 1<<16;
398
399    private static final int[] EMPTY_INT_ARRAY = new int[0];
400
401    /**
402     * Timeout (in milliseconds) after which the watchdog should declare that
403     * our handler thread is wedged.  The usual default for such things is one
404     * minute but we sometimes do very lengthy I/O operations on this thread,
405     * such as installing multi-gigabyte applications, so ours needs to be longer.
406     */
407    private static final long WATCHDOG_TIMEOUT = 1000*60*10;     // ten minutes
408
409    /**
410     * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim
411     * be run on this device.  We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL
412     * settings entry if available, otherwise we use the hardcoded default.  If it's been
413     * more than this long since the last fstrim, we force one during the boot sequence.
414     *
415     * This backstops other fstrim scheduling:  if the device is alive at midnight+idle,
416     * one gets run at the next available charging+idle time.  This final mandatory
417     * no-fstrim check kicks in only of the other scheduling criteria is never met.
418     */
419    private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS;
420
421    /**
422     * Whether verification is enabled by default.
423     */
424    private static final boolean DEFAULT_VERIFY_ENABLE = true;
425
426    /**
427     * The default maximum time to wait for the verification agent to return in
428     * milliseconds.
429     */
430    private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000;
431
432    /**
433     * The default response for package verification timeout.
434     *
435     * This can be either PackageManager.VERIFICATION_ALLOW or
436     * PackageManager.VERIFICATION_REJECT.
437     */
438    private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW;
439
440    static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer";
441
442    static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
443            DEFAULT_CONTAINER_PACKAGE,
444            "com.android.defcontainer.DefaultContainerService");
445
446    private static final String KILL_APP_REASON_GIDS_CHANGED =
447            "permission grant or revoke changed gids";
448
449    private static final String KILL_APP_REASON_PERMISSIONS_REVOKED =
450            "permissions revoked";
451
452    private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive";
453
454    private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay";
455
456    /** Permission grant: not grant the permission. */
457    private static final int GRANT_DENIED = 1;
458
459    /** Permission grant: grant the permission as an install permission. */
460    private static final int GRANT_INSTALL = 2;
461
462    /** Permission grant: grant the permission as a runtime one. */
463    private static final int GRANT_RUNTIME = 3;
464
465    /** Permission grant: grant as runtime a permission that was granted as an install time one. */
466    private static final int GRANT_UPGRADE = 4;
467
468    /** Canonical intent used to identify what counts as a "web browser" app */
469    private static final Intent sBrowserIntent;
470    static {
471        sBrowserIntent = new Intent();
472        sBrowserIntent.setAction(Intent.ACTION_VIEW);
473        sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE);
474        sBrowserIntent.setData(Uri.parse("http:"));
475    }
476
477    /**
478     * The set of all protected actions [i.e. those actions for which a high priority
479     * intent filter is disallowed].
480     */
481    private static final Set<String> PROTECTED_ACTIONS = new ArraySet<>();
482    static {
483        PROTECTED_ACTIONS.add(Intent.ACTION_SEND);
484        PROTECTED_ACTIONS.add(Intent.ACTION_SENDTO);
485        PROTECTED_ACTIONS.add(Intent.ACTION_SEND_MULTIPLE);
486        PROTECTED_ACTIONS.add(Intent.ACTION_VIEW);
487    }
488
489    // Compilation reasons.
490    public static final int REASON_FIRST_BOOT = 0;
491    public static final int REASON_BOOT = 1;
492    public static final int REASON_INSTALL = 2;
493    public static final int REASON_BACKGROUND_DEXOPT = 3;
494    public static final int REASON_AB_OTA = 4;
495    public static final int REASON_NON_SYSTEM_LIBRARY = 5;
496    public static final int REASON_SHARED_APK = 6;
497    public static final int REASON_FORCED_DEXOPT = 7;
498
499    public static final int REASON_LAST = REASON_FORCED_DEXOPT;
500
501    final ServiceThread mHandlerThread;
502
503    final PackageHandler mHandler;
504
505    private final ProcessLoggingHandler mProcessLoggingHandler;
506
507    /**
508     * Messages for {@link #mHandler} that need to wait for system ready before
509     * being dispatched.
510     */
511    private ArrayList<Message> mPostSystemReadyMessages;
512
513    final int mSdkVersion = Build.VERSION.SDK_INT;
514
515    final Context mContext;
516    final boolean mFactoryTest;
517    final boolean mOnlyCore;
518    final DisplayMetrics mMetrics;
519    final int mDefParseFlags;
520    final String[] mSeparateProcesses;
521    final boolean mIsUpgrade;
522    final boolean mIsPreNUpgrade;
523
524    /** The location for ASEC container files on internal storage. */
525    final String mAsecInternalPath;
526
527    // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages
528    // LOCK HELD.  Can be called with mInstallLock held.
529    @GuardedBy("mInstallLock")
530    final Installer mInstaller;
531
532    /** Directory where installed third-party apps stored */
533    final File mAppInstallDir;
534    final File mEphemeralInstallDir;
535
536    /**
537     * Directory to which applications installed internally have their
538     * 32 bit native libraries copied.
539     */
540    private File mAppLib32InstallDir;
541
542    // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked
543    // apps.
544    final File mDrmAppPrivateInstallDir;
545
546    // ----------------------------------------------------------------
547
548    // Lock for state used when installing and doing other long running
549    // operations.  Methods that must be called with this lock held have
550    // the suffix "LI".
551    final Object mInstallLock = new Object();
552
553    // ----------------------------------------------------------------
554
555    // Keys are String (package name), values are Package.  This also serves
556    // as the lock for the global state.  Methods that must be called with
557    // this lock held have the prefix "LP".
558    @GuardedBy("mPackages")
559    final ArrayMap<String, PackageParser.Package> mPackages =
560            new ArrayMap<String, PackageParser.Package>();
561
562    final ArrayMap<String, Set<String>> mKnownCodebase =
563            new ArrayMap<String, Set<String>>();
564
565    // Tracks available target package names -> overlay package paths.
566    final ArrayMap<String, ArrayMap<String, PackageParser.Package>> mOverlays =
567        new ArrayMap<String, ArrayMap<String, PackageParser.Package>>();
568
569    /**
570     * Tracks new system packages [received in an OTA] that we expect to
571     * find updated user-installed versions. Keys are package name, values
572     * are package location.
573     */
574    final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>();
575    /**
576     * Tracks high priority intent filters for protected actions. During boot, certain
577     * filter actions are protected and should never be allowed to have a high priority
578     * intent filter for them. However, there is one, and only one exception -- the
579     * setup wizard. It must be able to define a high priority intent filter for these
580     * actions to ensure there are no escapes from the wizard. We need to delay processing
581     * of these during boot as we need to look at all of the system packages in order
582     * to know which component is the setup wizard.
583     */
584    private final List<PackageParser.ActivityIntentInfo> mProtectedFilters = new ArrayList<>();
585    /**
586     * Whether or not processing protected filters should be deferred.
587     */
588    private boolean mDeferProtectedFilters = true;
589
590    /**
591     * Tracks existing system packages prior to receiving an OTA. Keys are package name.
592     */
593    final private ArraySet<String> mExistingSystemPackages = new ArraySet<>();
594    /**
595     * Whether or not system app permissions should be promoted from install to runtime.
596     */
597    boolean mPromoteSystemApps;
598
599    @GuardedBy("mPackages")
600    final Settings mSettings;
601
602    /**
603     * Set of package names that are currently "frozen", which means active
604     * surgery is being done on the code/data for that package. The platform
605     * will refuse to launch frozen packages to avoid race conditions.
606     *
607     * @see PackageFreezer
608     */
609    @GuardedBy("mPackages")
610    final ArraySet<String> mFrozenPackages = new ArraySet<>();
611
612    boolean mRestoredSettings;
613
614    // System configuration read by SystemConfig.
615    final int[] mGlobalGids;
616    final SparseArray<ArraySet<String>> mSystemPermissions;
617    final ArrayMap<String, FeatureInfo> mAvailableFeatures;
618
619    // If mac_permissions.xml was found for seinfo labeling.
620    boolean mFoundPolicyFile;
621
622    private final EphemeralApplicationRegistry mEphemeralApplicationRegistry;
623
624    public static final class SharedLibraryEntry {
625        public final String path;
626        public final String apk;
627
628        SharedLibraryEntry(String _path, String _apk) {
629            path = _path;
630            apk = _apk;
631        }
632    }
633
634    // Currently known shared libraries.
635    final ArrayMap<String, SharedLibraryEntry> mSharedLibraries =
636            new ArrayMap<String, SharedLibraryEntry>();
637
638    // All available activities, for your resolving pleasure.
639    final ActivityIntentResolver mActivities =
640            new ActivityIntentResolver();
641
642    // All available receivers, for your resolving pleasure.
643    final ActivityIntentResolver mReceivers =
644            new ActivityIntentResolver();
645
646    // All available services, for your resolving pleasure.
647    final ServiceIntentResolver mServices = new ServiceIntentResolver();
648
649    // All available providers, for your resolving pleasure.
650    final ProviderIntentResolver mProviders = new ProviderIntentResolver();
651
652    // Mapping from provider base names (first directory in content URI codePath)
653    // to the provider information.
654    final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority =
655            new ArrayMap<String, PackageParser.Provider>();
656
657    // Mapping from instrumentation class names to info about them.
658    final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
659            new ArrayMap<ComponentName, PackageParser.Instrumentation>();
660
661    // Mapping from permission names to info about them.
662    final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups =
663            new ArrayMap<String, PackageParser.PermissionGroup>();
664
665    // Packages whose data we have transfered into another package, thus
666    // should no longer exist.
667    final ArraySet<String> mTransferedPackages = new ArraySet<String>();
668
669    // Broadcast actions that are only available to the system.
670    final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>();
671
672    /** List of packages waiting for verification. */
673    final SparseArray<PackageVerificationState> mPendingVerification
674            = new SparseArray<PackageVerificationState>();
675
676    /** Set of packages associated with each app op permission. */
677    final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>();
678
679    final PackageInstallerService mInstallerService;
680
681    private final PackageDexOptimizer mPackageDexOptimizer;
682
683    private AtomicInteger mNextMoveId = new AtomicInteger();
684    private final MoveCallbacks mMoveCallbacks;
685
686    private final OnPermissionChangeListeners mOnPermissionChangeListeners;
687
688    // Cache of users who need badging.
689    SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray();
690
691    /** Token for keys in mPendingVerification. */
692    private int mPendingVerificationToken = 0;
693
694    volatile boolean mSystemReady;
695    volatile boolean mSafeMode;
696    volatile boolean mHasSystemUidErrors;
697
698    ApplicationInfo mAndroidApplication;
699    final ActivityInfo mResolveActivity = new ActivityInfo();
700    final ResolveInfo mResolveInfo = new ResolveInfo();
701    ComponentName mResolveComponentName;
702    PackageParser.Package mPlatformPackage;
703    ComponentName mCustomResolverComponentName;
704
705    boolean mResolverReplaced = false;
706
707    private final @Nullable ComponentName mIntentFilterVerifierComponent;
708    private final @Nullable IntentFilterVerifier<ActivityIntentInfo> mIntentFilterVerifier;
709
710    private int mIntentFilterVerificationToken = 0;
711
712    /** Component that knows whether or not an ephemeral application exists */
713    final ComponentName mEphemeralResolverComponent;
714    /** The service connection to the ephemeral resolver */
715    final EphemeralResolverConnection mEphemeralResolverConnection;
716
717    /** Component used to install ephemeral applications */
718    final ComponentName mEphemeralInstallerComponent;
719    final ActivityInfo mEphemeralInstallerActivity = new ActivityInfo();
720    final ResolveInfo mEphemeralInstallerInfo = new ResolveInfo();
721
722    final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates
723            = new SparseArray<IntentFilterVerificationState>();
724
725    final DefaultPermissionGrantPolicy mDefaultPermissionPolicy =
726            new DefaultPermissionGrantPolicy(this);
727
728    // List of packages names to keep cached, even if they are uninstalled for all users
729    private List<String> mKeepUninstalledPackages;
730
731    private static class IFVerificationParams {
732        PackageParser.Package pkg;
733        boolean replacing;
734        int userId;
735        int verifierUid;
736
737        public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing,
738                int _userId, int _verifierUid) {
739            pkg = _pkg;
740            replacing = _replacing;
741            userId = _userId;
742            replacing = _replacing;
743            verifierUid = _verifierUid;
744        }
745    }
746
747    private interface IntentFilterVerifier<T extends IntentFilter> {
748        boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId,
749                                               T filter, String packageName);
750        void startVerifications(int userId);
751        void receiveVerificationResponse(int verificationId);
752    }
753
754    private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> {
755        private Context mContext;
756        private ComponentName mIntentFilterVerifierComponent;
757        private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>();
758
759        public IntentVerifierProxy(Context context, ComponentName verifierComponent) {
760            mContext = context;
761            mIntentFilterVerifierComponent = verifierComponent;
762        }
763
764        private String getDefaultScheme() {
765            return IntentFilter.SCHEME_HTTPS;
766        }
767
768        @Override
769        public void startVerifications(int userId) {
770            // Launch verifications requests
771            int count = mCurrentIntentFilterVerifications.size();
772            for (int n=0; n<count; n++) {
773                int verificationId = mCurrentIntentFilterVerifications.get(n);
774                final IntentFilterVerificationState ivs =
775                        mIntentFilterVerificationStates.get(verificationId);
776
777                String packageName = ivs.getPackageName();
778
779                ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
780                final int filterCount = filters.size();
781                ArraySet<String> domainsSet = new ArraySet<>();
782                for (int m=0; m<filterCount; m++) {
783                    PackageParser.ActivityIntentInfo filter = filters.get(m);
784                    domainsSet.addAll(filter.getHostsList());
785                }
786                ArrayList<String> domainsList = new ArrayList<>(domainsSet);
787                synchronized (mPackages) {
788                    if (mSettings.createIntentFilterVerificationIfNeededLPw(
789                            packageName, domainsList) != null) {
790                        scheduleWriteSettingsLocked();
791                    }
792                }
793                sendVerificationRequest(userId, verificationId, ivs);
794            }
795            mCurrentIntentFilterVerifications.clear();
796        }
797
798        private void sendVerificationRequest(int userId, int verificationId,
799                IntentFilterVerificationState ivs) {
800
801            Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
802            verificationIntent.putExtra(
803                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID,
804                    verificationId);
805            verificationIntent.putExtra(
806                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME,
807                    getDefaultScheme());
808            verificationIntent.putExtra(
809                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS,
810                    ivs.getHostsString());
811            verificationIntent.putExtra(
812                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME,
813                    ivs.getPackageName());
814            verificationIntent.setComponent(mIntentFilterVerifierComponent);
815            verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
816
817            UserHandle user = new UserHandle(userId);
818            mContext.sendBroadcastAsUser(verificationIntent, user);
819            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
820                    "Sending IntentFilter verification broadcast");
821        }
822
823        public void receiveVerificationResponse(int verificationId) {
824            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
825
826            final boolean verified = ivs.isVerified();
827
828            ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
829            final int count = filters.size();
830            if (DEBUG_DOMAIN_VERIFICATION) {
831                Slog.i(TAG, "Received verification response " + verificationId
832                        + " for " + count + " filters, verified=" + verified);
833            }
834            for (int n=0; n<count; n++) {
835                PackageParser.ActivityIntentInfo filter = filters.get(n);
836                filter.setVerified(verified);
837
838                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString()
839                        + " verified with result:" + verified + " and hosts:"
840                        + ivs.getHostsString());
841            }
842
843            mIntentFilterVerificationStates.remove(verificationId);
844
845            final String packageName = ivs.getPackageName();
846            IntentFilterVerificationInfo ivi = null;
847
848            synchronized (mPackages) {
849                ivi = mSettings.getIntentFilterVerificationLPr(packageName);
850            }
851            if (ivi == null) {
852                Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:"
853                        + verificationId + " packageName:" + packageName);
854                return;
855            }
856            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
857                    "Updating IntentFilterVerificationInfo for package " + packageName
858                            +" verificationId:" + verificationId);
859
860            synchronized (mPackages) {
861                if (verified) {
862                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS);
863                } else {
864                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK);
865                }
866                scheduleWriteSettingsLocked();
867
868                final int userId = ivs.getUserId();
869                if (userId != UserHandle.USER_ALL) {
870                    final int userStatus =
871                            mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
872
873                    int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
874                    boolean needUpdate = false;
875
876                    // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have
877                    // already been set by the User thru the Disambiguation dialog
878                    switch (userStatus) {
879                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
880                            if (verified) {
881                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
882                            } else {
883                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
884                            }
885                            needUpdate = true;
886                            break;
887
888                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
889                            if (verified) {
890                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
891                                needUpdate = true;
892                            }
893                            break;
894
895                        default:
896                            // Nothing to do
897                    }
898
899                    if (needUpdate) {
900                        mSettings.updateIntentFilterVerificationStatusLPw(
901                                packageName, updatedStatus, userId);
902                        scheduleWritePackageRestrictionsLocked(userId);
903                    }
904                }
905            }
906        }
907
908        @Override
909        public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId,
910                    ActivityIntentInfo filter, String packageName) {
911            if (!hasValidDomains(filter)) {
912                return false;
913            }
914            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
915            if (ivs == null) {
916                ivs = createDomainVerificationState(verifierUid, userId, verificationId,
917                        packageName);
918            }
919            if (DEBUG_DOMAIN_VERIFICATION) {
920                Slog.d(TAG, "Adding verification filter for " + packageName + ": " + filter);
921            }
922            ivs.addFilter(filter);
923            return true;
924        }
925
926        private IntentFilterVerificationState createDomainVerificationState(int verifierUid,
927                int userId, int verificationId, String packageName) {
928            IntentFilterVerificationState ivs = new IntentFilterVerificationState(
929                    verifierUid, userId, packageName);
930            ivs.setPendingState();
931            synchronized (mPackages) {
932                mIntentFilterVerificationStates.append(verificationId, ivs);
933                mCurrentIntentFilterVerifications.add(verificationId);
934            }
935            return ivs;
936        }
937    }
938
939    private static boolean hasValidDomains(ActivityIntentInfo filter) {
940        return filter.hasCategory(Intent.CATEGORY_BROWSABLE)
941                && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
942                        filter.hasDataScheme(IntentFilter.SCHEME_HTTPS));
943    }
944
945    // Set of pending broadcasts for aggregating enable/disable of components.
946    static class PendingPackageBroadcasts {
947        // for each user id, a map of <package name -> components within that package>
948        final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap;
949
950        public PendingPackageBroadcasts() {
951            mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2);
952        }
953
954        public ArrayList<String> get(int userId, String packageName) {
955            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
956            return packages.get(packageName);
957        }
958
959        public void put(int userId, String packageName, ArrayList<String> components) {
960            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
961            packages.put(packageName, components);
962        }
963
964        public void remove(int userId, String packageName) {
965            ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId);
966            if (packages != null) {
967                packages.remove(packageName);
968            }
969        }
970
971        public void remove(int userId) {
972            mUidMap.remove(userId);
973        }
974
975        public int userIdCount() {
976            return mUidMap.size();
977        }
978
979        public int userIdAt(int n) {
980            return mUidMap.keyAt(n);
981        }
982
983        public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) {
984            return mUidMap.get(userId);
985        }
986
987        public int size() {
988            // total number of pending broadcast entries across all userIds
989            int num = 0;
990            for (int i = 0; i< mUidMap.size(); i++) {
991                num += mUidMap.valueAt(i).size();
992            }
993            return num;
994        }
995
996        public void clear() {
997            mUidMap.clear();
998        }
999
1000        private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) {
1001            ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId);
1002            if (map == null) {
1003                map = new ArrayMap<String, ArrayList<String>>();
1004                mUidMap.put(userId, map);
1005            }
1006            return map;
1007        }
1008    }
1009    final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts();
1010
1011    // Service Connection to remote media container service to copy
1012    // package uri's from external media onto secure containers
1013    // or internal storage.
1014    private IMediaContainerService mContainerService = null;
1015
1016    static final int SEND_PENDING_BROADCAST = 1;
1017    static final int MCS_BOUND = 3;
1018    static final int END_COPY = 4;
1019    static final int INIT_COPY = 5;
1020    static final int MCS_UNBIND = 6;
1021    static final int START_CLEANING_PACKAGE = 7;
1022    static final int FIND_INSTALL_LOC = 8;
1023    static final int POST_INSTALL = 9;
1024    static final int MCS_RECONNECT = 10;
1025    static final int MCS_GIVE_UP = 11;
1026    static final int UPDATED_MEDIA_STATUS = 12;
1027    static final int WRITE_SETTINGS = 13;
1028    static final int WRITE_PACKAGE_RESTRICTIONS = 14;
1029    static final int PACKAGE_VERIFIED = 15;
1030    static final int CHECK_PENDING_VERIFICATION = 16;
1031    static final int START_INTENT_FILTER_VERIFICATIONS = 17;
1032    static final int INTENT_FILTER_VERIFIED = 18;
1033
1034    static final int WRITE_SETTINGS_DELAY = 10*1000;  // 10 seconds
1035
1036    // Delay time in millisecs
1037    static final int BROADCAST_DELAY = 10 * 1000;
1038
1039    static UserManagerService sUserManager;
1040
1041    // Stores a list of users whose package restrictions file needs to be updated
1042    private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>();
1043
1044    final private DefaultContainerConnection mDefContainerConn =
1045            new DefaultContainerConnection();
1046    class DefaultContainerConnection implements ServiceConnection {
1047        public void onServiceConnected(ComponentName name, IBinder service) {
1048            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
1049            IMediaContainerService imcs =
1050                IMediaContainerService.Stub.asInterface(service);
1051            mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
1052        }
1053
1054        public void onServiceDisconnected(ComponentName name) {
1055            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
1056        }
1057    }
1058
1059    // Recordkeeping of restore-after-install operations that are currently in flight
1060    // between the Package Manager and the Backup Manager
1061    static class PostInstallData {
1062        public InstallArgs args;
1063        public PackageInstalledInfo res;
1064
1065        PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
1066            args = _a;
1067            res = _r;
1068        }
1069    }
1070
1071    final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
1072    int mNextInstallToken = 1;  // nonzero; will be wrapped back to 1 when ++ overflows
1073
1074    // XML tags for backup/restore of various bits of state
1075    private static final String TAG_PREFERRED_BACKUP = "pa";
1076    private static final String TAG_DEFAULT_APPS = "da";
1077    private static final String TAG_INTENT_FILTER_VERIFICATION = "iv";
1078
1079    private static final String TAG_PERMISSION_BACKUP = "perm-grant-backup";
1080    private static final String TAG_ALL_GRANTS = "rt-grants";
1081    private static final String TAG_GRANT = "grant";
1082    private static final String ATTR_PACKAGE_NAME = "pkg";
1083
1084    private static final String TAG_PERMISSION = "perm";
1085    private static final String ATTR_PERMISSION_NAME = "name";
1086    private static final String ATTR_IS_GRANTED = "g";
1087    private static final String ATTR_USER_SET = "set";
1088    private static final String ATTR_USER_FIXED = "fixed";
1089    private static final String ATTR_REVOKE_ON_UPGRADE = "rou";
1090
1091    // System/policy permission grants are not backed up
1092    private static final int SYSTEM_RUNTIME_GRANT_MASK =
1093            FLAG_PERMISSION_POLICY_FIXED
1094            | FLAG_PERMISSION_SYSTEM_FIXED
1095            | FLAG_PERMISSION_GRANTED_BY_DEFAULT;
1096
1097    // And we back up these user-adjusted states
1098    private static final int USER_RUNTIME_GRANT_MASK =
1099            FLAG_PERMISSION_USER_SET
1100            | FLAG_PERMISSION_USER_FIXED
1101            | FLAG_PERMISSION_REVOKE_ON_UPGRADE;
1102
1103    final @Nullable String mRequiredVerifierPackage;
1104    final @NonNull String mRequiredInstallerPackage;
1105    final @Nullable String mSetupWizardPackage;
1106    final @NonNull String mServicesSystemSharedLibraryPackageName;
1107
1108    private final PackageUsage mPackageUsage = new PackageUsage();
1109
1110    private class PackageUsage {
1111        private static final int WRITE_INTERVAL
1112            = (DEBUG_DEXOPT) ? 0 : 30*60*1000; // 30m in ms
1113
1114        private final Object mFileLock = new Object();
1115        private final AtomicLong mLastWritten = new AtomicLong(0);
1116        private final AtomicBoolean mBackgroundWriteRunning = new AtomicBoolean(false);
1117
1118        private boolean mIsHistoricalPackageUsageAvailable = true;
1119
1120        boolean isHistoricalPackageUsageAvailable() {
1121            return mIsHistoricalPackageUsageAvailable;
1122        }
1123
1124        void write(boolean force) {
1125            if (force) {
1126                writeInternal();
1127                return;
1128            }
1129            if (SystemClock.elapsedRealtime() - mLastWritten.get() < WRITE_INTERVAL
1130                && !DEBUG_DEXOPT) {
1131                return;
1132            }
1133            if (mBackgroundWriteRunning.compareAndSet(false, true)) {
1134                new Thread("PackageUsage_DiskWriter") {
1135                    @Override
1136                    public void run() {
1137                        try {
1138                            writeInternal();
1139                        } finally {
1140                            mBackgroundWriteRunning.set(false);
1141                        }
1142                    }
1143                }.start();
1144            }
1145        }
1146
1147        private void writeInternal() {
1148            synchronized (mPackages) {
1149                synchronized (mFileLock) {
1150                    AtomicFile file = getFile();
1151                    FileOutputStream f = null;
1152                    try {
1153                        f = file.startWrite();
1154                        BufferedOutputStream out = new BufferedOutputStream(f);
1155                        FileUtils.setPermissions(file.getBaseFile().getPath(), 0640, SYSTEM_UID, PACKAGE_INFO_GID);
1156                        StringBuilder sb = new StringBuilder();
1157                        for (PackageParser.Package pkg : mPackages.values()) {
1158                            if (pkg.mLastPackageUsageTimeInMills == 0) {
1159                                continue;
1160                            }
1161                            sb.setLength(0);
1162                            sb.append(pkg.packageName);
1163                            sb.append(' ');
1164                            sb.append((long)pkg.mLastPackageUsageTimeInMills);
1165                            sb.append('\n');
1166                            out.write(sb.toString().getBytes(StandardCharsets.US_ASCII));
1167                        }
1168                        out.flush();
1169                        file.finishWrite(f);
1170                    } catch (IOException e) {
1171                        if (f != null) {
1172                            file.failWrite(f);
1173                        }
1174                        Log.e(TAG, "Failed to write package usage times", e);
1175                    }
1176                }
1177            }
1178            mLastWritten.set(SystemClock.elapsedRealtime());
1179        }
1180
1181        void readLP() {
1182            synchronized (mFileLock) {
1183                AtomicFile file = getFile();
1184                BufferedInputStream in = null;
1185                try {
1186                    in = new BufferedInputStream(file.openRead());
1187                    StringBuffer sb = new StringBuffer();
1188                    while (true) {
1189                        String packageName = readToken(in, sb, ' ');
1190                        if (packageName == null) {
1191                            break;
1192                        }
1193                        String timeInMillisString = readToken(in, sb, '\n');
1194                        if (timeInMillisString == null) {
1195                            throw new IOException("Failed to find last usage time for package "
1196                                                  + packageName);
1197                        }
1198                        PackageParser.Package pkg = mPackages.get(packageName);
1199                        if (pkg == null) {
1200                            continue;
1201                        }
1202                        long timeInMillis;
1203                        try {
1204                            timeInMillis = Long.parseLong(timeInMillisString);
1205                        } catch (NumberFormatException e) {
1206                            throw new IOException("Failed to parse " + timeInMillisString
1207                                                  + " as a long.", e);
1208                        }
1209                        pkg.mLastPackageUsageTimeInMills = timeInMillis;
1210                    }
1211                } catch (FileNotFoundException expected) {
1212                    mIsHistoricalPackageUsageAvailable = false;
1213                } catch (IOException e) {
1214                    Log.w(TAG, "Failed to read package usage times", e);
1215                } finally {
1216                    IoUtils.closeQuietly(in);
1217                }
1218            }
1219            mLastWritten.set(SystemClock.elapsedRealtime());
1220        }
1221
1222        private String readToken(InputStream in, StringBuffer sb, char endOfToken)
1223                throws IOException {
1224            sb.setLength(0);
1225            while (true) {
1226                int ch = in.read();
1227                if (ch == -1) {
1228                    if (sb.length() == 0) {
1229                        return null;
1230                    }
1231                    throw new IOException("Unexpected EOF");
1232                }
1233                if (ch == endOfToken) {
1234                    return sb.toString();
1235                }
1236                sb.append((char)ch);
1237            }
1238        }
1239
1240        private AtomicFile getFile() {
1241            File dataDir = Environment.getDataDirectory();
1242            File systemDir = new File(dataDir, "system");
1243            File fname = new File(systemDir, "package-usage.list");
1244            return new AtomicFile(fname);
1245        }
1246    }
1247
1248    class PackageHandler extends Handler {
1249        private boolean mBound = false;
1250        final ArrayList<HandlerParams> mPendingInstalls =
1251            new ArrayList<HandlerParams>();
1252
1253        private boolean connectToService() {
1254            if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
1255                    " DefaultContainerService");
1256            Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
1257            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1258            if (mContext.bindServiceAsUser(service, mDefContainerConn,
1259                    Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
1260                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1261                mBound = true;
1262                return true;
1263            }
1264            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1265            return false;
1266        }
1267
1268        private void disconnectService() {
1269            mContainerService = null;
1270            mBound = false;
1271            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1272            mContext.unbindService(mDefContainerConn);
1273            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1274        }
1275
1276        PackageHandler(Looper looper) {
1277            super(looper);
1278        }
1279
1280        public void handleMessage(Message msg) {
1281            try {
1282                doHandleMessage(msg);
1283            } finally {
1284                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1285            }
1286        }
1287
1288        void doHandleMessage(Message msg) {
1289            switch (msg.what) {
1290                case INIT_COPY: {
1291                    HandlerParams params = (HandlerParams) msg.obj;
1292                    int idx = mPendingInstalls.size();
1293                    if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params);
1294                    // If a bind was already initiated we dont really
1295                    // need to do anything. The pending install
1296                    // will be processed later on.
1297                    if (!mBound) {
1298                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1299                                System.identityHashCode(mHandler));
1300                        // If this is the only one pending we might
1301                        // have to bind to the service again.
1302                        if (!connectToService()) {
1303                            Slog.e(TAG, "Failed to bind to media container service");
1304                            params.serviceError();
1305                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1306                                    System.identityHashCode(mHandler));
1307                            if (params.traceMethod != null) {
1308                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod,
1309                                        params.traceCookie);
1310                            }
1311                            return;
1312                        } else {
1313                            // Once we bind to the service, the first
1314                            // pending request will be processed.
1315                            mPendingInstalls.add(idx, params);
1316                        }
1317                    } else {
1318                        mPendingInstalls.add(idx, params);
1319                        // Already bound to the service. Just make
1320                        // sure we trigger off processing the first request.
1321                        if (idx == 0) {
1322                            mHandler.sendEmptyMessage(MCS_BOUND);
1323                        }
1324                    }
1325                    break;
1326                }
1327                case MCS_BOUND: {
1328                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound");
1329                    if (msg.obj != null) {
1330                        mContainerService = (IMediaContainerService) msg.obj;
1331                        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1332                                System.identityHashCode(mHandler));
1333                    }
1334                    if (mContainerService == null) {
1335                        if (!mBound) {
1336                            // Something seriously wrong since we are not bound and we are not
1337                            // waiting for connection. Bail out.
1338                            Slog.e(TAG, "Cannot bind to media container service");
1339                            for (HandlerParams params : mPendingInstalls) {
1340                                // Indicate service bind error
1341                                params.serviceError();
1342                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1343                                        System.identityHashCode(params));
1344                                if (params.traceMethod != null) {
1345                                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER,
1346                                            params.traceMethod, params.traceCookie);
1347                                }
1348                                return;
1349                            }
1350                            mPendingInstalls.clear();
1351                        } else {
1352                            Slog.w(TAG, "Waiting to connect to media container service");
1353                        }
1354                    } else if (mPendingInstalls.size() > 0) {
1355                        HandlerParams params = mPendingInstalls.get(0);
1356                        if (params != null) {
1357                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1358                                    System.identityHashCode(params));
1359                            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy");
1360                            if (params.startCopy()) {
1361                                // We are done...  look for more work or to
1362                                // go idle.
1363                                if (DEBUG_SD_INSTALL) Log.i(TAG,
1364                                        "Checking for more work or unbind...");
1365                                // Delete pending install
1366                                if (mPendingInstalls.size() > 0) {
1367                                    mPendingInstalls.remove(0);
1368                                }
1369                                if (mPendingInstalls.size() == 0) {
1370                                    if (mBound) {
1371                                        if (DEBUG_SD_INSTALL) Log.i(TAG,
1372                                                "Posting delayed MCS_UNBIND");
1373                                        removeMessages(MCS_UNBIND);
1374                                        Message ubmsg = obtainMessage(MCS_UNBIND);
1375                                        // Unbind after a little delay, to avoid
1376                                        // continual thrashing.
1377                                        sendMessageDelayed(ubmsg, 10000);
1378                                    }
1379                                } else {
1380                                    // There are more pending requests in queue.
1381                                    // Just post MCS_BOUND message to trigger processing
1382                                    // of next pending install.
1383                                    if (DEBUG_SD_INSTALL) Log.i(TAG,
1384                                            "Posting MCS_BOUND for next work");
1385                                    mHandler.sendEmptyMessage(MCS_BOUND);
1386                                }
1387                            }
1388                            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
1389                        }
1390                    } else {
1391                        // Should never happen ideally.
1392                        Slog.w(TAG, "Empty queue");
1393                    }
1394                    break;
1395                }
1396                case MCS_RECONNECT: {
1397                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect");
1398                    if (mPendingInstalls.size() > 0) {
1399                        if (mBound) {
1400                            disconnectService();
1401                        }
1402                        if (!connectToService()) {
1403                            Slog.e(TAG, "Failed to bind to media container service");
1404                            for (HandlerParams params : mPendingInstalls) {
1405                                // Indicate service bind error
1406                                params.serviceError();
1407                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1408                                        System.identityHashCode(params));
1409                            }
1410                            mPendingInstalls.clear();
1411                        }
1412                    }
1413                    break;
1414                }
1415                case MCS_UNBIND: {
1416                    // If there is no actual work left, then time to unbind.
1417                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind");
1418
1419                    if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) {
1420                        if (mBound) {
1421                            if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()");
1422
1423                            disconnectService();
1424                        }
1425                    } else if (mPendingInstalls.size() > 0) {
1426                        // There are more pending requests in queue.
1427                        // Just post MCS_BOUND message to trigger processing
1428                        // of next pending install.
1429                        mHandler.sendEmptyMessage(MCS_BOUND);
1430                    }
1431
1432                    break;
1433                }
1434                case MCS_GIVE_UP: {
1435                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries");
1436                    HandlerParams params = mPendingInstalls.remove(0);
1437                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1438                            System.identityHashCode(params));
1439                    break;
1440                }
1441                case SEND_PENDING_BROADCAST: {
1442                    String packages[];
1443                    ArrayList<String> components[];
1444                    int size = 0;
1445                    int uids[];
1446                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1447                    synchronized (mPackages) {
1448                        if (mPendingBroadcasts == null) {
1449                            return;
1450                        }
1451                        size = mPendingBroadcasts.size();
1452                        if (size <= 0) {
1453                            // Nothing to be done. Just return
1454                            return;
1455                        }
1456                        packages = new String[size];
1457                        components = new ArrayList[size];
1458                        uids = new int[size];
1459                        int i = 0;  // filling out the above arrays
1460
1461                        for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) {
1462                            int packageUserId = mPendingBroadcasts.userIdAt(n);
1463                            Iterator<Map.Entry<String, ArrayList<String>>> it
1464                                    = mPendingBroadcasts.packagesForUserId(packageUserId)
1465                                            .entrySet().iterator();
1466                            while (it.hasNext() && i < size) {
1467                                Map.Entry<String, ArrayList<String>> ent = it.next();
1468                                packages[i] = ent.getKey();
1469                                components[i] = ent.getValue();
1470                                PackageSetting ps = mSettings.mPackages.get(ent.getKey());
1471                                uids[i] = (ps != null)
1472                                        ? UserHandle.getUid(packageUserId, ps.appId)
1473                                        : -1;
1474                                i++;
1475                            }
1476                        }
1477                        size = i;
1478                        mPendingBroadcasts.clear();
1479                    }
1480                    // Send broadcasts
1481                    for (int i = 0; i < size; i++) {
1482                        sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]);
1483                    }
1484                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1485                    break;
1486                }
1487                case START_CLEANING_PACKAGE: {
1488                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1489                    final String packageName = (String)msg.obj;
1490                    final int userId = msg.arg1;
1491                    final boolean andCode = msg.arg2 != 0;
1492                    synchronized (mPackages) {
1493                        if (userId == UserHandle.USER_ALL) {
1494                            int[] users = sUserManager.getUserIds();
1495                            for (int user : users) {
1496                                mSettings.addPackageToCleanLPw(
1497                                        new PackageCleanItem(user, packageName, andCode));
1498                            }
1499                        } else {
1500                            mSettings.addPackageToCleanLPw(
1501                                    new PackageCleanItem(userId, packageName, andCode));
1502                        }
1503                    }
1504                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1505                    startCleaningPackages();
1506                } break;
1507                case POST_INSTALL: {
1508                    if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
1509
1510                    PostInstallData data = mRunningInstalls.get(msg.arg1);
1511                    mRunningInstalls.delete(msg.arg1);
1512
1513                    if (data != null) {
1514                        InstallArgs args = data.args;
1515                        PackageInstalledInfo parentRes = data.res;
1516
1517                        final boolean grantPermissions = (args.installFlags
1518                                & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0;
1519                        final boolean killApp = (args.installFlags
1520                                & PackageManager.INSTALL_DONT_KILL_APP) == 0;
1521                        final String[] grantedPermissions = args.installGrantPermissions;
1522
1523                        // Handle the parent package
1524                        handlePackagePostInstall(parentRes, grantPermissions, killApp,
1525                                grantedPermissions, args.observer);
1526
1527                        // Handle the child packages
1528                        final int childCount = (parentRes.addedChildPackages != null)
1529                                ? parentRes.addedChildPackages.size() : 0;
1530                        for (int i = 0; i < childCount; i++) {
1531                            PackageInstalledInfo childRes = parentRes.addedChildPackages.valueAt(i);
1532                            handlePackagePostInstall(childRes, grantPermissions, killApp,
1533                                    grantedPermissions, args.observer);
1534                        }
1535
1536                        // Log tracing if needed
1537                        if (args.traceMethod != null) {
1538                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod,
1539                                    args.traceCookie);
1540                        }
1541                    } else {
1542                        Slog.e(TAG, "Bogus post-install token " + msg.arg1);
1543                    }
1544
1545                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1);
1546                } break;
1547                case UPDATED_MEDIA_STATUS: {
1548                    if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS");
1549                    boolean reportStatus = msg.arg1 == 1;
1550                    boolean doGc = msg.arg2 == 1;
1551                    if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc);
1552                    if (doGc) {
1553                        // Force a gc to clear up stale containers.
1554                        Runtime.getRuntime().gc();
1555                    }
1556                    if (msg.obj != null) {
1557                        @SuppressWarnings("unchecked")
1558                        Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj;
1559                        if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers");
1560                        // Unload containers
1561                        unloadAllContainers(args);
1562                    }
1563                    if (reportStatus) {
1564                        try {
1565                            if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back");
1566                            PackageHelper.getMountService().finishMediaUpdate();
1567                        } catch (RemoteException e) {
1568                            Log.e(TAG, "MountService not running?");
1569                        }
1570                    }
1571                } break;
1572                case WRITE_SETTINGS: {
1573                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1574                    synchronized (mPackages) {
1575                        removeMessages(WRITE_SETTINGS);
1576                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1577                        mSettings.writeLPr();
1578                        mDirtyUsers.clear();
1579                    }
1580                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1581                } break;
1582                case WRITE_PACKAGE_RESTRICTIONS: {
1583                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1584                    synchronized (mPackages) {
1585                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1586                        for (int userId : mDirtyUsers) {
1587                            mSettings.writePackageRestrictionsLPr(userId);
1588                        }
1589                        mDirtyUsers.clear();
1590                    }
1591                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1592                } break;
1593                case CHECK_PENDING_VERIFICATION: {
1594                    final int verificationId = msg.arg1;
1595                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1596
1597                    if ((state != null) && !state.timeoutExtended()) {
1598                        final InstallArgs args = state.getInstallArgs();
1599                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1600
1601                        Slog.i(TAG, "Verification timed out for " + originUri);
1602                        mPendingVerification.remove(verificationId);
1603
1604                        int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1605
1606                        if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) {
1607                            Slog.i(TAG, "Continuing with installation of " + originUri);
1608                            state.setVerifierResponse(Binder.getCallingUid(),
1609                                    PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT);
1610                            broadcastPackageVerified(verificationId, originUri,
1611                                    PackageManager.VERIFICATION_ALLOW,
1612                                    state.getInstallArgs().getUser());
1613                            try {
1614                                ret = args.copyApk(mContainerService, true);
1615                            } catch (RemoteException e) {
1616                                Slog.e(TAG, "Could not contact the ContainerService");
1617                            }
1618                        } else {
1619                            broadcastPackageVerified(verificationId, originUri,
1620                                    PackageManager.VERIFICATION_REJECT,
1621                                    state.getInstallArgs().getUser());
1622                        }
1623
1624                        Trace.asyncTraceEnd(
1625                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1626
1627                        processPendingInstall(args, ret);
1628                        mHandler.sendEmptyMessage(MCS_UNBIND);
1629                    }
1630                    break;
1631                }
1632                case PACKAGE_VERIFIED: {
1633                    final int verificationId = msg.arg1;
1634
1635                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1636                    if (state == null) {
1637                        Slog.w(TAG, "Invalid verification token " + verificationId + " received");
1638                        break;
1639                    }
1640
1641                    final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj;
1642
1643                    state.setVerifierResponse(response.callerUid, response.code);
1644
1645                    if (state.isVerificationComplete()) {
1646                        mPendingVerification.remove(verificationId);
1647
1648                        final InstallArgs args = state.getInstallArgs();
1649                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1650
1651                        int ret;
1652                        if (state.isInstallAllowed()) {
1653                            ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
1654                            broadcastPackageVerified(verificationId, originUri,
1655                                    response.code, state.getInstallArgs().getUser());
1656                            try {
1657                                ret = args.copyApk(mContainerService, true);
1658                            } catch (RemoteException e) {
1659                                Slog.e(TAG, "Could not contact the ContainerService");
1660                            }
1661                        } else {
1662                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1663                        }
1664
1665                        Trace.asyncTraceEnd(
1666                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1667
1668                        processPendingInstall(args, ret);
1669                        mHandler.sendEmptyMessage(MCS_UNBIND);
1670                    }
1671
1672                    break;
1673                }
1674                case START_INTENT_FILTER_VERIFICATIONS: {
1675                    IFVerificationParams params = (IFVerificationParams) msg.obj;
1676                    verifyIntentFiltersIfNeeded(params.userId, params.verifierUid,
1677                            params.replacing, params.pkg);
1678                    break;
1679                }
1680                case INTENT_FILTER_VERIFIED: {
1681                    final int verificationId = msg.arg1;
1682
1683                    final IntentFilterVerificationState state = mIntentFilterVerificationStates.get(
1684                            verificationId);
1685                    if (state == null) {
1686                        Slog.w(TAG, "Invalid IntentFilter verification token "
1687                                + verificationId + " received");
1688                        break;
1689                    }
1690
1691                    final int userId = state.getUserId();
1692
1693                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1694                            "Processing IntentFilter verification with token:"
1695                            + verificationId + " and userId:" + userId);
1696
1697                    final IntentFilterVerificationResponse response =
1698                            (IntentFilterVerificationResponse) msg.obj;
1699
1700                    state.setVerifierResponse(response.callerUid, response.code);
1701
1702                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1703                            "IntentFilter verification with token:" + verificationId
1704                            + " and userId:" + userId
1705                            + " is settings verifier response with response code:"
1706                            + response.code);
1707
1708                    if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) {
1709                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: "
1710                                + response.getFailedDomainsString());
1711                    }
1712
1713                    if (state.isVerificationComplete()) {
1714                        mIntentFilterVerifier.receiveVerificationResponse(verificationId);
1715                    } else {
1716                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1717                                "IntentFilter verification with token:" + verificationId
1718                                + " was not said to be complete");
1719                    }
1720
1721                    break;
1722                }
1723            }
1724        }
1725    }
1726
1727    private void handlePackagePostInstall(PackageInstalledInfo res, boolean grantPermissions,
1728            boolean killApp, String[] grantedPermissions,
1729            IPackageInstallObserver2 installObserver) {
1730        if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
1731            // Send the removed broadcasts
1732            if (res.removedInfo != null) {
1733                res.removedInfo.sendPackageRemovedBroadcasts(killApp);
1734            }
1735
1736            // Now that we successfully installed the package, grant runtime
1737            // permissions if requested before broadcasting the install.
1738            if (grantPermissions && res.pkg.applicationInfo.targetSdkVersion
1739                    >= Build.VERSION_CODES.M) {
1740                grantRequestedRuntimePermissions(res.pkg, res.newUsers, grantedPermissions);
1741            }
1742
1743            final boolean update = res.removedInfo != null
1744                    && res.removedInfo.removedPackage != null;
1745
1746            // If this is the first time we have child packages for a disabled privileged
1747            // app that had no children, we grant requested runtime permissions to the new
1748            // children if the parent on the system image had them already granted.
1749            if (res.pkg.parentPackage != null) {
1750                synchronized (mPackages) {
1751                    grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(res.pkg);
1752                }
1753            }
1754
1755            synchronized (mPackages) {
1756                mEphemeralApplicationRegistry.onPackageInstalledLPw(res.pkg);
1757            }
1758
1759            final String packageName = res.pkg.applicationInfo.packageName;
1760            Bundle extras = new Bundle(1);
1761            extras.putInt(Intent.EXTRA_UID, res.uid);
1762
1763            // Determine the set of users who are adding this package for
1764            // the first time vs. those who are seeing an update.
1765            int[] firstUsers = EMPTY_INT_ARRAY;
1766            int[] updateUsers = EMPTY_INT_ARRAY;
1767            if (res.origUsers == null || res.origUsers.length == 0) {
1768                firstUsers = res.newUsers;
1769            } else {
1770                for (int newUser : res.newUsers) {
1771                    boolean isNew = true;
1772                    for (int origUser : res.origUsers) {
1773                        if (origUser == newUser) {
1774                            isNew = false;
1775                            break;
1776                        }
1777                    }
1778                    if (isNew) {
1779                        firstUsers = ArrayUtils.appendInt(firstUsers, newUser);
1780                    } else {
1781                        updateUsers = ArrayUtils.appendInt(updateUsers, newUser);
1782                    }
1783                }
1784            }
1785
1786            // Send installed broadcasts if the install/update is not ephemeral
1787            if (!isEphemeral(res.pkg)) {
1788                mProcessLoggingHandler.invalidateProcessLoggingBaseApkHash(res.pkg.baseCodePath);
1789
1790                // Send added for users that see the package for the first time
1791                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
1792                        extras, 0 /*flags*/, null /*targetPackage*/,
1793                        null /*finishedReceiver*/, firstUsers);
1794
1795                // Send added for users that don't see the package for the first time
1796                if (update) {
1797                    extras.putBoolean(Intent.EXTRA_REPLACING, true);
1798                }
1799                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
1800                        extras, 0 /*flags*/, null /*targetPackage*/,
1801                        null /*finishedReceiver*/, updateUsers);
1802
1803                // Send replaced for users that don't see the package for the first time
1804                if (update) {
1805                    sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
1806                            packageName, extras, 0 /*flags*/,
1807                            null /*targetPackage*/, null /*finishedReceiver*/,
1808                            updateUsers);
1809                    sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
1810                            null /*package*/, null /*extras*/, 0 /*flags*/,
1811                            packageName /*targetPackage*/,
1812                            null /*finishedReceiver*/, updateUsers);
1813                }
1814
1815                // Send broadcast package appeared if forward locked/external for all users
1816                // treat asec-hosted packages like removable media on upgrade
1817                if (res.pkg.isForwardLocked() || isExternal(res.pkg)) {
1818                    if (DEBUG_INSTALL) {
1819                        Slog.i(TAG, "upgrading pkg " + res.pkg
1820                                + " is ASEC-hosted -> AVAILABLE");
1821                    }
1822                    final int[] uidArray = new int[]{res.pkg.applicationInfo.uid};
1823                    ArrayList<String> pkgList = new ArrayList<>(1);
1824                    pkgList.add(packageName);
1825                    sendResourcesChangedBroadcast(true, true, pkgList, uidArray, null);
1826                }
1827            }
1828
1829            // Work that needs to happen on first install within each user
1830            if (firstUsers != null && firstUsers.length > 0) {
1831                synchronized (mPackages) {
1832                    for (int userId : firstUsers) {
1833                        // If this app is a browser and it's newly-installed for some
1834                        // users, clear any default-browser state in those users. The
1835                        // app's nature doesn't depend on the user, so we can just check
1836                        // its browser nature in any user and generalize.
1837                        if (packageIsBrowser(packageName, userId)) {
1838                            mSettings.setDefaultBrowserPackageNameLPw(null, userId);
1839                        }
1840
1841                        // We may also need to apply pending (restored) runtime
1842                        // permission grants within these users.
1843                        mSettings.applyPendingPermissionGrantsLPw(packageName, userId);
1844                    }
1845                }
1846            }
1847
1848            // Log current value of "unknown sources" setting
1849            EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED,
1850                    getUnknownSourcesSettings());
1851
1852            // Force a gc to clear up things
1853            Runtime.getRuntime().gc();
1854
1855            // Remove the replaced package's older resources safely now
1856            // We delete after a gc for applications  on sdcard.
1857            if (res.removedInfo != null && res.removedInfo.args != null) {
1858                synchronized (mInstallLock) {
1859                    res.removedInfo.args.doPostDeleteLI(true);
1860                }
1861            }
1862        }
1863
1864        // If someone is watching installs - notify them
1865        if (installObserver != null) {
1866            try {
1867                Bundle extras = extrasForInstallResult(res);
1868                installObserver.onPackageInstalled(res.name, res.returnCode,
1869                        res.returnMsg, extras);
1870            } catch (RemoteException e) {
1871                Slog.i(TAG, "Observer no longer exists.");
1872            }
1873        }
1874    }
1875
1876    private void grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(
1877            PackageParser.Package pkg) {
1878        if (pkg.parentPackage == null) {
1879            return;
1880        }
1881        if (pkg.requestedPermissions == null) {
1882            return;
1883        }
1884        final PackageSetting disabledSysParentPs = mSettings
1885                .getDisabledSystemPkgLPr(pkg.parentPackage.packageName);
1886        if (disabledSysParentPs == null || disabledSysParentPs.pkg == null
1887                || !disabledSysParentPs.isPrivileged()
1888                || (disabledSysParentPs.childPackageNames != null
1889                        && !disabledSysParentPs.childPackageNames.isEmpty())) {
1890            return;
1891        }
1892        final int[] allUserIds = sUserManager.getUserIds();
1893        final int permCount = pkg.requestedPermissions.size();
1894        for (int i = 0; i < permCount; i++) {
1895            String permission = pkg.requestedPermissions.get(i);
1896            BasePermission bp = mSettings.mPermissions.get(permission);
1897            if (bp == null || !(bp.isRuntime() || bp.isDevelopment())) {
1898                continue;
1899            }
1900            for (int userId : allUserIds) {
1901                if (disabledSysParentPs.getPermissionsState().hasRuntimePermission(
1902                        permission, userId)) {
1903                    grantRuntimePermission(pkg.packageName, permission, userId);
1904                }
1905            }
1906        }
1907    }
1908
1909    private StorageEventListener mStorageListener = new StorageEventListener() {
1910        @Override
1911        public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) {
1912            if (vol.type == VolumeInfo.TYPE_PRIVATE) {
1913                if (vol.state == VolumeInfo.STATE_MOUNTED) {
1914                    final String volumeUuid = vol.getFsUuid();
1915
1916                    // Clean up any users or apps that were removed or recreated
1917                    // while this volume was missing
1918                    reconcileUsers(volumeUuid);
1919                    reconcileApps(volumeUuid);
1920
1921                    // Clean up any install sessions that expired or were
1922                    // cancelled while this volume was missing
1923                    mInstallerService.onPrivateVolumeMounted(volumeUuid);
1924
1925                    loadPrivatePackages(vol);
1926
1927                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
1928                    unloadPrivatePackages(vol);
1929                }
1930            }
1931
1932            if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) {
1933                if (vol.state == VolumeInfo.STATE_MOUNTED) {
1934                    updateExternalMediaStatus(true, false);
1935                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
1936                    updateExternalMediaStatus(false, false);
1937                }
1938            }
1939        }
1940
1941        @Override
1942        public void onVolumeForgotten(String fsUuid) {
1943            if (TextUtils.isEmpty(fsUuid)) {
1944                Slog.e(TAG, "Forgetting internal storage is probably a mistake; ignoring");
1945                return;
1946            }
1947
1948            // Remove any apps installed on the forgotten volume
1949            synchronized (mPackages) {
1950                final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid);
1951                for (PackageSetting ps : packages) {
1952                    Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten");
1953                    deletePackage(ps.name, new LegacyPackageDeleteObserver(null).getBinder(),
1954                            UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS);
1955                }
1956
1957                mSettings.onVolumeForgotten(fsUuid);
1958                mSettings.writeLPr();
1959            }
1960        }
1961    };
1962
1963    private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int[] userIds,
1964            String[] grantedPermissions) {
1965        for (int userId : userIds) {
1966            grantRequestedRuntimePermissionsForUser(pkg, userId, grantedPermissions);
1967        }
1968
1969        // We could have touched GID membership, so flush out packages.list
1970        synchronized (mPackages) {
1971            mSettings.writePackageListLPr();
1972        }
1973    }
1974
1975    private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId,
1976            String[] grantedPermissions) {
1977        SettingBase sb = (SettingBase) pkg.mExtras;
1978        if (sb == null) {
1979            return;
1980        }
1981
1982        PermissionsState permissionsState = sb.getPermissionsState();
1983
1984        final int immutableFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
1985                | PackageManager.FLAG_PERMISSION_POLICY_FIXED;
1986
1987        synchronized (mPackages) {
1988            for (String permission : pkg.requestedPermissions) {
1989                BasePermission bp = mSettings.mPermissions.get(permission);
1990                if (bp != null && (bp.isRuntime() || bp.isDevelopment())
1991                        && (grantedPermissions == null
1992                               || ArrayUtils.contains(grantedPermissions, permission))) {
1993                    final int flags = permissionsState.getPermissionFlags(permission, userId);
1994                    // Installer cannot change immutable permissions.
1995                    if ((flags & immutableFlags) == 0) {
1996                        grantRuntimePermission(pkg.packageName, permission, userId);
1997                    }
1998                }
1999            }
2000        }
2001    }
2002
2003    Bundle extrasForInstallResult(PackageInstalledInfo res) {
2004        Bundle extras = null;
2005        switch (res.returnCode) {
2006            case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: {
2007                extras = new Bundle();
2008                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION,
2009                        res.origPermission);
2010                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE,
2011                        res.origPackage);
2012                break;
2013            }
2014            case PackageManager.INSTALL_SUCCEEDED: {
2015                extras = new Bundle();
2016                extras.putBoolean(Intent.EXTRA_REPLACING,
2017                        res.removedInfo != null && res.removedInfo.removedPackage != null);
2018                break;
2019            }
2020        }
2021        return extras;
2022    }
2023
2024    void scheduleWriteSettingsLocked() {
2025        if (!mHandler.hasMessages(WRITE_SETTINGS)) {
2026            mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
2027        }
2028    }
2029
2030    void scheduleWritePackageRestrictionsLocked(UserHandle user) {
2031        final int userId = user == null ? UserHandle.USER_ALL : user.getIdentifier();
2032        scheduleWritePackageRestrictionsLocked(userId);
2033    }
2034
2035    void scheduleWritePackageRestrictionsLocked(int userId) {
2036        final int[] userIds = (userId == UserHandle.USER_ALL)
2037                ? sUserManager.getUserIds() : new int[]{userId};
2038        for (int nextUserId : userIds) {
2039            if (!sUserManager.exists(nextUserId)) return;
2040            mDirtyUsers.add(nextUserId);
2041            if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) {
2042                mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY);
2043            }
2044        }
2045    }
2046
2047    public static PackageManagerService main(Context context, Installer installer,
2048            boolean factoryTest, boolean onlyCore) {
2049        // Self-check for initial settings.
2050        PackageManagerServiceCompilerMapping.checkProperties();
2051
2052        PackageManagerService m = new PackageManagerService(context, installer,
2053                factoryTest, onlyCore);
2054        m.enableSystemUserPackages();
2055        // Disable any carrier apps. We do this very early in boot to prevent the apps from being
2056        // disabled after already being started.
2057        CarrierAppUtils.disableCarrierAppsUntilPrivileged(context.getOpPackageName(), m,
2058                UserHandle.USER_SYSTEM);
2059        ServiceManager.addService("package", m);
2060        return m;
2061    }
2062
2063    private void enableSystemUserPackages() {
2064        if (!UserManager.isSplitSystemUser()) {
2065            return;
2066        }
2067        // For system user, enable apps based on the following conditions:
2068        // - app is whitelisted or belong to one of these groups:
2069        //   -- system app which has no launcher icons
2070        //   -- system app which has INTERACT_ACROSS_USERS permission
2071        //   -- system IME app
2072        // - app is not in the blacklist
2073        AppsQueryHelper queryHelper = new AppsQueryHelper(this);
2074        Set<String> enableApps = new ArraySet<>();
2075        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS
2076                | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM
2077                | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM));
2078        ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps();
2079        enableApps.addAll(wlApps);
2080        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_REQUIRED_FOR_SYSTEM_USER,
2081                /* systemAppsOnly */ false, UserHandle.SYSTEM));
2082        ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps();
2083        enableApps.removeAll(blApps);
2084        Log.i(TAG, "Applications installed for system user: " + enableApps);
2085        List<String> allAps = queryHelper.queryApps(0, /* systemAppsOnly */ false,
2086                UserHandle.SYSTEM);
2087        final int allAppsSize = allAps.size();
2088        synchronized (mPackages) {
2089            for (int i = 0; i < allAppsSize; i++) {
2090                String pName = allAps.get(i);
2091                PackageSetting pkgSetting = mSettings.mPackages.get(pName);
2092                // Should not happen, but we shouldn't be failing if it does
2093                if (pkgSetting == null) {
2094                    continue;
2095                }
2096                boolean install = enableApps.contains(pName);
2097                if (pkgSetting.getInstalled(UserHandle.USER_SYSTEM) != install) {
2098                    Log.i(TAG, (install ? "Installing " : "Uninstalling ") + pName
2099                            + " for system user");
2100                    pkgSetting.setInstalled(install, UserHandle.USER_SYSTEM);
2101                }
2102            }
2103        }
2104    }
2105
2106    private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) {
2107        DisplayManager displayManager = (DisplayManager) context.getSystemService(
2108                Context.DISPLAY_SERVICE);
2109        displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics);
2110    }
2111
2112    public PackageManagerService(Context context, Installer installer,
2113            boolean factoryTest, boolean onlyCore) {
2114        EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
2115                SystemClock.uptimeMillis());
2116
2117        if (mSdkVersion <= 0) {
2118            Slog.w(TAG, "**** ro.build.version.sdk not set!");
2119        }
2120
2121        mContext = context;
2122        mFactoryTest = factoryTest;
2123        mOnlyCore = onlyCore;
2124        mMetrics = new DisplayMetrics();
2125        mSettings = new Settings(mPackages);
2126        mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID,
2127                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2128        mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID,
2129                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2130        mSettings.addSharedUserLPw("android.uid.log", LOG_UID,
2131                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2132        mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID,
2133                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2134        mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID,
2135                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2136        mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID,
2137                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2138
2139        String separateProcesses = SystemProperties.get("debug.separate_processes");
2140        if (separateProcesses != null && separateProcesses.length() > 0) {
2141            if ("*".equals(separateProcesses)) {
2142                mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
2143                mSeparateProcesses = null;
2144                Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
2145            } else {
2146                mDefParseFlags = 0;
2147                mSeparateProcesses = separateProcesses.split(",");
2148                Slog.w(TAG, "Running with debug.separate_processes: "
2149                        + separateProcesses);
2150            }
2151        } else {
2152            mDefParseFlags = 0;
2153            mSeparateProcesses = null;
2154        }
2155
2156        mInstaller = installer;
2157        mPackageDexOptimizer = new PackageDexOptimizer(installer, mInstallLock, context,
2158                "*dexopt*");
2159        mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper());
2160
2161        mOnPermissionChangeListeners = new OnPermissionChangeListeners(
2162                FgThread.get().getLooper());
2163
2164        getDefaultDisplayMetrics(context, mMetrics);
2165
2166        SystemConfig systemConfig = SystemConfig.getInstance();
2167        mGlobalGids = systemConfig.getGlobalGids();
2168        mSystemPermissions = systemConfig.getSystemPermissions();
2169        mAvailableFeatures = systemConfig.getAvailableFeatures();
2170
2171        synchronized (mInstallLock) {
2172        // writer
2173        synchronized (mPackages) {
2174            mHandlerThread = new ServiceThread(TAG,
2175                    Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/);
2176            mHandlerThread.start();
2177            mHandler = new PackageHandler(mHandlerThread.getLooper());
2178            mProcessLoggingHandler = new ProcessLoggingHandler();
2179            Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT);
2180
2181            File dataDir = Environment.getDataDirectory();
2182            mAppInstallDir = new File(dataDir, "app");
2183            mAppLib32InstallDir = new File(dataDir, "app-lib");
2184            mEphemeralInstallDir = new File(dataDir, "app-ephemeral");
2185            mAsecInternalPath = new File(dataDir, "app-asec").getPath();
2186            mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
2187
2188            sUserManager = new UserManagerService(context, this, mPackages);
2189
2190            // Propagate permission configuration in to package manager.
2191            ArrayMap<String, SystemConfig.PermissionEntry> permConfig
2192                    = systemConfig.getPermissions();
2193            for (int i=0; i<permConfig.size(); i++) {
2194                SystemConfig.PermissionEntry perm = permConfig.valueAt(i);
2195                BasePermission bp = mSettings.mPermissions.get(perm.name);
2196                if (bp == null) {
2197                    bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN);
2198                    mSettings.mPermissions.put(perm.name, bp);
2199                }
2200                if (perm.gids != null) {
2201                    bp.setGids(perm.gids, perm.perUser);
2202                }
2203            }
2204
2205            ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries();
2206            for (int i=0; i<libConfig.size(); i++) {
2207                mSharedLibraries.put(libConfig.keyAt(i),
2208                        new SharedLibraryEntry(libConfig.valueAt(i), null));
2209            }
2210
2211            mFoundPolicyFile = SELinuxMMAC.readInstallPolicy();
2212
2213            mRestoredSettings = mSettings.readLPw(sUserManager.getUsers(false));
2214
2215            String customResolverActivity = Resources.getSystem().getString(
2216                    R.string.config_customResolverActivity);
2217            if (TextUtils.isEmpty(customResolverActivity)) {
2218                customResolverActivity = null;
2219            } else {
2220                mCustomResolverComponentName = ComponentName.unflattenFromString(
2221                        customResolverActivity);
2222            }
2223
2224            long startTime = SystemClock.uptimeMillis();
2225
2226            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
2227                    startTime);
2228
2229            // Set flag to monitor and not change apk file paths when
2230            // scanning install directories.
2231            final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING | SCAN_INITIAL;
2232
2233            final String bootClassPath = System.getenv("BOOTCLASSPATH");
2234            final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH");
2235
2236            if (bootClassPath == null) {
2237                Slog.w(TAG, "No BOOTCLASSPATH found!");
2238            }
2239
2240            if (systemServerClassPath == null) {
2241                Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!");
2242            }
2243
2244            final List<String> allInstructionSets = InstructionSets.getAllInstructionSets();
2245            final String[] dexCodeInstructionSets =
2246                    getDexCodeInstructionSets(
2247                            allInstructionSets.toArray(new String[allInstructionSets.size()]));
2248
2249            /**
2250             * Ensure all external libraries have had dexopt run on them.
2251             */
2252            if (mSharedLibraries.size() > 0) {
2253                // NOTE: For now, we're compiling these system "shared libraries"
2254                // (and framework jars) into all available architectures. It's possible
2255                // to compile them only when we come across an app that uses them (there's
2256                // already logic for that in scanPackageLI) but that adds some complexity.
2257                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
2258                    for (SharedLibraryEntry libEntry : mSharedLibraries.values()) {
2259                        final String lib = libEntry.path;
2260                        if (lib == null) {
2261                            continue;
2262                        }
2263
2264                        try {
2265                            // Shared libraries do not have profiles so we perform a full
2266                            // AOT compilation (if needed).
2267                            int dexoptNeeded = DexFile.getDexOptNeeded(
2268                                    lib, dexCodeInstructionSet,
2269                                    getCompilerFilterForReason(REASON_SHARED_APK),
2270                                    false /* newProfile */);
2271                            if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) {
2272                                mInstaller.dexopt(lib, Process.SYSTEM_UID, dexCodeInstructionSet,
2273                                        dexoptNeeded, DEXOPT_PUBLIC /*dexFlags*/,
2274                                        getCompilerFilterForReason(REASON_SHARED_APK),
2275                                        StorageManager.UUID_PRIVATE_INTERNAL);
2276                            }
2277                        } catch (FileNotFoundException e) {
2278                            Slog.w(TAG, "Library not found: " + lib);
2279                        } catch (IOException | InstallerException e) {
2280                            Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? "
2281                                    + e.getMessage());
2282                        }
2283                    }
2284                }
2285            }
2286
2287            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
2288
2289            final VersionInfo ver = mSettings.getInternalVersion();
2290            mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint);
2291
2292            // when upgrading from pre-M, promote system app permissions from install to runtime
2293            mPromoteSystemApps =
2294                    mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1;
2295
2296            // save off the names of pre-existing system packages prior to scanning; we don't
2297            // want to automatically grant runtime permissions for new system apps
2298            if (mPromoteSystemApps) {
2299                Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator();
2300                while (pkgSettingIter.hasNext()) {
2301                    PackageSetting ps = pkgSettingIter.next();
2302                    if (isSystemApp(ps)) {
2303                        mExistingSystemPackages.add(ps.name);
2304                    }
2305                }
2306            }
2307
2308            // When upgrading from pre-N, we need to handle package extraction like first boot,
2309            // as there is no profiling data available.
2310            mIsPreNUpgrade = !mSettings.isNWorkDone();
2311            mSettings.setNWorkDone();
2312
2313            // Collect vendor overlay packages.
2314            // (Do this before scanning any apps.)
2315            // For security and version matching reason, only consider
2316            // overlay packages if they reside in VENDOR_OVERLAY_DIR.
2317            File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR);
2318            scanDirTracedLI(vendorOverlayDir, mDefParseFlags
2319                    | PackageParser.PARSE_IS_SYSTEM
2320                    | PackageParser.PARSE_IS_SYSTEM_DIR
2321                    | PackageParser.PARSE_TRUSTED_OVERLAY, scanFlags | SCAN_TRUSTED_OVERLAY, 0);
2322
2323            // Find base frameworks (resource packages without code).
2324            scanDirTracedLI(frameworkDir, mDefParseFlags
2325                    | PackageParser.PARSE_IS_SYSTEM
2326                    | PackageParser.PARSE_IS_SYSTEM_DIR
2327                    | PackageParser.PARSE_IS_PRIVILEGED,
2328                    scanFlags | SCAN_NO_DEX, 0);
2329
2330            // Collected privileged system packages.
2331            final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
2332            scanDirTracedLI(privilegedAppDir, mDefParseFlags
2333                    | PackageParser.PARSE_IS_SYSTEM
2334                    | PackageParser.PARSE_IS_SYSTEM_DIR
2335                    | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0);
2336
2337            // Collect ordinary system packages.
2338            final File systemAppDir = new File(Environment.getRootDirectory(), "app");
2339            scanDirTracedLI(systemAppDir, mDefParseFlags
2340                    | PackageParser.PARSE_IS_SYSTEM
2341                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2342
2343            // Collect all vendor packages.
2344            File vendorAppDir = new File("/vendor/app");
2345            try {
2346                vendorAppDir = vendorAppDir.getCanonicalFile();
2347            } catch (IOException e) {
2348                // failed to look up canonical path, continue with original one
2349            }
2350            scanDirTracedLI(vendorAppDir, mDefParseFlags
2351                    | PackageParser.PARSE_IS_SYSTEM
2352                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2353
2354            // Collect all OEM packages.
2355            final File oemAppDir = new File(Environment.getOemDirectory(), "app");
2356            scanDirTracedLI(oemAppDir, mDefParseFlags
2357                    | PackageParser.PARSE_IS_SYSTEM
2358                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2359
2360            // Prune any system packages that no longer exist.
2361            final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>();
2362            if (!mOnlyCore) {
2363                Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
2364                while (psit.hasNext()) {
2365                    PackageSetting ps = psit.next();
2366
2367                    /*
2368                     * If this is not a system app, it can't be a
2369                     * disable system app.
2370                     */
2371                    if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
2372                        continue;
2373                    }
2374
2375                    /*
2376                     * If the package is scanned, it's not erased.
2377                     */
2378                    final PackageParser.Package scannedPkg = mPackages.get(ps.name);
2379                    if (scannedPkg != null) {
2380                        /*
2381                         * If the system app is both scanned and in the
2382                         * disabled packages list, then it must have been
2383                         * added via OTA. Remove it from the currently
2384                         * scanned package so the previously user-installed
2385                         * application can be scanned.
2386                         */
2387                        if (mSettings.isDisabledSystemPackageLPr(ps.name)) {
2388                            logCriticalInfo(Log.WARN, "Expecting better updated system app for "
2389                                    + ps.name + "; removing system app.  Last known codePath="
2390                                    + ps.codePathString + ", installStatus=" + ps.installStatus
2391                                    + ", versionCode=" + ps.versionCode + "; scanned versionCode="
2392                                    + scannedPkg.mVersionCode);
2393                            removePackageLI(scannedPkg, true);
2394                            mExpectingBetter.put(ps.name, ps.codePath);
2395                        }
2396
2397                        continue;
2398                    }
2399
2400                    if (!mSettings.isDisabledSystemPackageLPr(ps.name)) {
2401                        psit.remove();
2402                        logCriticalInfo(Log.WARN, "System package " + ps.name
2403                                + " no longer exists; it's data will be wiped");
2404                        // Actual deletion of code and data will be handled by later
2405                        // reconciliation step
2406                    } else {
2407                        final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name);
2408                        if (disabledPs.codePath == null || !disabledPs.codePath.exists()) {
2409                            possiblyDeletedUpdatedSystemApps.add(ps.name);
2410                        }
2411                    }
2412                }
2413            }
2414
2415            //look for any incomplete package installations
2416            ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr();
2417            for (int i = 0; i < deletePkgsList.size(); i++) {
2418                // Actual deletion of code and data will be handled by later
2419                // reconciliation step
2420                final String packageName = deletePkgsList.get(i).name;
2421                logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + packageName);
2422                synchronized (mPackages) {
2423                    mSettings.removePackageLPw(packageName);
2424                }
2425            }
2426
2427            //delete tmp files
2428            deleteTempPackageFiles();
2429
2430            // Remove any shared userIDs that have no associated packages
2431            mSettings.pruneSharedUsersLPw();
2432
2433            if (!mOnlyCore) {
2434                EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
2435                        SystemClock.uptimeMillis());
2436                scanDirTracedLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0);
2437
2438                scanDirTracedLI(mDrmAppPrivateInstallDir, mDefParseFlags
2439                        | PackageParser.PARSE_FORWARD_LOCK,
2440                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2441
2442                scanDirLI(mEphemeralInstallDir, mDefParseFlags
2443                        | PackageParser.PARSE_IS_EPHEMERAL,
2444                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2445
2446                /**
2447                 * Remove disable package settings for any updated system
2448                 * apps that were removed via an OTA. If they're not a
2449                 * previously-updated app, remove them completely.
2450                 * Otherwise, just revoke their system-level permissions.
2451                 */
2452                for (String deletedAppName : possiblyDeletedUpdatedSystemApps) {
2453                    PackageParser.Package deletedPkg = mPackages.get(deletedAppName);
2454                    mSettings.removeDisabledSystemPackageLPw(deletedAppName);
2455
2456                    String msg;
2457                    if (deletedPkg == null) {
2458                        msg = "Updated system package " + deletedAppName
2459                                + " no longer exists; it's data will be wiped";
2460                        // Actual deletion of code and data will be handled by later
2461                        // reconciliation step
2462                    } else {
2463                        msg = "Updated system app + " + deletedAppName
2464                                + " no longer present; removing system privileges for "
2465                                + deletedAppName;
2466
2467                        deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM;
2468
2469                        PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName);
2470                        deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM;
2471                    }
2472                    logCriticalInfo(Log.WARN, msg);
2473                }
2474
2475                /**
2476                 * Make sure all system apps that we expected to appear on
2477                 * the userdata partition actually showed up. If they never
2478                 * appeared, crawl back and revive the system version.
2479                 */
2480                for (int i = 0; i < mExpectingBetter.size(); i++) {
2481                    final String packageName = mExpectingBetter.keyAt(i);
2482                    if (!mPackages.containsKey(packageName)) {
2483                        final File scanFile = mExpectingBetter.valueAt(i);
2484
2485                        logCriticalInfo(Log.WARN, "Expected better " + packageName
2486                                + " but never showed up; reverting to system");
2487
2488                        int reparseFlags = mDefParseFlags;
2489                        if (FileUtils.contains(privilegedAppDir, scanFile)) {
2490                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2491                                    | PackageParser.PARSE_IS_SYSTEM_DIR
2492                                    | PackageParser.PARSE_IS_PRIVILEGED;
2493                        } else if (FileUtils.contains(systemAppDir, scanFile)) {
2494                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2495                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2496                        } else if (FileUtils.contains(vendorAppDir, scanFile)) {
2497                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2498                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2499                        } else if (FileUtils.contains(oemAppDir, scanFile)) {
2500                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2501                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2502                        } else {
2503                            Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile);
2504                            continue;
2505                        }
2506
2507                        mSettings.enableSystemPackageLPw(packageName);
2508
2509                        try {
2510                            scanPackageTracedLI(scanFile, reparseFlags, scanFlags, 0, null);
2511                        } catch (PackageManagerException e) {
2512                            Slog.e(TAG, "Failed to parse original system package: "
2513                                    + e.getMessage());
2514                        }
2515                    }
2516                }
2517            }
2518            mExpectingBetter.clear();
2519
2520            // Resolve protected action filters. Only the setup wizard is allowed to
2521            // have a high priority filter for these actions.
2522            mSetupWizardPackage = getSetupWizardPackageName();
2523            if (mProtectedFilters.size() > 0) {
2524                if (DEBUG_FILTERS && mSetupWizardPackage == null) {
2525                    Slog.i(TAG, "No setup wizard;"
2526                        + " All protected intents capped to priority 0");
2527                }
2528                for (ActivityIntentInfo filter : mProtectedFilters) {
2529                    if (filter.activity.info.packageName.equals(mSetupWizardPackage)) {
2530                        if (DEBUG_FILTERS) {
2531                            Slog.i(TAG, "Found setup wizard;"
2532                                + " allow priority " + filter.getPriority() + ";"
2533                                + " package: " + filter.activity.info.packageName
2534                                + " activity: " + filter.activity.className
2535                                + " priority: " + filter.getPriority());
2536                        }
2537                        // skip setup wizard; allow it to keep the high priority filter
2538                        continue;
2539                    }
2540                    Slog.w(TAG, "Protected action; cap priority to 0;"
2541                            + " package: " + filter.activity.info.packageName
2542                            + " activity: " + filter.activity.className
2543                            + " origPrio: " + filter.getPriority());
2544                    filter.setPriority(0);
2545                }
2546            }
2547            mDeferProtectedFilters = false;
2548            mProtectedFilters.clear();
2549
2550            // Now that we know all of the shared libraries, update all clients to have
2551            // the correct library paths.
2552            updateAllSharedLibrariesLPw();
2553
2554            for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) {
2555                // NOTE: We ignore potential failures here during a system scan (like
2556                // the rest of the commands above) because there's precious little we
2557                // can do about it. A settings error is reported, though.
2558                adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */,
2559                        false /* boot complete */);
2560            }
2561
2562            // Now that we know all the packages we are keeping,
2563            // read and update their last usage times.
2564            mPackageUsage.readLP();
2565
2566            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
2567                    SystemClock.uptimeMillis());
2568            Slog.i(TAG, "Time to scan packages: "
2569                    + ((SystemClock.uptimeMillis()-startTime)/1000f)
2570                    + " seconds");
2571
2572            // If the platform SDK has changed since the last time we booted,
2573            // we need to re-grant app permission to catch any new ones that
2574            // appear.  This is really a hack, and means that apps can in some
2575            // cases get permissions that the user didn't initially explicitly
2576            // allow...  it would be nice to have some better way to handle
2577            // this situation.
2578            int updateFlags = UPDATE_PERMISSIONS_ALL;
2579            if (ver.sdkVersion != mSdkVersion) {
2580                Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to "
2581                        + mSdkVersion + "; regranting permissions for internal storage");
2582                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
2583            }
2584            updatePermissionsLPw(null, null, StorageManager.UUID_PRIVATE_INTERNAL, updateFlags);
2585            ver.sdkVersion = mSdkVersion;
2586
2587            // If this is the first boot or an update from pre-M, and it is a normal
2588            // boot, then we need to initialize the default preferred apps across
2589            // all defined users.
2590            if (!onlyCore && (mPromoteSystemApps || !mRestoredSettings)) {
2591                for (UserInfo user : sUserManager.getUsers(true)) {
2592                    mSettings.applyDefaultPreferredAppsLPw(this, user.id);
2593                    applyFactoryDefaultBrowserLPw(user.id);
2594                    primeDomainVerificationsLPw(user.id);
2595                }
2596            }
2597
2598            // Prepare storage for system user really early during boot,
2599            // since core system apps like SettingsProvider and SystemUI
2600            // can't wait for user to start
2601            final int storageFlags;
2602            if (StorageManager.isFileEncryptedNativeOrEmulated()) {
2603                storageFlags = StorageManager.FLAG_STORAGE_DE;
2604            } else {
2605                storageFlags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
2606            }
2607            reconcileAppsDataLI(StorageManager.UUID_PRIVATE_INTERNAL, UserHandle.USER_SYSTEM,
2608                    storageFlags);
2609
2610            // If this is first boot after an OTA, and a normal boot, then
2611            // we need to clear code cache directories.
2612            if (mIsUpgrade && !onlyCore) {
2613                Slog.i(TAG, "Build fingerprint changed; clearing code caches");
2614                for (int i = 0; i < mSettings.mPackages.size(); i++) {
2615                    final PackageSetting ps = mSettings.mPackages.valueAt(i);
2616                    if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) {
2617                        // No apps are running this early, so no need to freeze
2618                        clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
2619                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
2620                                        | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
2621                    }
2622                    clearAppProfilesLIF(ps.pkg);
2623                }
2624                ver.fingerprint = Build.FINGERPRINT;
2625            }
2626
2627            checkDefaultBrowser();
2628
2629            // clear only after permissions and other defaults have been updated
2630            mExistingSystemPackages.clear();
2631            mPromoteSystemApps = false;
2632
2633            // All the changes are done during package scanning.
2634            ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION;
2635
2636            // can downgrade to reader
2637            mSettings.writeLPr();
2638
2639            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
2640                    SystemClock.uptimeMillis());
2641
2642            if (!mOnlyCore) {
2643                mRequiredVerifierPackage = getRequiredButNotReallyRequiredVerifierLPr();
2644                mRequiredInstallerPackage = getRequiredInstallerLPr();
2645                mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr();
2646                mIntentFilterVerifier = new IntentVerifierProxy(mContext,
2647                        mIntentFilterVerifierComponent);
2648                mServicesSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
2649                        PackageManager.SYSTEM_SHARED_LIBRARY_SERVICES);
2650                getRequiredSharedLibraryLPr(
2651                        PackageManager.SYSTEM_SHARED_LIBRARY_SHARED);
2652            } else {
2653                mRequiredVerifierPackage = null;
2654                mRequiredInstallerPackage = null;
2655                mIntentFilterVerifierComponent = null;
2656                mIntentFilterVerifier = null;
2657                mServicesSystemSharedLibraryPackageName = null;
2658            }
2659
2660            mInstallerService = new PackageInstallerService(context, this);
2661
2662            final ComponentName ephemeralResolverComponent = getEphemeralResolverLPr();
2663            final ComponentName ephemeralInstallerComponent = getEphemeralInstallerLPr();
2664            // both the installer and resolver must be present to enable ephemeral
2665            if (ephemeralInstallerComponent != null && ephemeralResolverComponent != null) {
2666                if (DEBUG_EPHEMERAL) {
2667                    Slog.i(TAG, "Ephemeral activated; resolver: " + ephemeralResolverComponent
2668                            + " installer:" + ephemeralInstallerComponent);
2669                }
2670                mEphemeralResolverComponent = ephemeralResolverComponent;
2671                mEphemeralInstallerComponent = ephemeralInstallerComponent;
2672                setUpEphemeralInstallerActivityLP(mEphemeralInstallerComponent);
2673                mEphemeralResolverConnection =
2674                        new EphemeralResolverConnection(mContext, mEphemeralResolverComponent);
2675            } else {
2676                if (DEBUG_EPHEMERAL) {
2677                    final String missingComponent =
2678                            (ephemeralResolverComponent == null)
2679                            ? (ephemeralInstallerComponent == null)
2680                                    ? "resolver and installer"
2681                                    : "resolver"
2682                            : "installer";
2683                    Slog.i(TAG, "Ephemeral deactivated; missing " + missingComponent);
2684                }
2685                mEphemeralResolverComponent = null;
2686                mEphemeralInstallerComponent = null;
2687                mEphemeralResolverConnection = null;
2688            }
2689
2690            mEphemeralApplicationRegistry = new EphemeralApplicationRegistry(this);
2691        } // synchronized (mPackages)
2692        } // synchronized (mInstallLock)
2693
2694        // Now after opening every single application zip, make sure they
2695        // are all flushed.  Not really needed, but keeps things nice and
2696        // tidy.
2697        Runtime.getRuntime().gc();
2698
2699        // The initial scanning above does many calls into installd while
2700        // holding the mPackages lock, but we're mostly interested in yelling
2701        // once we have a booted system.
2702        mInstaller.setWarnIfHeld(mPackages);
2703
2704        // Expose private service for system components to use.
2705        LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl());
2706    }
2707
2708    @Override
2709    public boolean isFirstBoot() {
2710        return !mRestoredSettings;
2711    }
2712
2713    @Override
2714    public boolean isOnlyCoreApps() {
2715        return mOnlyCore;
2716    }
2717
2718    @Override
2719    public boolean isUpgrade() {
2720        return mIsUpgrade;
2721    }
2722
2723    private @Nullable String getRequiredButNotReallyRequiredVerifierLPr() {
2724        final Intent intent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
2725
2726        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
2727                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
2728                UserHandle.USER_SYSTEM);
2729        if (matches.size() == 1) {
2730            return matches.get(0).getComponentInfo().packageName;
2731        } else {
2732            Log.e(TAG, "There should probably be exactly one verifier; found " + matches);
2733            return null;
2734        }
2735    }
2736
2737    private @NonNull String getRequiredSharedLibraryLPr(String libraryName) {
2738        synchronized (mPackages) {
2739            SharedLibraryEntry libraryEntry = mSharedLibraries.get(libraryName);
2740            if (libraryEntry == null) {
2741                throw new IllegalStateException("Missing required shared library:" + libraryName);
2742            }
2743            return libraryEntry.apk;
2744        }
2745    }
2746
2747    private @NonNull String getRequiredInstallerLPr() {
2748        final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
2749        intent.addCategory(Intent.CATEGORY_DEFAULT);
2750        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
2751
2752        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
2753                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
2754                UserHandle.USER_SYSTEM);
2755        if (matches.size() == 1) {
2756            ResolveInfo resolveInfo = matches.get(0);
2757            if (!resolveInfo.activityInfo.applicationInfo.isPrivilegedApp()) {
2758                throw new RuntimeException("The installer must be a privileged app");
2759            }
2760            return matches.get(0).getComponentInfo().packageName;
2761        } else {
2762            throw new RuntimeException("There must be exactly one installer; found " + matches);
2763        }
2764    }
2765
2766    private @NonNull ComponentName getIntentFilterVerifierComponentNameLPr() {
2767        final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
2768
2769        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
2770                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
2771                UserHandle.USER_SYSTEM);
2772        ResolveInfo best = null;
2773        final int N = matches.size();
2774        for (int i = 0; i < N; i++) {
2775            final ResolveInfo cur = matches.get(i);
2776            final String packageName = cur.getComponentInfo().packageName;
2777            if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
2778                    packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) {
2779                continue;
2780            }
2781
2782            if (best == null || cur.priority > best.priority) {
2783                best = cur;
2784            }
2785        }
2786
2787        if (best != null) {
2788            return best.getComponentInfo().getComponentName();
2789        } else {
2790            throw new RuntimeException("There must be at least one intent filter verifier");
2791        }
2792    }
2793
2794    private @Nullable ComponentName getEphemeralResolverLPr() {
2795        final String[] packageArray =
2796                mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage);
2797        if (packageArray.length == 0) {
2798            if (DEBUG_EPHEMERAL) {
2799                Slog.d(TAG, "Ephemeral resolver NOT found; empty package list");
2800            }
2801            return null;
2802        }
2803
2804        final Intent resolverIntent = new Intent(Intent.ACTION_RESOLVE_EPHEMERAL_PACKAGE);
2805        final List<ResolveInfo> resolvers = queryIntentServicesInternal(resolverIntent, null,
2806                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
2807                UserHandle.USER_SYSTEM);
2808
2809        final int N = resolvers.size();
2810        if (N == 0) {
2811            if (DEBUG_EPHEMERAL) {
2812                Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters");
2813            }
2814            return null;
2815        }
2816
2817        final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray));
2818        for (int i = 0; i < N; i++) {
2819            final ResolveInfo info = resolvers.get(i);
2820
2821            if (info.serviceInfo == null) {
2822                continue;
2823            }
2824
2825            final String packageName = info.serviceInfo.packageName;
2826            if (!possiblePackages.contains(packageName)) {
2827                if (DEBUG_EPHEMERAL) {
2828                    Slog.d(TAG, "Ephemeral resolver not in allowed package list;"
2829                            + " pkg: " + packageName + ", info:" + info);
2830                }
2831                continue;
2832            }
2833
2834            if (DEBUG_EPHEMERAL) {
2835                Slog.v(TAG, "Ephemeral resolver found;"
2836                        + " pkg: " + packageName + ", info:" + info);
2837            }
2838            return new ComponentName(packageName, info.serviceInfo.name);
2839        }
2840        if (DEBUG_EPHEMERAL) {
2841            Slog.v(TAG, "Ephemeral resolver NOT found");
2842        }
2843        return null;
2844    }
2845
2846    private @Nullable ComponentName getEphemeralInstallerLPr() {
2847        final Intent intent = new Intent(Intent.ACTION_INSTALL_EPHEMERAL_PACKAGE);
2848        intent.addCategory(Intent.CATEGORY_DEFAULT);
2849        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
2850
2851        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
2852                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
2853                UserHandle.USER_SYSTEM);
2854        if (matches.size() == 0) {
2855            return null;
2856        } else if (matches.size() == 1) {
2857            return matches.get(0).getComponentInfo().getComponentName();
2858        } else {
2859            throw new RuntimeException(
2860                    "There must be at most one ephemeral installer; found " + matches);
2861        }
2862    }
2863
2864    private void primeDomainVerificationsLPw(int userId) {
2865        if (DEBUG_DOMAIN_VERIFICATION) {
2866            Slog.d(TAG, "Priming domain verifications in user " + userId);
2867        }
2868
2869        SystemConfig systemConfig = SystemConfig.getInstance();
2870        ArraySet<String> packages = systemConfig.getLinkedApps();
2871        ArraySet<String> domains = new ArraySet<String>();
2872
2873        for (String packageName : packages) {
2874            PackageParser.Package pkg = mPackages.get(packageName);
2875            if (pkg != null) {
2876                if (!pkg.isSystemApp()) {
2877                    Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>");
2878                    continue;
2879                }
2880
2881                domains.clear();
2882                for (PackageParser.Activity a : pkg.activities) {
2883                    for (ActivityIntentInfo filter : a.intents) {
2884                        if (hasValidDomains(filter)) {
2885                            domains.addAll(filter.getHostsList());
2886                        }
2887                    }
2888                }
2889
2890                if (domains.size() > 0) {
2891                    if (DEBUG_DOMAIN_VERIFICATION) {
2892                        Slog.v(TAG, "      + " + packageName);
2893                    }
2894                    // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual
2895                    // state w.r.t. the formal app-linkage "no verification attempted" state;
2896                    // and then 'always' in the per-user state actually used for intent resolution.
2897                    final IntentFilterVerificationInfo ivi;
2898                    ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName,
2899                            new ArrayList<String>(domains));
2900                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED);
2901                    mSettings.updateIntentFilterVerificationStatusLPw(packageName,
2902                            INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId);
2903                } else {
2904                    Slog.w(TAG, "Sysconfig <app-link> package '" + packageName
2905                            + "' does not handle web links");
2906                }
2907            } else {
2908                Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>");
2909            }
2910        }
2911
2912        scheduleWritePackageRestrictionsLocked(userId);
2913        scheduleWriteSettingsLocked();
2914    }
2915
2916    private void applyFactoryDefaultBrowserLPw(int userId) {
2917        // The default browser app's package name is stored in a string resource,
2918        // with a product-specific overlay used for vendor customization.
2919        String browserPkg = mContext.getResources().getString(
2920                com.android.internal.R.string.default_browser);
2921        if (!TextUtils.isEmpty(browserPkg)) {
2922            // non-empty string => required to be a known package
2923            PackageSetting ps = mSettings.mPackages.get(browserPkg);
2924            if (ps == null) {
2925                Slog.e(TAG, "Product default browser app does not exist: " + browserPkg);
2926                browserPkg = null;
2927            } else {
2928                mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
2929            }
2930        }
2931
2932        // Nothing valid explicitly set? Make the factory-installed browser the explicit
2933        // default.  If there's more than one, just leave everything alone.
2934        if (browserPkg == null) {
2935            calculateDefaultBrowserLPw(userId);
2936        }
2937    }
2938
2939    private void calculateDefaultBrowserLPw(int userId) {
2940        List<String> allBrowsers = resolveAllBrowserApps(userId);
2941        final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null;
2942        mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
2943    }
2944
2945    private List<String> resolveAllBrowserApps(int userId) {
2946        // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set
2947        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
2948                PackageManager.MATCH_ALL, userId);
2949
2950        final int count = list.size();
2951        List<String> result = new ArrayList<String>(count);
2952        for (int i=0; i<count; i++) {
2953            ResolveInfo info = list.get(i);
2954            if (info.activityInfo == null
2955                    || !info.handleAllWebDataURI
2956                    || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0
2957                    || result.contains(info.activityInfo.packageName)) {
2958                continue;
2959            }
2960            result.add(info.activityInfo.packageName);
2961        }
2962
2963        return result;
2964    }
2965
2966    private boolean packageIsBrowser(String packageName, int userId) {
2967        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
2968                PackageManager.MATCH_ALL, userId);
2969        final int N = list.size();
2970        for (int i = 0; i < N; i++) {
2971            ResolveInfo info = list.get(i);
2972            if (packageName.equals(info.activityInfo.packageName)) {
2973                return true;
2974            }
2975        }
2976        return false;
2977    }
2978
2979    private void checkDefaultBrowser() {
2980        final int myUserId = UserHandle.myUserId();
2981        final String packageName = getDefaultBrowserPackageName(myUserId);
2982        if (packageName != null) {
2983            PackageInfo info = getPackageInfo(packageName, 0, myUserId);
2984            if (info == null) {
2985                Slog.w(TAG, "Default browser no longer installed: " + packageName);
2986                synchronized (mPackages) {
2987                    applyFactoryDefaultBrowserLPw(myUserId);    // leaves ambiguous when > 1
2988                }
2989            }
2990        }
2991    }
2992
2993    @Override
2994    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
2995            throws RemoteException {
2996        try {
2997            return super.onTransact(code, data, reply, flags);
2998        } catch (RuntimeException e) {
2999            if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
3000                Slog.wtf(TAG, "Package Manager Crash", e);
3001            }
3002            throw e;
3003        }
3004    }
3005
3006    static int[] appendInts(int[] cur, int[] add) {
3007        if (add == null) return cur;
3008        if (cur == null) return add;
3009        final int N = add.length;
3010        for (int i=0; i<N; i++) {
3011            cur = appendInt(cur, add[i]);
3012        }
3013        return cur;
3014    }
3015
3016    private PackageInfo generatePackageInfo(PackageSetting ps, int flags, int userId) {
3017        if (!sUserManager.exists(userId)) return null;
3018        if (ps == null) {
3019            return null;
3020        }
3021        final PackageParser.Package p = ps.pkg;
3022        if (p == null) {
3023            return null;
3024        }
3025
3026        final PermissionsState permissionsState = ps.getPermissionsState();
3027
3028        final int[] gids = permissionsState.computeGids(userId);
3029        final Set<String> permissions = permissionsState.getPermissions(userId);
3030        final PackageUserState state = ps.readUserState(userId);
3031
3032        return PackageParser.generatePackageInfo(p, gids, flags,
3033                ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId);
3034    }
3035
3036    @Override
3037    public void checkPackageStartable(String packageName, int userId) {
3038        final boolean userKeyUnlocked = isUserKeyUnlocked(userId);
3039
3040        synchronized (mPackages) {
3041            final PackageSetting ps = mSettings.mPackages.get(packageName);
3042            if (ps == null) {
3043                throw new SecurityException("Package " + packageName + " was not found!");
3044            }
3045
3046            if (!ps.getInstalled(userId)) {
3047                throw new SecurityException(
3048                        "Package " + packageName + " was not installed for user " + userId + "!");
3049            }
3050
3051            if (mSafeMode && !ps.isSystem()) {
3052                throw new SecurityException("Package " + packageName + " not a system app!");
3053            }
3054
3055            if (mFrozenPackages.contains(packageName)) {
3056                throw new SecurityException("Package " + packageName + " is currently frozen!");
3057            }
3058
3059            if (!userKeyUnlocked && !(ps.pkg.applicationInfo.isDirectBootAware()
3060                    || ps.pkg.applicationInfo.isPartiallyDirectBootAware())) {
3061                throw new SecurityException("Package " + packageName + " is not encryption aware!");
3062            }
3063        }
3064    }
3065
3066    @Override
3067    public boolean isPackageAvailable(String packageName, int userId) {
3068        if (!sUserManager.exists(userId)) return false;
3069        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3070                false /* requireFullPermission */, false /* checkShell */, "is package available");
3071        synchronized (mPackages) {
3072            PackageParser.Package p = mPackages.get(packageName);
3073            if (p != null) {
3074                final PackageSetting ps = (PackageSetting) p.mExtras;
3075                if (ps != null) {
3076                    final PackageUserState state = ps.readUserState(userId);
3077                    if (state != null) {
3078                        return PackageParser.isAvailable(state);
3079                    }
3080                }
3081            }
3082        }
3083        return false;
3084    }
3085
3086    @Override
3087    public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
3088        if (!sUserManager.exists(userId)) return null;
3089        flags = updateFlagsForPackage(flags, userId, packageName);
3090        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3091                false /* requireFullPermission */, false /* checkShell */, "get package info");
3092        // reader
3093        synchronized (mPackages) {
3094            final boolean matchFactoryOnly = (flags & MATCH_FACTORY_ONLY) != 0;
3095            PackageParser.Package p = null;
3096            if (matchFactoryOnly) {
3097                final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName);
3098                if (ps != null) {
3099                    return generatePackageInfo(ps, flags, userId);
3100                }
3101            }
3102            if (p == null) {
3103                p = mPackages.get(packageName);
3104                if (matchFactoryOnly && p != null && !isSystemApp(p)) {
3105                    return null;
3106                }
3107            }
3108            if (DEBUG_PACKAGE_INFO)
3109                Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
3110            if (p != null) {
3111                return generatePackageInfo((PackageSetting)p.mExtras, flags, userId);
3112            }
3113            if (!matchFactoryOnly && (flags & MATCH_UNINSTALLED_PACKAGES) != 0) {
3114                final PackageSetting ps = mSettings.mPackages.get(packageName);
3115                return generatePackageInfo(ps, flags, userId);
3116            }
3117        }
3118        return null;
3119    }
3120
3121    @Override
3122    public String[] currentToCanonicalPackageNames(String[] names) {
3123        String[] out = new String[names.length];
3124        // reader
3125        synchronized (mPackages) {
3126            for (int i=names.length-1; i>=0; i--) {
3127                PackageSetting ps = mSettings.mPackages.get(names[i]);
3128                out[i] = ps != null && ps.realName != null ? ps.realName : names[i];
3129            }
3130        }
3131        return out;
3132    }
3133
3134    @Override
3135    public String[] canonicalToCurrentPackageNames(String[] names) {
3136        String[] out = new String[names.length];
3137        // reader
3138        synchronized (mPackages) {
3139            for (int i=names.length-1; i>=0; i--) {
3140                String cur = mSettings.mRenamedPackages.get(names[i]);
3141                out[i] = cur != null ? cur : names[i];
3142            }
3143        }
3144        return out;
3145    }
3146
3147    @Override
3148    public int getPackageUid(String packageName, int flags, int userId) {
3149        if (!sUserManager.exists(userId)) return -1;
3150        flags = updateFlagsForPackage(flags, userId, packageName);
3151        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3152                false /* requireFullPermission */, false /* checkShell */, "get package uid");
3153
3154        // reader
3155        synchronized (mPackages) {
3156            final PackageParser.Package p = mPackages.get(packageName);
3157            if (p != null && p.isMatch(flags)) {
3158                return UserHandle.getUid(userId, p.applicationInfo.uid);
3159            }
3160            if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) {
3161                final PackageSetting ps = mSettings.mPackages.get(packageName);
3162                if (ps != null && ps.isMatch(flags)) {
3163                    return UserHandle.getUid(userId, ps.appId);
3164                }
3165            }
3166        }
3167
3168        return -1;
3169    }
3170
3171    @Override
3172    public int[] getPackageGids(String packageName, int flags, int userId) {
3173        if (!sUserManager.exists(userId)) return null;
3174        flags = updateFlagsForPackage(flags, userId, packageName);
3175        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3176                false /* requireFullPermission */, false /* checkShell */,
3177                "getPackageGids");
3178
3179        // reader
3180        synchronized (mPackages) {
3181            final PackageParser.Package p = mPackages.get(packageName);
3182            if (p != null && p.isMatch(flags)) {
3183                PackageSetting ps = (PackageSetting) p.mExtras;
3184                return ps.getPermissionsState().computeGids(userId);
3185            }
3186            if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) {
3187                final PackageSetting ps = mSettings.mPackages.get(packageName);
3188                if (ps != null && ps.isMatch(flags)) {
3189                    return ps.getPermissionsState().computeGids(userId);
3190                }
3191            }
3192        }
3193
3194        return null;
3195    }
3196
3197    static PermissionInfo generatePermissionInfo(BasePermission bp, int flags) {
3198        if (bp.perm != null) {
3199            return PackageParser.generatePermissionInfo(bp.perm, flags);
3200        }
3201        PermissionInfo pi = new PermissionInfo();
3202        pi.name = bp.name;
3203        pi.packageName = bp.sourcePackage;
3204        pi.nonLocalizedLabel = bp.name;
3205        pi.protectionLevel = bp.protectionLevel;
3206        return pi;
3207    }
3208
3209    @Override
3210    public PermissionInfo getPermissionInfo(String name, int flags) {
3211        // reader
3212        synchronized (mPackages) {
3213            final BasePermission p = mSettings.mPermissions.get(name);
3214            if (p != null) {
3215                return generatePermissionInfo(p, flags);
3216            }
3217            return null;
3218        }
3219    }
3220
3221    @Override
3222    public @Nullable ParceledListSlice<PermissionInfo> queryPermissionsByGroup(String group,
3223            int flags) {
3224        // reader
3225        synchronized (mPackages) {
3226            if (group != null && !mPermissionGroups.containsKey(group)) {
3227                // This is thrown as NameNotFoundException
3228                return null;
3229            }
3230
3231            ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
3232            for (BasePermission p : mSettings.mPermissions.values()) {
3233                if (group == null) {
3234                    if (p.perm == null || p.perm.info.group == null) {
3235                        out.add(generatePermissionInfo(p, flags));
3236                    }
3237                } else {
3238                    if (p.perm != null && group.equals(p.perm.info.group)) {
3239                        out.add(PackageParser.generatePermissionInfo(p.perm, flags));
3240                    }
3241                }
3242            }
3243            return new ParceledListSlice<>(out);
3244        }
3245    }
3246
3247    @Override
3248    public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
3249        // reader
3250        synchronized (mPackages) {
3251            return PackageParser.generatePermissionGroupInfo(
3252                    mPermissionGroups.get(name), flags);
3253        }
3254    }
3255
3256    @Override
3257    public @NonNull ParceledListSlice<PermissionGroupInfo> getAllPermissionGroups(int flags) {
3258        // reader
3259        synchronized (mPackages) {
3260            final int N = mPermissionGroups.size();
3261            ArrayList<PermissionGroupInfo> out
3262                    = new ArrayList<PermissionGroupInfo>(N);
3263            for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
3264                out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
3265            }
3266            return new ParceledListSlice<>(out);
3267        }
3268    }
3269
3270    private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
3271            int userId) {
3272        if (!sUserManager.exists(userId)) return null;
3273        PackageSetting ps = mSettings.mPackages.get(packageName);
3274        if (ps != null) {
3275            if (ps.pkg == null) {
3276                final PackageInfo pInfo = generatePackageInfo(ps, flags, userId);
3277                if (pInfo != null) {
3278                    return pInfo.applicationInfo;
3279                }
3280                return null;
3281            }
3282            return PackageParser.generateApplicationInfo(ps.pkg, flags,
3283                    ps.readUserState(userId), userId);
3284        }
3285        return null;
3286    }
3287
3288    @Override
3289    public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
3290        if (!sUserManager.exists(userId)) return null;
3291        flags = updateFlagsForApplication(flags, userId, packageName);
3292        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3293                false /* requireFullPermission */, false /* checkShell */, "get application info");
3294        // writer
3295        synchronized (mPackages) {
3296            PackageParser.Package p = mPackages.get(packageName);
3297            if (DEBUG_PACKAGE_INFO) Log.v(
3298                    TAG, "getApplicationInfo " + packageName
3299                    + ": " + p);
3300            if (p != null) {
3301                PackageSetting ps = mSettings.mPackages.get(packageName);
3302                if (ps == null) return null;
3303                // Note: isEnabledLP() does not apply here - always return info
3304                return PackageParser.generateApplicationInfo(
3305                        p, flags, ps.readUserState(userId), userId);
3306            }
3307            if ("android".equals(packageName)||"system".equals(packageName)) {
3308                return mAndroidApplication;
3309            }
3310            if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) {
3311                return generateApplicationInfoFromSettingsLPw(packageName, flags, userId);
3312            }
3313        }
3314        return null;
3315    }
3316
3317    @Override
3318    public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize,
3319            final IPackageDataObserver observer) {
3320        mContext.enforceCallingOrSelfPermission(
3321                android.Manifest.permission.CLEAR_APP_CACHE, null);
3322        // Queue up an async operation since clearing cache may take a little while.
3323        mHandler.post(new Runnable() {
3324            public void run() {
3325                mHandler.removeCallbacks(this);
3326                boolean success = true;
3327                synchronized (mInstallLock) {
3328                    try {
3329                        mInstaller.freeCache(volumeUuid, freeStorageSize);
3330                    } catch (InstallerException e) {
3331                        Slog.w(TAG, "Couldn't clear application caches: " + e);
3332                        success = false;
3333                    }
3334                }
3335                if (observer != null) {
3336                    try {
3337                        observer.onRemoveCompleted(null, success);
3338                    } catch (RemoteException e) {
3339                        Slog.w(TAG, "RemoveException when invoking call back");
3340                    }
3341                }
3342            }
3343        });
3344    }
3345
3346    @Override
3347    public void freeStorage(final String volumeUuid, final long freeStorageSize,
3348            final IntentSender pi) {
3349        mContext.enforceCallingOrSelfPermission(
3350                android.Manifest.permission.CLEAR_APP_CACHE, null);
3351        // Queue up an async operation since clearing cache may take a little while.
3352        mHandler.post(new Runnable() {
3353            public void run() {
3354                mHandler.removeCallbacks(this);
3355                boolean success = true;
3356                synchronized (mInstallLock) {
3357                    try {
3358                        mInstaller.freeCache(volumeUuid, freeStorageSize);
3359                    } catch (InstallerException e) {
3360                        Slog.w(TAG, "Couldn't clear application caches: " + e);
3361                        success = false;
3362                    }
3363                }
3364                if(pi != null) {
3365                    try {
3366                        // Callback via pending intent
3367                        int code = success ? 1 : 0;
3368                        pi.sendIntent(null, code, null,
3369                                null, null);
3370                    } catch (SendIntentException e1) {
3371                        Slog.i(TAG, "Failed to send pending intent");
3372                    }
3373                }
3374            }
3375        });
3376    }
3377
3378    void freeStorage(String volumeUuid, long freeStorageSize) throws IOException {
3379        synchronized (mInstallLock) {
3380            try {
3381                mInstaller.freeCache(volumeUuid, freeStorageSize);
3382            } catch (InstallerException e) {
3383                throw new IOException("Failed to free enough space", e);
3384            }
3385        }
3386    }
3387
3388    /**
3389     * Return if the user key is currently unlocked.
3390     */
3391    private boolean isUserKeyUnlocked(int userId) {
3392        if (StorageManager.isFileEncryptedNativeOrEmulated()) {
3393            final IMountService mount = IMountService.Stub
3394                    .asInterface(ServiceManager.getService("mount"));
3395            if (mount == null) {
3396                Slog.w(TAG, "Early during boot, assuming locked");
3397                return false;
3398            }
3399            final long token = Binder.clearCallingIdentity();
3400            try {
3401                return mount.isUserKeyUnlocked(userId);
3402            } catch (RemoteException e) {
3403                throw e.rethrowAsRuntimeException();
3404            } finally {
3405                Binder.restoreCallingIdentity(token);
3406            }
3407        } else {
3408            return true;
3409        }
3410    }
3411
3412    /**
3413     * Update given flags based on encryption status of current user.
3414     */
3415    private int updateFlags(int flags, int userId) {
3416        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
3417                | PackageManager.MATCH_DIRECT_BOOT_AWARE)) != 0) {
3418            // Caller expressed an explicit opinion about what encryption
3419            // aware/unaware components they want to see, so fall through and
3420            // give them what they want
3421        } else {
3422            // Caller expressed no opinion, so match based on user state
3423            if (isUserKeyUnlocked(userId)) {
3424                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE;
3425            } else {
3426                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE;
3427            }
3428        }
3429        return flags;
3430    }
3431
3432    /**
3433     * Update given flags when being used to request {@link PackageInfo}.
3434     */
3435    private int updateFlagsForPackage(int flags, int userId, Object cookie) {
3436        boolean triaged = true;
3437        if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS
3438                | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) {
3439            // Caller is asking for component details, so they'd better be
3440            // asking for specific encryption matching behavior, or be triaged
3441            if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
3442                    | PackageManager.MATCH_DIRECT_BOOT_AWARE
3443                    | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
3444                triaged = false;
3445            }
3446        }
3447        if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES
3448                | PackageManager.MATCH_SYSTEM_ONLY
3449                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
3450            triaged = false;
3451        }
3452        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
3453            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
3454                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
3455        }
3456        return updateFlags(flags, userId);
3457    }
3458
3459    /**
3460     * Update given flags when being used to request {@link ApplicationInfo}.
3461     */
3462    private int updateFlagsForApplication(int flags, int userId, Object cookie) {
3463        return updateFlagsForPackage(flags, userId, cookie);
3464    }
3465
3466    /**
3467     * Update given flags when being used to request {@link ComponentInfo}.
3468     */
3469    private int updateFlagsForComponent(int flags, int userId, Object cookie) {
3470        if (cookie instanceof Intent) {
3471            if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) {
3472                flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
3473            }
3474        }
3475
3476        boolean triaged = true;
3477        // Caller is asking for component details, so they'd better be
3478        // asking for specific encryption matching behavior, or be triaged
3479        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
3480                | PackageManager.MATCH_DIRECT_BOOT_AWARE
3481                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
3482            triaged = false;
3483        }
3484        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
3485            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
3486                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
3487        }
3488
3489        return updateFlags(flags, userId);
3490    }
3491
3492    /**
3493     * Update given flags when being used to request {@link ResolveInfo}.
3494     */
3495    int updateFlagsForResolve(int flags, int userId, Object cookie) {
3496        // Safe mode means we shouldn't match any third-party components
3497        if (mSafeMode) {
3498            flags |= PackageManager.MATCH_SYSTEM_ONLY;
3499        }
3500
3501        return updateFlagsForComponent(flags, userId, cookie);
3502    }
3503
3504    @Override
3505    public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
3506        if (!sUserManager.exists(userId)) return null;
3507        flags = updateFlagsForComponent(flags, userId, component);
3508        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3509                false /* requireFullPermission */, false /* checkShell */, "get activity info");
3510        synchronized (mPackages) {
3511            PackageParser.Activity a = mActivities.mActivities.get(component);
3512
3513            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
3514            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
3515                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3516                if (ps == null) return null;
3517                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
3518                        userId);
3519            }
3520            if (mResolveComponentName.equals(component)) {
3521                return PackageParser.generateActivityInfo(mResolveActivity, flags,
3522                        new PackageUserState(), userId);
3523            }
3524        }
3525        return null;
3526    }
3527
3528    @Override
3529    public boolean activitySupportsIntent(ComponentName component, Intent intent,
3530            String resolvedType) {
3531        synchronized (mPackages) {
3532            if (component.equals(mResolveComponentName)) {
3533                // The resolver supports EVERYTHING!
3534                return true;
3535            }
3536            PackageParser.Activity a = mActivities.mActivities.get(component);
3537            if (a == null) {
3538                return false;
3539            }
3540            for (int i=0; i<a.intents.size(); i++) {
3541                if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
3542                        intent.getData(), intent.getCategories(), TAG) >= 0) {
3543                    return true;
3544                }
3545            }
3546            return false;
3547        }
3548    }
3549
3550    @Override
3551    public ActivityInfo getReceiverInfo(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 receiver info");
3556        synchronized (mPackages) {
3557            PackageParser.Activity a = mReceivers.mActivities.get(component);
3558            if (DEBUG_PACKAGE_INFO) Log.v(
3559                TAG, "getReceiverInfo " + component + ": " + a);
3560            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
3561                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3562                if (ps == null) return null;
3563                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
3564                        userId);
3565            }
3566        }
3567        return null;
3568    }
3569
3570    @Override
3571    public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
3572        if (!sUserManager.exists(userId)) return null;
3573        flags = updateFlagsForComponent(flags, userId, component);
3574        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3575                false /* requireFullPermission */, false /* checkShell */, "get service info");
3576        synchronized (mPackages) {
3577            PackageParser.Service s = mServices.mServices.get(component);
3578            if (DEBUG_PACKAGE_INFO) Log.v(
3579                TAG, "getServiceInfo " + component + ": " + s);
3580            if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) {
3581                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3582                if (ps == null) return null;
3583                return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId),
3584                        userId);
3585            }
3586        }
3587        return null;
3588    }
3589
3590    @Override
3591    public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
3592        if (!sUserManager.exists(userId)) return null;
3593        flags = updateFlagsForComponent(flags, userId, component);
3594        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3595                false /* requireFullPermission */, false /* checkShell */, "get provider info");
3596        synchronized (mPackages) {
3597            PackageParser.Provider p = mProviders.mProviders.get(component);
3598            if (DEBUG_PACKAGE_INFO) Log.v(
3599                TAG, "getProviderInfo " + component + ": " + p);
3600            if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
3601                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3602                if (ps == null) return null;
3603                return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId),
3604                        userId);
3605            }
3606        }
3607        return null;
3608    }
3609
3610    @Override
3611    public String[] getSystemSharedLibraryNames() {
3612        Set<String> libSet;
3613        synchronized (mPackages) {
3614            libSet = mSharedLibraries.keySet();
3615            int size = libSet.size();
3616            if (size > 0) {
3617                String[] libs = new String[size];
3618                libSet.toArray(libs);
3619                return libs;
3620            }
3621        }
3622        return null;
3623    }
3624
3625    @Override
3626    public @NonNull String getServicesSystemSharedLibraryPackageName() {
3627        synchronized (mPackages) {
3628            return mServicesSystemSharedLibraryPackageName;
3629        }
3630    }
3631
3632    @Override
3633    public @NonNull ParceledListSlice<FeatureInfo> getSystemAvailableFeatures() {
3634        synchronized (mPackages) {
3635            final ArrayList<FeatureInfo> res = new ArrayList<>(mAvailableFeatures.values());
3636
3637            final FeatureInfo fi = new FeatureInfo();
3638            fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
3639                    FeatureInfo.GL_ES_VERSION_UNDEFINED);
3640            res.add(fi);
3641
3642            return new ParceledListSlice<>(res);
3643        }
3644    }
3645
3646    @Override
3647    public boolean hasSystemFeature(String name, int version) {
3648        synchronized (mPackages) {
3649            final FeatureInfo feat = mAvailableFeatures.get(name);
3650            if (feat == null) {
3651                return false;
3652            } else {
3653                return feat.version >= version;
3654            }
3655        }
3656    }
3657
3658    @Override
3659    public int checkPermission(String permName, String pkgName, int userId) {
3660        if (!sUserManager.exists(userId)) {
3661            return PackageManager.PERMISSION_DENIED;
3662        }
3663
3664        synchronized (mPackages) {
3665            final PackageParser.Package p = mPackages.get(pkgName);
3666            if (p != null && p.mExtras != null) {
3667                final PackageSetting ps = (PackageSetting) p.mExtras;
3668                final PermissionsState permissionsState = ps.getPermissionsState();
3669                if (permissionsState.hasPermission(permName, userId)) {
3670                    return PackageManager.PERMISSION_GRANTED;
3671                }
3672                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
3673                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
3674                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
3675                    return PackageManager.PERMISSION_GRANTED;
3676                }
3677            }
3678        }
3679
3680        return PackageManager.PERMISSION_DENIED;
3681    }
3682
3683    @Override
3684    public int checkUidPermission(String permName, int uid) {
3685        final int userId = UserHandle.getUserId(uid);
3686
3687        if (!sUserManager.exists(userId)) {
3688            return PackageManager.PERMISSION_DENIED;
3689        }
3690
3691        synchronized (mPackages) {
3692            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
3693            if (obj != null) {
3694                final SettingBase ps = (SettingBase) obj;
3695                final PermissionsState permissionsState = ps.getPermissionsState();
3696                if (permissionsState.hasPermission(permName, userId)) {
3697                    return PackageManager.PERMISSION_GRANTED;
3698                }
3699                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
3700                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
3701                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
3702                    return PackageManager.PERMISSION_GRANTED;
3703                }
3704            } else {
3705                ArraySet<String> perms = mSystemPermissions.get(uid);
3706                if (perms != null) {
3707                    if (perms.contains(permName)) {
3708                        return PackageManager.PERMISSION_GRANTED;
3709                    }
3710                    if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms
3711                            .contains(Manifest.permission.ACCESS_FINE_LOCATION)) {
3712                        return PackageManager.PERMISSION_GRANTED;
3713                    }
3714                }
3715            }
3716        }
3717
3718        return PackageManager.PERMISSION_DENIED;
3719    }
3720
3721    @Override
3722    public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) {
3723        if (UserHandle.getCallingUserId() != userId) {
3724            mContext.enforceCallingPermission(
3725                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
3726                    "isPermissionRevokedByPolicy for user " + userId);
3727        }
3728
3729        if (checkPermission(permission, packageName, userId)
3730                == PackageManager.PERMISSION_GRANTED) {
3731            return false;
3732        }
3733
3734        final long identity = Binder.clearCallingIdentity();
3735        try {
3736            final int flags = getPermissionFlags(permission, packageName, userId);
3737            return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0;
3738        } finally {
3739            Binder.restoreCallingIdentity(identity);
3740        }
3741    }
3742
3743    @Override
3744    public String getPermissionControllerPackageName() {
3745        synchronized (mPackages) {
3746            return mRequiredInstallerPackage;
3747        }
3748    }
3749
3750    /**
3751     * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS
3752     * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller.
3753     * @param checkShell whether to prevent shell from access if there's a debugging restriction
3754     * @param message the message to log on security exception
3755     */
3756    void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission,
3757            boolean checkShell, String message) {
3758        if (userId < 0) {
3759            throw new IllegalArgumentException("Invalid userId " + userId);
3760        }
3761        if (checkShell) {
3762            enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId);
3763        }
3764        if (userId == UserHandle.getUserId(callingUid)) return;
3765        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
3766            if (requireFullPermission) {
3767                mContext.enforceCallingOrSelfPermission(
3768                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
3769            } else {
3770                try {
3771                    mContext.enforceCallingOrSelfPermission(
3772                            android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
3773                } catch (SecurityException se) {
3774                    mContext.enforceCallingOrSelfPermission(
3775                            android.Manifest.permission.INTERACT_ACROSS_USERS, message);
3776                }
3777            }
3778        }
3779    }
3780
3781    void enforceShellRestriction(String restriction, int callingUid, int userHandle) {
3782        if (callingUid == Process.SHELL_UID) {
3783            if (userHandle >= 0
3784                    && sUserManager.hasUserRestriction(restriction, userHandle)) {
3785                throw new SecurityException("Shell does not have permission to access user "
3786                        + userHandle);
3787            } else if (userHandle < 0) {
3788                Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t"
3789                        + Debug.getCallers(3));
3790            }
3791        }
3792    }
3793
3794    private BasePermission findPermissionTreeLP(String permName) {
3795        for(BasePermission bp : mSettings.mPermissionTrees.values()) {
3796            if (permName.startsWith(bp.name) &&
3797                    permName.length() > bp.name.length() &&
3798                    permName.charAt(bp.name.length()) == '.') {
3799                return bp;
3800            }
3801        }
3802        return null;
3803    }
3804
3805    private BasePermission checkPermissionTreeLP(String permName) {
3806        if (permName != null) {
3807            BasePermission bp = findPermissionTreeLP(permName);
3808            if (bp != null) {
3809                if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) {
3810                    return bp;
3811                }
3812                throw new SecurityException("Calling uid "
3813                        + Binder.getCallingUid()
3814                        + " is not allowed to add to permission tree "
3815                        + bp.name + " owned by uid " + bp.uid);
3816            }
3817        }
3818        throw new SecurityException("No permission tree found for " + permName);
3819    }
3820
3821    static boolean compareStrings(CharSequence s1, CharSequence s2) {
3822        if (s1 == null) {
3823            return s2 == null;
3824        }
3825        if (s2 == null) {
3826            return false;
3827        }
3828        if (s1.getClass() != s2.getClass()) {
3829            return false;
3830        }
3831        return s1.equals(s2);
3832    }
3833
3834    static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
3835        if (pi1.icon != pi2.icon) return false;
3836        if (pi1.logo != pi2.logo) return false;
3837        if (pi1.protectionLevel != pi2.protectionLevel) return false;
3838        if (!compareStrings(pi1.name, pi2.name)) return false;
3839        if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
3840        // We'll take care of setting this one.
3841        if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
3842        // These are not currently stored in settings.
3843        //if (!compareStrings(pi1.group, pi2.group)) return false;
3844        //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
3845        //if (pi1.labelRes != pi2.labelRes) return false;
3846        //if (pi1.descriptionRes != pi2.descriptionRes) return false;
3847        return true;
3848    }
3849
3850    int permissionInfoFootprint(PermissionInfo info) {
3851        int size = info.name.length();
3852        if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length();
3853        if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length();
3854        return size;
3855    }
3856
3857    int calculateCurrentPermissionFootprintLocked(BasePermission tree) {
3858        int size = 0;
3859        for (BasePermission perm : mSettings.mPermissions.values()) {
3860            if (perm.uid == tree.uid) {
3861                size += perm.name.length() + permissionInfoFootprint(perm.perm.info);
3862            }
3863        }
3864        return size;
3865    }
3866
3867    void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) {
3868        // We calculate the max size of permissions defined by this uid and throw
3869        // if that plus the size of 'info' would exceed our stated maximum.
3870        if (tree.uid != Process.SYSTEM_UID) {
3871            final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree);
3872            if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) {
3873                throw new SecurityException("Permission tree size cap exceeded");
3874            }
3875        }
3876    }
3877
3878    boolean addPermissionLocked(PermissionInfo info, boolean async) {
3879        if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
3880            throw new SecurityException("Label must be specified in permission");
3881        }
3882        BasePermission tree = checkPermissionTreeLP(info.name);
3883        BasePermission bp = mSettings.mPermissions.get(info.name);
3884        boolean added = bp == null;
3885        boolean changed = true;
3886        int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel);
3887        if (added) {
3888            enforcePermissionCapLocked(info, tree);
3889            bp = new BasePermission(info.name, tree.sourcePackage,
3890                    BasePermission.TYPE_DYNAMIC);
3891        } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
3892            throw new SecurityException(
3893                    "Not allowed to modify non-dynamic permission "
3894                    + info.name);
3895        } else {
3896            if (bp.protectionLevel == fixedLevel
3897                    && bp.perm.owner.equals(tree.perm.owner)
3898                    && bp.uid == tree.uid
3899                    && comparePermissionInfos(bp.perm.info, info)) {
3900                changed = false;
3901            }
3902        }
3903        bp.protectionLevel = fixedLevel;
3904        info = new PermissionInfo(info);
3905        info.protectionLevel = fixedLevel;
3906        bp.perm = new PackageParser.Permission(tree.perm.owner, info);
3907        bp.perm.info.packageName = tree.perm.info.packageName;
3908        bp.uid = tree.uid;
3909        if (added) {
3910            mSettings.mPermissions.put(info.name, bp);
3911        }
3912        if (changed) {
3913            if (!async) {
3914                mSettings.writeLPr();
3915            } else {
3916                scheduleWriteSettingsLocked();
3917            }
3918        }
3919        return added;
3920    }
3921
3922    @Override
3923    public boolean addPermission(PermissionInfo info) {
3924        synchronized (mPackages) {
3925            return addPermissionLocked(info, false);
3926        }
3927    }
3928
3929    @Override
3930    public boolean addPermissionAsync(PermissionInfo info) {
3931        synchronized (mPackages) {
3932            return addPermissionLocked(info, true);
3933        }
3934    }
3935
3936    @Override
3937    public void removePermission(String name) {
3938        synchronized (mPackages) {
3939            checkPermissionTreeLP(name);
3940            BasePermission bp = mSettings.mPermissions.get(name);
3941            if (bp != null) {
3942                if (bp.type != BasePermission.TYPE_DYNAMIC) {
3943                    throw new SecurityException(
3944                            "Not allowed to modify non-dynamic permission "
3945                            + name);
3946                }
3947                mSettings.mPermissions.remove(name);
3948                mSettings.writeLPr();
3949            }
3950        }
3951    }
3952
3953    private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(PackageParser.Package pkg,
3954            BasePermission bp) {
3955        int index = pkg.requestedPermissions.indexOf(bp.name);
3956        if (index == -1) {
3957            throw new SecurityException("Package " + pkg.packageName
3958                    + " has not requested permission " + bp.name);
3959        }
3960        if (!bp.isRuntime() && !bp.isDevelopment()) {
3961            throw new SecurityException("Permission " + bp.name
3962                    + " is not a changeable permission type");
3963        }
3964    }
3965
3966    @Override
3967    public void grantRuntimePermission(String packageName, String name, final int userId) {
3968        if (!sUserManager.exists(userId)) {
3969            Log.e(TAG, "No such user:" + userId);
3970            return;
3971        }
3972
3973        mContext.enforceCallingOrSelfPermission(
3974                android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
3975                "grantRuntimePermission");
3976
3977        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3978                true /* requireFullPermission */, true /* checkShell */,
3979                "grantRuntimePermission");
3980
3981        final int uid;
3982        final SettingBase sb;
3983
3984        synchronized (mPackages) {
3985            final PackageParser.Package pkg = mPackages.get(packageName);
3986            if (pkg == null) {
3987                throw new IllegalArgumentException("Unknown package: " + packageName);
3988            }
3989
3990            final BasePermission bp = mSettings.mPermissions.get(name);
3991            if (bp == null) {
3992                throw new IllegalArgumentException("Unknown permission: " + name);
3993            }
3994
3995            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
3996
3997            // If a permission review is required for legacy apps we represent
3998            // their permissions as always granted runtime ones since we need
3999            // to keep the review required permission flag per user while an
4000            // install permission's state is shared across all users.
4001            if (Build.PERMISSIONS_REVIEW_REQUIRED
4002                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
4003                    && bp.isRuntime()) {
4004                return;
4005            }
4006
4007            uid = UserHandle.getUid(userId, pkg.applicationInfo.uid);
4008            sb = (SettingBase) pkg.mExtras;
4009            if (sb == null) {
4010                throw new IllegalArgumentException("Unknown package: " + packageName);
4011            }
4012
4013            final PermissionsState permissionsState = sb.getPermissionsState();
4014
4015            final int flags = permissionsState.getPermissionFlags(name, userId);
4016            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
4017                throw new SecurityException("Cannot grant system fixed permission "
4018                        + name + " for package " + packageName);
4019            }
4020
4021            if (bp.isDevelopment()) {
4022                // Development permissions must be handled specially, since they are not
4023                // normal runtime permissions.  For now they apply to all users.
4024                if (permissionsState.grantInstallPermission(bp) !=
4025                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
4026                    scheduleWriteSettingsLocked();
4027                }
4028                return;
4029            }
4030
4031            if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
4032                Slog.w(TAG, "Cannot grant runtime permission to a legacy app");
4033                return;
4034            }
4035
4036            final int result = permissionsState.grantRuntimePermission(bp, userId);
4037            switch (result) {
4038                case PermissionsState.PERMISSION_OPERATION_FAILURE: {
4039                    return;
4040                }
4041
4042                case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
4043                    final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
4044                    mHandler.post(new Runnable() {
4045                        @Override
4046                        public void run() {
4047                            killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED);
4048                        }
4049                    });
4050                }
4051                break;
4052            }
4053
4054            mOnPermissionChangeListeners.onPermissionsChanged(uid);
4055
4056            // Not critical if that is lost - app has to request again.
4057            mSettings.writeRuntimePermissionsForUserLPr(userId, false);
4058        }
4059
4060        // Only need to do this if user is initialized. Otherwise it's a new user
4061        // and there are no processes running as the user yet and there's no need
4062        // to make an expensive call to remount processes for the changed permissions.
4063        if (READ_EXTERNAL_STORAGE.equals(name)
4064                || WRITE_EXTERNAL_STORAGE.equals(name)) {
4065            final long token = Binder.clearCallingIdentity();
4066            try {
4067                if (sUserManager.isInitialized(userId)) {
4068                    MountServiceInternal mountServiceInternal = LocalServices.getService(
4069                            MountServiceInternal.class);
4070                    mountServiceInternal.onExternalStoragePolicyChanged(uid, packageName);
4071                }
4072            } finally {
4073                Binder.restoreCallingIdentity(token);
4074            }
4075        }
4076    }
4077
4078    @Override
4079    public void revokeRuntimePermission(String packageName, String name, int userId) {
4080        if (!sUserManager.exists(userId)) {
4081            Log.e(TAG, "No such user:" + userId);
4082            return;
4083        }
4084
4085        mContext.enforceCallingOrSelfPermission(
4086                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
4087                "revokeRuntimePermission");
4088
4089        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4090                true /* requireFullPermission */, true /* checkShell */,
4091                "revokeRuntimePermission");
4092
4093        final int appId;
4094
4095        synchronized (mPackages) {
4096            final PackageParser.Package pkg = mPackages.get(packageName);
4097            if (pkg == null) {
4098                throw new IllegalArgumentException("Unknown package: " + packageName);
4099            }
4100
4101            final BasePermission bp = mSettings.mPermissions.get(name);
4102            if (bp == null) {
4103                throw new IllegalArgumentException("Unknown permission: " + name);
4104            }
4105
4106            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
4107
4108            // If a permission review is required for legacy apps we represent
4109            // their permissions as always granted runtime ones since we need
4110            // to keep the review required permission flag per user while an
4111            // install permission's state is shared across all users.
4112            if (Build.PERMISSIONS_REVIEW_REQUIRED
4113                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
4114                    && bp.isRuntime()) {
4115                return;
4116            }
4117
4118            SettingBase sb = (SettingBase) pkg.mExtras;
4119            if (sb == null) {
4120                throw new IllegalArgumentException("Unknown package: " + packageName);
4121            }
4122
4123            final PermissionsState permissionsState = sb.getPermissionsState();
4124
4125            final int flags = permissionsState.getPermissionFlags(name, userId);
4126            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
4127                throw new SecurityException("Cannot revoke system fixed permission "
4128                        + name + " for package " + packageName);
4129            }
4130
4131            if (bp.isDevelopment()) {
4132                // Development permissions must be handled specially, since they are not
4133                // normal runtime permissions.  For now they apply to all users.
4134                if (permissionsState.revokeInstallPermission(bp) !=
4135                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
4136                    scheduleWriteSettingsLocked();
4137                }
4138                return;
4139            }
4140
4141            if (permissionsState.revokeRuntimePermission(bp, userId) ==
4142                    PermissionsState.PERMISSION_OPERATION_FAILURE) {
4143                return;
4144            }
4145
4146            mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid);
4147
4148            // Critical, after this call app should never have the permission.
4149            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
4150
4151            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
4152        }
4153
4154        killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
4155    }
4156
4157    @Override
4158    public void resetRuntimePermissions() {
4159        mContext.enforceCallingOrSelfPermission(
4160                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
4161                "revokeRuntimePermission");
4162
4163        int callingUid = Binder.getCallingUid();
4164        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
4165            mContext.enforceCallingOrSelfPermission(
4166                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
4167                    "resetRuntimePermissions");
4168        }
4169
4170        synchronized (mPackages) {
4171            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL);
4172            for (int userId : UserManagerService.getInstance().getUserIds()) {
4173                final int packageCount = mPackages.size();
4174                for (int i = 0; i < packageCount; i++) {
4175                    PackageParser.Package pkg = mPackages.valueAt(i);
4176                    if (!(pkg.mExtras instanceof PackageSetting)) {
4177                        continue;
4178                    }
4179                    PackageSetting ps = (PackageSetting) pkg.mExtras;
4180                    resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
4181                }
4182            }
4183        }
4184    }
4185
4186    @Override
4187    public int getPermissionFlags(String name, String packageName, int userId) {
4188        if (!sUserManager.exists(userId)) {
4189            return 0;
4190        }
4191
4192        enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags");
4193
4194        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4195                true /* requireFullPermission */, false /* checkShell */,
4196                "getPermissionFlags");
4197
4198        synchronized (mPackages) {
4199            final PackageParser.Package pkg = mPackages.get(packageName);
4200            if (pkg == null) {
4201                throw new IllegalArgumentException("Unknown package: " + packageName);
4202            }
4203
4204            final BasePermission bp = mSettings.mPermissions.get(name);
4205            if (bp == null) {
4206                throw new IllegalArgumentException("Unknown permission: " + name);
4207            }
4208
4209            SettingBase sb = (SettingBase) pkg.mExtras;
4210            if (sb == null) {
4211                throw new IllegalArgumentException("Unknown package: " + packageName);
4212            }
4213
4214            PermissionsState permissionsState = sb.getPermissionsState();
4215            return permissionsState.getPermissionFlags(name, userId);
4216        }
4217    }
4218
4219    @Override
4220    public void updatePermissionFlags(String name, String packageName, int flagMask,
4221            int flagValues, int userId) {
4222        if (!sUserManager.exists(userId)) {
4223            return;
4224        }
4225
4226        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags");
4227
4228        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4229                true /* requireFullPermission */, true /* checkShell */,
4230                "updatePermissionFlags");
4231
4232        // Only the system can change these flags and nothing else.
4233        if (getCallingUid() != Process.SYSTEM_UID) {
4234            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4235            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4236            flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
4237            flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
4238            flagValues &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
4239        }
4240
4241        synchronized (mPackages) {
4242            final PackageParser.Package pkg = mPackages.get(packageName);
4243            if (pkg == null) {
4244                throw new IllegalArgumentException("Unknown package: " + packageName);
4245            }
4246
4247            final BasePermission bp = mSettings.mPermissions.get(name);
4248            if (bp == null) {
4249                throw new IllegalArgumentException("Unknown permission: " + name);
4250            }
4251
4252            SettingBase sb = (SettingBase) pkg.mExtras;
4253            if (sb == null) {
4254                throw new IllegalArgumentException("Unknown package: " + packageName);
4255            }
4256
4257            PermissionsState permissionsState = sb.getPermissionsState();
4258
4259            boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null;
4260
4261            if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) {
4262                // Install and runtime permissions are stored in different places,
4263                // so figure out what permission changed and persist the change.
4264                if (permissionsState.getInstallPermissionState(name) != null) {
4265                    scheduleWriteSettingsLocked();
4266                } else if (permissionsState.getRuntimePermissionState(name, userId) != null
4267                        || hadState) {
4268                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
4269                }
4270            }
4271        }
4272    }
4273
4274    /**
4275     * Update the permission flags for all packages and runtime permissions of a user in order
4276     * to allow device or profile owner to remove POLICY_FIXED.
4277     */
4278    @Override
4279    public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) {
4280        if (!sUserManager.exists(userId)) {
4281            return;
4282        }
4283
4284        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps");
4285
4286        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4287                true /* requireFullPermission */, true /* checkShell */,
4288                "updatePermissionFlagsForAllApps");
4289
4290        // Only the system can change system fixed flags.
4291        if (getCallingUid() != Process.SYSTEM_UID) {
4292            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4293            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4294        }
4295
4296        synchronized (mPackages) {
4297            boolean changed = false;
4298            final int packageCount = mPackages.size();
4299            for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) {
4300                final PackageParser.Package pkg = mPackages.valueAt(pkgIndex);
4301                SettingBase sb = (SettingBase) pkg.mExtras;
4302                if (sb == null) {
4303                    continue;
4304                }
4305                PermissionsState permissionsState = sb.getPermissionsState();
4306                changed |= permissionsState.updatePermissionFlagsForAllPermissions(
4307                        userId, flagMask, flagValues);
4308            }
4309            if (changed) {
4310                mSettings.writeRuntimePermissionsForUserLPr(userId, false);
4311            }
4312        }
4313    }
4314
4315    private void enforceGrantRevokeRuntimePermissionPermissions(String message) {
4316        if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS)
4317                != PackageManager.PERMISSION_GRANTED
4318            && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS)
4319                != PackageManager.PERMISSION_GRANTED) {
4320            throw new SecurityException(message + " requires "
4321                    + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or "
4322                    + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS);
4323        }
4324    }
4325
4326    @Override
4327    public boolean shouldShowRequestPermissionRationale(String permissionName,
4328            String packageName, int userId) {
4329        if (UserHandle.getCallingUserId() != userId) {
4330            mContext.enforceCallingPermission(
4331                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
4332                    "canShowRequestPermissionRationale for user " + userId);
4333        }
4334
4335        final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId);
4336        if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) {
4337            return false;
4338        }
4339
4340        if (checkPermission(permissionName, packageName, userId)
4341                == PackageManager.PERMISSION_GRANTED) {
4342            return false;
4343        }
4344
4345        final int flags;
4346
4347        final long identity = Binder.clearCallingIdentity();
4348        try {
4349            flags = getPermissionFlags(permissionName,
4350                    packageName, userId);
4351        } finally {
4352            Binder.restoreCallingIdentity(identity);
4353        }
4354
4355        final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
4356                | PackageManager.FLAG_PERMISSION_POLICY_FIXED
4357                | PackageManager.FLAG_PERMISSION_USER_FIXED;
4358
4359        if ((flags & fixedFlags) != 0) {
4360            return false;
4361        }
4362
4363        return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0;
4364    }
4365
4366    @Override
4367    public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
4368        mContext.enforceCallingOrSelfPermission(
4369                Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS,
4370                "addOnPermissionsChangeListener");
4371
4372        synchronized (mPackages) {
4373            mOnPermissionChangeListeners.addListenerLocked(listener);
4374        }
4375    }
4376
4377    @Override
4378    public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
4379        synchronized (mPackages) {
4380            mOnPermissionChangeListeners.removeListenerLocked(listener);
4381        }
4382    }
4383
4384    @Override
4385    public boolean isProtectedBroadcast(String actionName) {
4386        synchronized (mPackages) {
4387            if (mProtectedBroadcasts.contains(actionName)) {
4388                return true;
4389            } else if (actionName != null) {
4390                // TODO: remove these terrible hacks
4391                if (actionName.startsWith("android.net.netmon.lingerExpired")
4392                        || actionName.startsWith("com.android.server.sip.SipWakeupTimer")
4393                        || actionName.startsWith("com.android.internal.telephony.data-reconnect")
4394                        || actionName.startsWith("android.net.netmon.launchCaptivePortalApp")) {
4395                    return true;
4396                }
4397            }
4398        }
4399        return false;
4400    }
4401
4402    @Override
4403    public int checkSignatures(String pkg1, String pkg2) {
4404        synchronized (mPackages) {
4405            final PackageParser.Package p1 = mPackages.get(pkg1);
4406            final PackageParser.Package p2 = mPackages.get(pkg2);
4407            if (p1 == null || p1.mExtras == null
4408                    || p2 == null || p2.mExtras == null) {
4409                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4410            }
4411            return compareSignatures(p1.mSignatures, p2.mSignatures);
4412        }
4413    }
4414
4415    @Override
4416    public int checkUidSignatures(int uid1, int uid2) {
4417        // Map to base uids.
4418        uid1 = UserHandle.getAppId(uid1);
4419        uid2 = UserHandle.getAppId(uid2);
4420        // reader
4421        synchronized (mPackages) {
4422            Signature[] s1;
4423            Signature[] s2;
4424            Object obj = mSettings.getUserIdLPr(uid1);
4425            if (obj != null) {
4426                if (obj instanceof SharedUserSetting) {
4427                    s1 = ((SharedUserSetting)obj).signatures.mSignatures;
4428                } else if (obj instanceof PackageSetting) {
4429                    s1 = ((PackageSetting)obj).signatures.mSignatures;
4430                } else {
4431                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4432                }
4433            } else {
4434                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4435            }
4436            obj = mSettings.getUserIdLPr(uid2);
4437            if (obj != null) {
4438                if (obj instanceof SharedUserSetting) {
4439                    s2 = ((SharedUserSetting)obj).signatures.mSignatures;
4440                } else if (obj instanceof PackageSetting) {
4441                    s2 = ((PackageSetting)obj).signatures.mSignatures;
4442                } else {
4443                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4444                }
4445            } else {
4446                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4447            }
4448            return compareSignatures(s1, s2);
4449        }
4450    }
4451
4452    /**
4453     * This method should typically only be used when granting or revoking
4454     * permissions, since the app may immediately restart after this call.
4455     * <p>
4456     * If you're doing surgery on app code/data, use {@link PackageFreezer} to
4457     * guard your work against the app being relaunched.
4458     */
4459    private void killUid(int appId, int userId, String reason) {
4460        final long identity = Binder.clearCallingIdentity();
4461        try {
4462            IActivityManager am = ActivityManagerNative.getDefault();
4463            if (am != null) {
4464                try {
4465                    am.killUid(appId, userId, reason);
4466                } catch (RemoteException e) {
4467                    /* ignore - same process */
4468                }
4469            }
4470        } finally {
4471            Binder.restoreCallingIdentity(identity);
4472        }
4473    }
4474
4475    /**
4476     * Compares two sets of signatures. Returns:
4477     * <br />
4478     * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null,
4479     * <br />
4480     * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null,
4481     * <br />
4482     * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null,
4483     * <br />
4484     * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical,
4485     * <br />
4486     * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ.
4487     */
4488    static int compareSignatures(Signature[] s1, Signature[] s2) {
4489        if (s1 == null) {
4490            return s2 == null
4491                    ? PackageManager.SIGNATURE_NEITHER_SIGNED
4492                    : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
4493        }
4494
4495        if (s2 == null) {
4496            return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
4497        }
4498
4499        if (s1.length != s2.length) {
4500            return PackageManager.SIGNATURE_NO_MATCH;
4501        }
4502
4503        // Since both signature sets are of size 1, we can compare without HashSets.
4504        if (s1.length == 1) {
4505            return s1[0].equals(s2[0]) ?
4506                    PackageManager.SIGNATURE_MATCH :
4507                    PackageManager.SIGNATURE_NO_MATCH;
4508        }
4509
4510        ArraySet<Signature> set1 = new ArraySet<Signature>();
4511        for (Signature sig : s1) {
4512            set1.add(sig);
4513        }
4514        ArraySet<Signature> set2 = new ArraySet<Signature>();
4515        for (Signature sig : s2) {
4516            set2.add(sig);
4517        }
4518        // Make sure s2 contains all signatures in s1.
4519        if (set1.equals(set2)) {
4520            return PackageManager.SIGNATURE_MATCH;
4521        }
4522        return PackageManager.SIGNATURE_NO_MATCH;
4523    }
4524
4525    /**
4526     * If the database version for this type of package (internal storage or
4527     * external storage) is less than the version where package signatures
4528     * were updated, return true.
4529     */
4530    private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
4531        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
4532        return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY;
4533    }
4534
4535    /**
4536     * Used for backward compatibility to make sure any packages with
4537     * certificate chains get upgraded to the new style. {@code existingSigs}
4538     * will be in the old format (since they were stored on disk from before the
4539     * system upgrade) and {@code scannedSigs} will be in the newer format.
4540     */
4541    private int compareSignaturesCompat(PackageSignatures existingSigs,
4542            PackageParser.Package scannedPkg) {
4543        if (!isCompatSignatureUpdateNeeded(scannedPkg)) {
4544            return PackageManager.SIGNATURE_NO_MATCH;
4545        }
4546
4547        ArraySet<Signature> existingSet = new ArraySet<Signature>();
4548        for (Signature sig : existingSigs.mSignatures) {
4549            existingSet.add(sig);
4550        }
4551        ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>();
4552        for (Signature sig : scannedPkg.mSignatures) {
4553            try {
4554                Signature[] chainSignatures = sig.getChainSignatures();
4555                for (Signature chainSig : chainSignatures) {
4556                    scannedCompatSet.add(chainSig);
4557                }
4558            } catch (CertificateEncodingException e) {
4559                scannedCompatSet.add(sig);
4560            }
4561        }
4562        /*
4563         * Make sure the expanded scanned set contains all signatures in the
4564         * existing one.
4565         */
4566        if (scannedCompatSet.equals(existingSet)) {
4567            // Migrate the old signatures to the new scheme.
4568            existingSigs.assignSignatures(scannedPkg.mSignatures);
4569            // The new KeySets will be re-added later in the scanning process.
4570            synchronized (mPackages) {
4571                mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName);
4572            }
4573            return PackageManager.SIGNATURE_MATCH;
4574        }
4575        return PackageManager.SIGNATURE_NO_MATCH;
4576    }
4577
4578    private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
4579        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
4580        return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER;
4581    }
4582
4583    private int compareSignaturesRecover(PackageSignatures existingSigs,
4584            PackageParser.Package scannedPkg) {
4585        if (!isRecoverSignatureUpdateNeeded(scannedPkg)) {
4586            return PackageManager.SIGNATURE_NO_MATCH;
4587        }
4588
4589        String msg = null;
4590        try {
4591            if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) {
4592                logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for "
4593                        + scannedPkg.packageName);
4594                return PackageManager.SIGNATURE_MATCH;
4595            }
4596        } catch (CertificateException e) {
4597            msg = e.getMessage();
4598        }
4599
4600        logCriticalInfo(Log.INFO,
4601                "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg);
4602        return PackageManager.SIGNATURE_NO_MATCH;
4603    }
4604
4605    @Override
4606    public List<String> getAllPackages() {
4607        synchronized (mPackages) {
4608            return new ArrayList<String>(mPackages.keySet());
4609        }
4610    }
4611
4612    @Override
4613    public String[] getPackagesForUid(int uid) {
4614        uid = UserHandle.getAppId(uid);
4615        // reader
4616        synchronized (mPackages) {
4617            Object obj = mSettings.getUserIdLPr(uid);
4618            if (obj instanceof SharedUserSetting) {
4619                final SharedUserSetting sus = (SharedUserSetting) obj;
4620                final int N = sus.packages.size();
4621                final String[] res = new String[N];
4622                final Iterator<PackageSetting> it = sus.packages.iterator();
4623                int i = 0;
4624                while (it.hasNext()) {
4625                    res[i++] = it.next().name;
4626                }
4627                return res;
4628            } else if (obj instanceof PackageSetting) {
4629                final PackageSetting ps = (PackageSetting) obj;
4630                return new String[] { ps.name };
4631            }
4632        }
4633        return null;
4634    }
4635
4636    @Override
4637    public String getNameForUid(int uid) {
4638        // reader
4639        synchronized (mPackages) {
4640            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4641            if (obj instanceof SharedUserSetting) {
4642                final SharedUserSetting sus = (SharedUserSetting) obj;
4643                return sus.name + ":" + sus.userId;
4644            } else if (obj instanceof PackageSetting) {
4645                final PackageSetting ps = (PackageSetting) obj;
4646                return ps.name;
4647            }
4648        }
4649        return null;
4650    }
4651
4652    @Override
4653    public int getUidForSharedUser(String sharedUserName) {
4654        if(sharedUserName == null) {
4655            return -1;
4656        }
4657        // reader
4658        synchronized (mPackages) {
4659            final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false);
4660            if (suid == null) {
4661                return -1;
4662            }
4663            return suid.userId;
4664        }
4665    }
4666
4667    @Override
4668    public int getFlagsForUid(int uid) {
4669        synchronized (mPackages) {
4670            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4671            if (obj instanceof SharedUserSetting) {
4672                final SharedUserSetting sus = (SharedUserSetting) obj;
4673                return sus.pkgFlags;
4674            } else if (obj instanceof PackageSetting) {
4675                final PackageSetting ps = (PackageSetting) obj;
4676                return ps.pkgFlags;
4677            }
4678        }
4679        return 0;
4680    }
4681
4682    @Override
4683    public int getPrivateFlagsForUid(int uid) {
4684        synchronized (mPackages) {
4685            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4686            if (obj instanceof SharedUserSetting) {
4687                final SharedUserSetting sus = (SharedUserSetting) obj;
4688                return sus.pkgPrivateFlags;
4689            } else if (obj instanceof PackageSetting) {
4690                final PackageSetting ps = (PackageSetting) obj;
4691                return ps.pkgPrivateFlags;
4692            }
4693        }
4694        return 0;
4695    }
4696
4697    @Override
4698    public boolean isUidPrivileged(int uid) {
4699        uid = UserHandle.getAppId(uid);
4700        // reader
4701        synchronized (mPackages) {
4702            Object obj = mSettings.getUserIdLPr(uid);
4703            if (obj instanceof SharedUserSetting) {
4704                final SharedUserSetting sus = (SharedUserSetting) obj;
4705                final Iterator<PackageSetting> it = sus.packages.iterator();
4706                while (it.hasNext()) {
4707                    if (it.next().isPrivileged()) {
4708                        return true;
4709                    }
4710                }
4711            } else if (obj instanceof PackageSetting) {
4712                final PackageSetting ps = (PackageSetting) obj;
4713                return ps.isPrivileged();
4714            }
4715        }
4716        return false;
4717    }
4718
4719    @Override
4720    public String[] getAppOpPermissionPackages(String permissionName) {
4721        synchronized (mPackages) {
4722            ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName);
4723            if (pkgs == null) {
4724                return null;
4725            }
4726            return pkgs.toArray(new String[pkgs.size()]);
4727        }
4728    }
4729
4730    @Override
4731    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
4732            int flags, int userId) {
4733        try {
4734            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveIntent");
4735
4736            if (!sUserManager.exists(userId)) return null;
4737            flags = updateFlagsForResolve(flags, userId, intent);
4738            enforceCrossUserPermission(Binder.getCallingUid(), userId,
4739                    false /*requireFullPermission*/, false /*checkShell*/, "resolve intent");
4740
4741            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
4742            final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType,
4743                    flags, userId);
4744            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
4745
4746            final ResolveInfo bestChoice =
4747                    chooseBestActivity(intent, resolvedType, flags, query, userId);
4748
4749            if (isEphemeralAllowed(intent, query, userId)) {
4750                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveEphemeral");
4751                final EphemeralResolveInfo ai =
4752                        getEphemeralResolveInfo(intent, resolvedType, userId);
4753                if (ai != null) {
4754                    if (DEBUG_EPHEMERAL) {
4755                        Slog.v(TAG, "Returning an EphemeralResolveInfo");
4756                    }
4757                    bestChoice.ephemeralInstaller = mEphemeralInstallerInfo;
4758                    bestChoice.ephemeralResolveInfo = ai;
4759                }
4760                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
4761            }
4762            return bestChoice;
4763        } finally {
4764            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
4765        }
4766    }
4767
4768    @Override
4769    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
4770            IntentFilter filter, int match, ComponentName activity) {
4771        final int userId = UserHandle.getCallingUserId();
4772        if (DEBUG_PREFERRED) {
4773            Log.v(TAG, "setLastChosenActivity intent=" + intent
4774                + " resolvedType=" + resolvedType
4775                + " flags=" + flags
4776                + " filter=" + filter
4777                + " match=" + match
4778                + " activity=" + activity);
4779            filter.dump(new PrintStreamPrinter(System.out), "    ");
4780        }
4781        intent.setComponent(null);
4782        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
4783                userId);
4784        // Find any earlier preferred or last chosen entries and nuke them
4785        findPreferredActivity(intent, resolvedType,
4786                flags, query, 0, false, true, false, userId);
4787        // Add the new activity as the last chosen for this filter
4788        addPreferredActivityInternal(filter, match, null, activity, false, userId,
4789                "Setting last chosen");
4790    }
4791
4792    @Override
4793    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
4794        final int userId = UserHandle.getCallingUserId();
4795        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
4796        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
4797                userId);
4798        return findPreferredActivity(intent, resolvedType, flags, query, 0,
4799                false, false, false, userId);
4800    }
4801
4802
4803    private boolean isEphemeralAllowed(
4804            Intent intent, List<ResolveInfo> resolvedActivites, int userId) {
4805        // Short circuit and return early if possible.
4806        if (DISABLE_EPHEMERAL_APPS) {
4807            return false;
4808        }
4809        final int callingUser = UserHandle.getCallingUserId();
4810        if (callingUser != UserHandle.USER_SYSTEM) {
4811            return false;
4812        }
4813        if (mEphemeralResolverConnection == null) {
4814            return false;
4815        }
4816        if (intent.getComponent() != null) {
4817            return false;
4818        }
4819        if (intent.getPackage() != null) {
4820            return false;
4821        }
4822        final boolean isWebUri = hasWebURI(intent);
4823        if (!isWebUri) {
4824            return false;
4825        }
4826        // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution.
4827        synchronized (mPackages) {
4828            final int count = resolvedActivites.size();
4829            for (int n = 0; n < count; n++) {
4830                ResolveInfo info = resolvedActivites.get(n);
4831                String packageName = info.activityInfo.packageName;
4832                PackageSetting ps = mSettings.mPackages.get(packageName);
4833                if (ps != null) {
4834                    // Try to get the status from User settings first
4835                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
4836                    int status = (int) (packedStatus >> 32);
4837                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS
4838                            || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
4839                        if (DEBUG_EPHEMERAL) {
4840                            Slog.v(TAG, "DENY ephemeral apps;"
4841                                + " pkg: " + packageName + ", status: " + status);
4842                        }
4843                        return false;
4844                    }
4845                }
4846            }
4847        }
4848        // We've exhausted all ways to deny ephemeral application; let the system look for them.
4849        return true;
4850    }
4851
4852    private EphemeralResolveInfo getEphemeralResolveInfo(Intent intent, String resolvedType,
4853            int userId) {
4854        MessageDigest digest = null;
4855        try {
4856            digest = MessageDigest.getInstance(EphemeralResolveInfo.SHA_ALGORITHM);
4857        } catch (NoSuchAlgorithmException e) {
4858            // If we can't create a digest, ignore ephemeral apps.
4859            return null;
4860        }
4861
4862        final byte[] hostBytes = intent.getData().getHost().getBytes();
4863        final byte[] digestBytes = digest.digest(hostBytes);
4864        int shaPrefix =
4865                digestBytes[0] << 24
4866                | digestBytes[1] << 16
4867                | digestBytes[2] << 8
4868                | digestBytes[3] << 0;
4869        final List<EphemeralResolveInfo> ephemeralResolveInfoList =
4870                mEphemeralResolverConnection.getEphemeralResolveInfoList(shaPrefix);
4871        if (ephemeralResolveInfoList == null || ephemeralResolveInfoList.size() == 0) {
4872            // No hash prefix match; there are no ephemeral apps for this domain.
4873            return null;
4874        }
4875        for (int i = ephemeralResolveInfoList.size() - 1; i >= 0; --i) {
4876            EphemeralResolveInfo ephemeralApplication = ephemeralResolveInfoList.get(i);
4877            if (!Arrays.equals(digestBytes, ephemeralApplication.getDigestBytes())) {
4878                continue;
4879            }
4880            final List<IntentFilter> filters = ephemeralApplication.getFilters();
4881            // No filters; this should never happen.
4882            if (filters.isEmpty()) {
4883                continue;
4884            }
4885            // We have a domain match; resolve the filters to see if anything matches.
4886            final EphemeralIntentResolver ephemeralResolver = new EphemeralIntentResolver();
4887            for (int j = filters.size() - 1; j >= 0; --j) {
4888                final EphemeralResolveIntentInfo intentInfo =
4889                        new EphemeralResolveIntentInfo(filters.get(j), ephemeralApplication);
4890                ephemeralResolver.addFilter(intentInfo);
4891            }
4892            List<EphemeralResolveInfo> matchedResolveInfoList = ephemeralResolver.queryIntent(
4893                    intent, resolvedType, false /*defaultOnly*/, userId);
4894            if (!matchedResolveInfoList.isEmpty()) {
4895                return matchedResolveInfoList.get(0);
4896            }
4897        }
4898        // Hash or filter mis-match; no ephemeral apps for this domain.
4899        return null;
4900    }
4901
4902    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
4903            int flags, List<ResolveInfo> query, int userId) {
4904        if (query != null) {
4905            final int N = query.size();
4906            if (N == 1) {
4907                return query.get(0);
4908            } else if (N > 1) {
4909                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
4910                // If there is more than one activity with the same priority,
4911                // then let the user decide between them.
4912                ResolveInfo r0 = query.get(0);
4913                ResolveInfo r1 = query.get(1);
4914                if (DEBUG_INTENT_MATCHING || debug) {
4915                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
4916                            + r1.activityInfo.name + "=" + r1.priority);
4917                }
4918                // If the first activity has a higher priority, or a different
4919                // default, then it is always desirable to pick it.
4920                if (r0.priority != r1.priority
4921                        || r0.preferredOrder != r1.preferredOrder
4922                        || r0.isDefault != r1.isDefault) {
4923                    return query.get(0);
4924                }
4925                // If we have saved a preference for a preferred activity for
4926                // this Intent, use that.
4927                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
4928                        flags, query, r0.priority, true, false, debug, userId);
4929                if (ri != null) {
4930                    return ri;
4931                }
4932                ri = new ResolveInfo(mResolveInfo);
4933                ri.activityInfo = new ActivityInfo(ri.activityInfo);
4934                ri.activityInfo.labelRes = ResolverActivity.getLabelRes(intent.getAction());
4935                ri.activityInfo.applicationInfo = new ApplicationInfo(
4936                        ri.activityInfo.applicationInfo);
4937                if (userId != 0) {
4938                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
4939                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
4940                }
4941                // Make sure that the resolver is displayable in car mode
4942                if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle();
4943                ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true);
4944                return ri;
4945            }
4946        }
4947        return null;
4948    }
4949
4950    private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
4951            int flags, List<ResolveInfo> query, boolean debug, int userId) {
4952        final int N = query.size();
4953        PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
4954                .get(userId);
4955        // Get the list of persistent preferred activities that handle the intent
4956        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
4957        List<PersistentPreferredActivity> pprefs = ppir != null
4958                ? ppir.queryIntent(intent, resolvedType,
4959                        (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
4960                : null;
4961        if (pprefs != null && pprefs.size() > 0) {
4962            final int M = pprefs.size();
4963            for (int i=0; i<M; i++) {
4964                final PersistentPreferredActivity ppa = pprefs.get(i);
4965                if (DEBUG_PREFERRED || debug) {
4966                    Slog.v(TAG, "Checking PersistentPreferredActivity ds="
4967                            + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
4968                            + "\n  component=" + ppa.mComponent);
4969                    ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4970                }
4971                final ActivityInfo ai = getActivityInfo(ppa.mComponent,
4972                        flags | MATCH_DISABLED_COMPONENTS, userId);
4973                if (DEBUG_PREFERRED || debug) {
4974                    Slog.v(TAG, "Found persistent preferred activity:");
4975                    if (ai != null) {
4976                        ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4977                    } else {
4978                        Slog.v(TAG, "  null");
4979                    }
4980                }
4981                if (ai == null) {
4982                    // This previously registered persistent preferred activity
4983                    // component is no longer known. Ignore it and do NOT remove it.
4984                    continue;
4985                }
4986                for (int j=0; j<N; j++) {
4987                    final ResolveInfo ri = query.get(j);
4988                    if (!ri.activityInfo.applicationInfo.packageName
4989                            .equals(ai.applicationInfo.packageName)) {
4990                        continue;
4991                    }
4992                    if (!ri.activityInfo.name.equals(ai.name)) {
4993                        continue;
4994                    }
4995                    //  Found a persistent preference that can handle the intent.
4996                    if (DEBUG_PREFERRED || debug) {
4997                        Slog.v(TAG, "Returning persistent preferred activity: " +
4998                                ri.activityInfo.packageName + "/" + ri.activityInfo.name);
4999                    }
5000                    return ri;
5001                }
5002            }
5003        }
5004        return null;
5005    }
5006
5007    // TODO: handle preferred activities missing while user has amnesia
5008    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
5009            List<ResolveInfo> query, int priority, boolean always,
5010            boolean removeMatches, boolean debug, int userId) {
5011        if (!sUserManager.exists(userId)) return null;
5012        flags = updateFlagsForResolve(flags, userId, intent);
5013        // writer
5014        synchronized (mPackages) {
5015            if (intent.getSelector() != null) {
5016                intent = intent.getSelector();
5017            }
5018            if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
5019
5020            // Try to find a matching persistent preferred activity.
5021            ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
5022                    debug, userId);
5023
5024            // If a persistent preferred activity matched, use it.
5025            if (pri != null) {
5026                return pri;
5027            }
5028
5029            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
5030            // Get the list of preferred activities that handle the intent
5031            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
5032            List<PreferredActivity> prefs = pir != null
5033                    ? pir.queryIntent(intent, resolvedType,
5034                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
5035                    : null;
5036            if (prefs != null && prefs.size() > 0) {
5037                boolean changed = false;
5038                try {
5039                    // First figure out how good the original match set is.
5040                    // We will only allow preferred activities that came
5041                    // from the same match quality.
5042                    int match = 0;
5043
5044                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
5045
5046                    final int N = query.size();
5047                    for (int j=0; j<N; j++) {
5048                        final ResolveInfo ri = query.get(j);
5049                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
5050                                + ": 0x" + Integer.toHexString(match));
5051                        if (ri.match > match) {
5052                            match = ri.match;
5053                        }
5054                    }
5055
5056                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
5057                            + Integer.toHexString(match));
5058
5059                    match &= IntentFilter.MATCH_CATEGORY_MASK;
5060                    final int M = prefs.size();
5061                    for (int i=0; i<M; i++) {
5062                        final PreferredActivity pa = prefs.get(i);
5063                        if (DEBUG_PREFERRED || debug) {
5064                            Slog.v(TAG, "Checking PreferredActivity ds="
5065                                    + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
5066                                    + "\n  component=" + pa.mPref.mComponent);
5067                            pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
5068                        }
5069                        if (pa.mPref.mMatch != match) {
5070                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
5071                                    + Integer.toHexString(pa.mPref.mMatch));
5072                            continue;
5073                        }
5074                        // If it's not an "always" type preferred activity and that's what we're
5075                        // looking for, skip it.
5076                        if (always && !pa.mPref.mAlways) {
5077                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
5078                            continue;
5079                        }
5080                        final ActivityInfo ai = getActivityInfo(
5081                                pa.mPref.mComponent, flags | MATCH_DISABLED_COMPONENTS
5082                                        | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
5083                                userId);
5084                        if (DEBUG_PREFERRED || debug) {
5085                            Slog.v(TAG, "Found preferred activity:");
5086                            if (ai != null) {
5087                                ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
5088                            } else {
5089                                Slog.v(TAG, "  null");
5090                            }
5091                        }
5092                        if (ai == null) {
5093                            // This previously registered preferred activity
5094                            // component is no longer known.  Most likely an update
5095                            // to the app was installed and in the new version this
5096                            // component no longer exists.  Clean it up by removing
5097                            // it from the preferred activities list, and skip it.
5098                            Slog.w(TAG, "Removing dangling preferred activity: "
5099                                    + pa.mPref.mComponent);
5100                            pir.removeFilter(pa);
5101                            changed = true;
5102                            continue;
5103                        }
5104                        for (int j=0; j<N; j++) {
5105                            final ResolveInfo ri = query.get(j);
5106                            if (!ri.activityInfo.applicationInfo.packageName
5107                                    .equals(ai.applicationInfo.packageName)) {
5108                                continue;
5109                            }
5110                            if (!ri.activityInfo.name.equals(ai.name)) {
5111                                continue;
5112                            }
5113
5114                            if (removeMatches) {
5115                                pir.removeFilter(pa);
5116                                changed = true;
5117                                if (DEBUG_PREFERRED) {
5118                                    Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
5119                                }
5120                                break;
5121                            }
5122
5123                            // Okay we found a previously set preferred or last chosen app.
5124                            // If the result set is different from when this
5125                            // was created, we need to clear it and re-ask the
5126                            // user their preference, if we're looking for an "always" type entry.
5127                            if (always && !pa.mPref.sameSet(query)) {
5128                                Slog.i(TAG, "Result set changed, dropping preferred activity for "
5129                                        + intent + " type " + resolvedType);
5130                                if (DEBUG_PREFERRED) {
5131                                    Slog.v(TAG, "Removing preferred activity since set changed "
5132                                            + pa.mPref.mComponent);
5133                                }
5134                                pir.removeFilter(pa);
5135                                // Re-add the filter as a "last chosen" entry (!always)
5136                                PreferredActivity lastChosen = new PreferredActivity(
5137                                        pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
5138                                pir.addFilter(lastChosen);
5139                                changed = true;
5140                                return null;
5141                            }
5142
5143                            // Yay! Either the set matched or we're looking for the last chosen
5144                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
5145                                    + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
5146                            return ri;
5147                        }
5148                    }
5149                } finally {
5150                    if (changed) {
5151                        if (DEBUG_PREFERRED) {
5152                            Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions");
5153                        }
5154                        scheduleWritePackageRestrictionsLocked(userId);
5155                    }
5156                }
5157            }
5158        }
5159        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
5160        return null;
5161    }
5162
5163    /*
5164     * Returns if intent can be forwarded from the sourceUserId to the targetUserId
5165     */
5166    @Override
5167    public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
5168            int targetUserId) {
5169        mContext.enforceCallingOrSelfPermission(
5170                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
5171        List<CrossProfileIntentFilter> matches =
5172                getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
5173        if (matches != null) {
5174            int size = matches.size();
5175            for (int i = 0; i < size; i++) {
5176                if (matches.get(i).getTargetUserId() == targetUserId) return true;
5177            }
5178        }
5179        if (hasWebURI(intent)) {
5180            // cross-profile app linking works only towards the parent.
5181            final UserInfo parent = getProfileParent(sourceUserId);
5182            synchronized(mPackages) {
5183                int flags = updateFlagsForResolve(0, parent.id, intent);
5184                CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr(
5185                        intent, resolvedType, flags, sourceUserId, parent.id);
5186                return xpDomainInfo != null;
5187            }
5188        }
5189        return false;
5190    }
5191
5192    private UserInfo getProfileParent(int userId) {
5193        final long identity = Binder.clearCallingIdentity();
5194        try {
5195            return sUserManager.getProfileParent(userId);
5196        } finally {
5197            Binder.restoreCallingIdentity(identity);
5198        }
5199    }
5200
5201    private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
5202            String resolvedType, int userId) {
5203        CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
5204        if (resolver != null) {
5205            return resolver.queryIntent(intent, resolvedType, false, userId);
5206        }
5207        return null;
5208    }
5209
5210    @Override
5211    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivities(Intent intent,
5212            String resolvedType, int flags, int userId) {
5213        try {
5214            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
5215
5216            return new ParceledListSlice<>(
5217                    queryIntentActivitiesInternal(intent, resolvedType, flags, userId));
5218        } finally {
5219            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
5220        }
5221    }
5222
5223    private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent,
5224            String resolvedType, int flags, int userId) {
5225        if (!sUserManager.exists(userId)) return Collections.emptyList();
5226        flags = updateFlagsForResolve(flags, userId, intent);
5227        enforceCrossUserPermission(Binder.getCallingUid(), userId,
5228                false /* requireFullPermission */, false /* checkShell */,
5229                "query intent activities");
5230        ComponentName comp = intent.getComponent();
5231        if (comp == null) {
5232            if (intent.getSelector() != null) {
5233                intent = intent.getSelector();
5234                comp = intent.getComponent();
5235            }
5236        }
5237
5238        if (comp != null) {
5239            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5240            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
5241            if (ai != null) {
5242                final ResolveInfo ri = new ResolveInfo();
5243                ri.activityInfo = ai;
5244                list.add(ri);
5245            }
5246            return list;
5247        }
5248
5249        // reader
5250        synchronized (mPackages) {
5251            final String pkgName = intent.getPackage();
5252            if (pkgName == null) {
5253                List<CrossProfileIntentFilter> matchingFilters =
5254                        getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
5255                // Check for results that need to skip the current profile.
5256                ResolveInfo xpResolveInfo  = querySkipCurrentProfileIntents(matchingFilters, intent,
5257                        resolvedType, flags, userId);
5258                if (xpResolveInfo != null) {
5259                    List<ResolveInfo> result = new ArrayList<ResolveInfo>(1);
5260                    result.add(xpResolveInfo);
5261                    return filterIfNotSystemUser(result, userId);
5262                }
5263
5264                // Check for results in the current profile.
5265                List<ResolveInfo> result = mActivities.queryIntent(
5266                        intent, resolvedType, flags, userId);
5267                result = filterIfNotSystemUser(result, userId);
5268
5269                // Check for cross profile results.
5270                boolean hasNonNegativePriorityResult = hasNonNegativePriority(result);
5271                xpResolveInfo = queryCrossProfileIntents(
5272                        matchingFilters, intent, resolvedType, flags, userId,
5273                        hasNonNegativePriorityResult);
5274                if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
5275                    boolean isVisibleToUser = filterIfNotSystemUser(
5276                            Collections.singletonList(xpResolveInfo), userId).size() > 0;
5277                    if (isVisibleToUser) {
5278                        result.add(xpResolveInfo);
5279                        Collections.sort(result, mResolvePrioritySorter);
5280                    }
5281                }
5282                if (hasWebURI(intent)) {
5283                    CrossProfileDomainInfo xpDomainInfo = null;
5284                    final UserInfo parent = getProfileParent(userId);
5285                    if (parent != null) {
5286                        xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType,
5287                                flags, userId, parent.id);
5288                    }
5289                    if (xpDomainInfo != null) {
5290                        if (xpResolveInfo != null) {
5291                            // If we didn't remove it, the cross-profile ResolveInfo would be twice
5292                            // in the result.
5293                            result.remove(xpResolveInfo);
5294                        }
5295                        if (result.size() == 0) {
5296                            result.add(xpDomainInfo.resolveInfo);
5297                            return result;
5298                        }
5299                    } else if (result.size() <= 1) {
5300                        return result;
5301                    }
5302                    result = filterCandidatesWithDomainPreferredActivitiesLPr(intent, flags, result,
5303                            xpDomainInfo, userId);
5304                    Collections.sort(result, mResolvePrioritySorter);
5305                }
5306                return result;
5307            }
5308            final PackageParser.Package pkg = mPackages.get(pkgName);
5309            if (pkg != null) {
5310                return filterIfNotSystemUser(
5311                        mActivities.queryIntentForPackage(
5312                                intent, resolvedType, flags, pkg.activities, userId),
5313                        userId);
5314            }
5315            return new ArrayList<ResolveInfo>();
5316        }
5317    }
5318
5319    private static class CrossProfileDomainInfo {
5320        /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */
5321        ResolveInfo resolveInfo;
5322        /* Best domain verification status of the activities found in the other profile */
5323        int bestDomainVerificationStatus;
5324    }
5325
5326    private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent,
5327            String resolvedType, int flags, int sourceUserId, int parentUserId) {
5328        if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING,
5329                sourceUserId)) {
5330            return null;
5331        }
5332        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
5333                resolvedType, flags, parentUserId);
5334
5335        if (resultTargetUser == null || resultTargetUser.isEmpty()) {
5336            return null;
5337        }
5338        CrossProfileDomainInfo result = null;
5339        int size = resultTargetUser.size();
5340        for (int i = 0; i < size; i++) {
5341            ResolveInfo riTargetUser = resultTargetUser.get(i);
5342            // Intent filter verification is only for filters that specify a host. So don't return
5343            // those that handle all web uris.
5344            if (riTargetUser.handleAllWebDataURI) {
5345                continue;
5346            }
5347            String packageName = riTargetUser.activityInfo.packageName;
5348            PackageSetting ps = mSettings.mPackages.get(packageName);
5349            if (ps == null) {
5350                continue;
5351            }
5352            long verificationState = getDomainVerificationStatusLPr(ps, parentUserId);
5353            int status = (int)(verificationState >> 32);
5354            if (result == null) {
5355                result = new CrossProfileDomainInfo();
5356                result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(),
5357                        sourceUserId, parentUserId);
5358                result.bestDomainVerificationStatus = status;
5359            } else {
5360                result.bestDomainVerificationStatus = bestDomainVerificationStatus(status,
5361                        result.bestDomainVerificationStatus);
5362            }
5363        }
5364        // Don't consider matches with status NEVER across profiles.
5365        if (result != null && result.bestDomainVerificationStatus
5366                == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5367            return null;
5368        }
5369        return result;
5370    }
5371
5372    /**
5373     * Verification statuses are ordered from the worse to the best, except for
5374     * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse.
5375     */
5376    private int bestDomainVerificationStatus(int status1, int status2) {
5377        if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5378            return status2;
5379        }
5380        if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5381            return status1;
5382        }
5383        return (int) MathUtils.max(status1, status2);
5384    }
5385
5386    private boolean isUserEnabled(int userId) {
5387        long callingId = Binder.clearCallingIdentity();
5388        try {
5389            UserInfo userInfo = sUserManager.getUserInfo(userId);
5390            return userInfo != null && userInfo.isEnabled();
5391        } finally {
5392            Binder.restoreCallingIdentity(callingId);
5393        }
5394    }
5395
5396    /**
5397     * Filter out activities with systemUserOnly flag set, when current user is not System.
5398     *
5399     * @return filtered list
5400     */
5401    private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) {
5402        if (userId == UserHandle.USER_SYSTEM) {
5403            return resolveInfos;
5404        }
5405        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
5406            ResolveInfo info = resolveInfos.get(i);
5407            if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) {
5408                resolveInfos.remove(i);
5409            }
5410        }
5411        return resolveInfos;
5412    }
5413
5414    /**
5415     * @param resolveInfos list of resolve infos in descending priority order
5416     * @return if the list contains a resolve info with non-negative priority
5417     */
5418    private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) {
5419        return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0;
5420    }
5421
5422    private static boolean hasWebURI(Intent intent) {
5423        if (intent.getData() == null) {
5424            return false;
5425        }
5426        final String scheme = intent.getScheme();
5427        if (TextUtils.isEmpty(scheme)) {
5428            return false;
5429        }
5430        return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS);
5431    }
5432
5433    private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent,
5434            int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo,
5435            int userId) {
5436        final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0;
5437
5438        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
5439            Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " +
5440                    candidates.size());
5441        }
5442
5443        ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>();
5444        ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>();
5445        ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>();
5446        ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>();
5447        ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>();
5448        ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>();
5449
5450        synchronized (mPackages) {
5451            final int count = candidates.size();
5452            // First, try to use linked apps. Partition the candidates into four lists:
5453            // one for the final results, one for the "do not use ever", one for "undefined status"
5454            // and finally one for "browser app type".
5455            for (int n=0; n<count; n++) {
5456                ResolveInfo info = candidates.get(n);
5457                String packageName = info.activityInfo.packageName;
5458                PackageSetting ps = mSettings.mPackages.get(packageName);
5459                if (ps != null) {
5460                    // Add to the special match all list (Browser use case)
5461                    if (info.handleAllWebDataURI) {
5462                        matchAllList.add(info);
5463                        continue;
5464                    }
5465                    // Try to get the status from User settings first
5466                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
5467                    int status = (int)(packedStatus >> 32);
5468                    int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
5469                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
5470                        if (DEBUG_DOMAIN_VERIFICATION) {
5471                            Slog.i(TAG, "  + always: " + info.activityInfo.packageName
5472                                    + " : linkgen=" + linkGeneration);
5473                        }
5474                        // Use link-enabled generation as preferredOrder, i.e.
5475                        // prefer newly-enabled over earlier-enabled.
5476                        info.preferredOrder = linkGeneration;
5477                        alwaysList.add(info);
5478                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5479                        if (DEBUG_DOMAIN_VERIFICATION) {
5480                            Slog.i(TAG, "  + never: " + info.activityInfo.packageName);
5481                        }
5482                        neverList.add(info);
5483                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
5484                        if (DEBUG_DOMAIN_VERIFICATION) {
5485                            Slog.i(TAG, "  + always-ask: " + info.activityInfo.packageName);
5486                        }
5487                        alwaysAskList.add(info);
5488                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED ||
5489                            status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) {
5490                        if (DEBUG_DOMAIN_VERIFICATION) {
5491                            Slog.i(TAG, "  + ask: " + info.activityInfo.packageName);
5492                        }
5493                        undefinedList.add(info);
5494                    }
5495                }
5496            }
5497
5498            // We'll want to include browser possibilities in a few cases
5499            boolean includeBrowser = false;
5500
5501            // First try to add the "always" resolution(s) for the current user, if any
5502            if (alwaysList.size() > 0) {
5503                result.addAll(alwaysList);
5504            } else {
5505                // Add all undefined apps as we want them to appear in the disambiguation dialog.
5506                result.addAll(undefinedList);
5507                // Maybe add one for the other profile.
5508                if (xpDomainInfo != null && (
5509                        xpDomainInfo.bestDomainVerificationStatus
5510                        != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) {
5511                    result.add(xpDomainInfo.resolveInfo);
5512                }
5513                includeBrowser = true;
5514            }
5515
5516            // The presence of any 'always ask' alternatives means we'll also offer browsers.
5517            // If there were 'always' entries their preferred order has been set, so we also
5518            // back that off to make the alternatives equivalent
5519            if (alwaysAskList.size() > 0) {
5520                for (ResolveInfo i : result) {
5521                    i.preferredOrder = 0;
5522                }
5523                result.addAll(alwaysAskList);
5524                includeBrowser = true;
5525            }
5526
5527            if (includeBrowser) {
5528                // Also add browsers (all of them or only the default one)
5529                if (DEBUG_DOMAIN_VERIFICATION) {
5530                    Slog.v(TAG, "   ...including browsers in candidate set");
5531                }
5532                if ((matchFlags & MATCH_ALL) != 0) {
5533                    result.addAll(matchAllList);
5534                } else {
5535                    // Browser/generic handling case.  If there's a default browser, go straight
5536                    // to that (but only if there is no other higher-priority match).
5537                    final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
5538                    int maxMatchPrio = 0;
5539                    ResolveInfo defaultBrowserMatch = null;
5540                    final int numCandidates = matchAllList.size();
5541                    for (int n = 0; n < numCandidates; n++) {
5542                        ResolveInfo info = matchAllList.get(n);
5543                        // track the highest overall match priority...
5544                        if (info.priority > maxMatchPrio) {
5545                            maxMatchPrio = info.priority;
5546                        }
5547                        // ...and the highest-priority default browser match
5548                        if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) {
5549                            if (defaultBrowserMatch == null
5550                                    || (defaultBrowserMatch.priority < info.priority)) {
5551                                if (debug) {
5552                                    Slog.v(TAG, "Considering default browser match " + info);
5553                                }
5554                                defaultBrowserMatch = info;
5555                            }
5556                        }
5557                    }
5558                    if (defaultBrowserMatch != null
5559                            && defaultBrowserMatch.priority >= maxMatchPrio
5560                            && !TextUtils.isEmpty(defaultBrowserPackageName))
5561                    {
5562                        if (debug) {
5563                            Slog.v(TAG, "Default browser match " + defaultBrowserMatch);
5564                        }
5565                        result.add(defaultBrowserMatch);
5566                    } else {
5567                        result.addAll(matchAllList);
5568                    }
5569                }
5570
5571                // If there is nothing selected, add all candidates and remove the ones that the user
5572                // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state
5573                if (result.size() == 0) {
5574                    result.addAll(candidates);
5575                    result.removeAll(neverList);
5576                }
5577            }
5578        }
5579        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
5580            Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " +
5581                    result.size());
5582            for (ResolveInfo info : result) {
5583                Slog.v(TAG, "  + " + info.activityInfo);
5584            }
5585        }
5586        return result;
5587    }
5588
5589    // Returns a packed value as a long:
5590    //
5591    // high 'int'-sized word: link status: undefined/ask/never/always.
5592    // low 'int'-sized word: relative priority among 'always' results.
5593    private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) {
5594        long result = ps.getDomainVerificationStatusForUser(userId);
5595        // if none available, get the master status
5596        if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
5597            if (ps.getIntentFilterVerificationInfo() != null) {
5598                result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32;
5599            }
5600        }
5601        return result;
5602    }
5603
5604    private ResolveInfo querySkipCurrentProfileIntents(
5605            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
5606            int flags, int sourceUserId) {
5607        if (matchingFilters != null) {
5608            int size = matchingFilters.size();
5609            for (int i = 0; i < size; i ++) {
5610                CrossProfileIntentFilter filter = matchingFilters.get(i);
5611                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
5612                    // Checking if there are activities in the target user that can handle the
5613                    // intent.
5614                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
5615                            resolvedType, flags, sourceUserId);
5616                    if (resolveInfo != null) {
5617                        return resolveInfo;
5618                    }
5619                }
5620            }
5621        }
5622        return null;
5623    }
5624
5625    // Return matching ResolveInfo in target user if any.
5626    private ResolveInfo queryCrossProfileIntents(
5627            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
5628            int flags, int sourceUserId, boolean matchInCurrentProfile) {
5629        if (matchingFilters != null) {
5630            // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
5631            // match the same intent. For performance reasons, it is better not to
5632            // run queryIntent twice for the same userId
5633            SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
5634            int size = matchingFilters.size();
5635            for (int i = 0; i < size; i++) {
5636                CrossProfileIntentFilter filter = matchingFilters.get(i);
5637                int targetUserId = filter.getTargetUserId();
5638                boolean skipCurrentProfile =
5639                        (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0;
5640                boolean skipCurrentProfileIfNoMatchFound =
5641                        (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0;
5642                if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId)
5643                        && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) {
5644                    // Checking if there are activities in the target user that can handle the
5645                    // intent.
5646                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
5647                            resolvedType, flags, sourceUserId);
5648                    if (resolveInfo != null) return resolveInfo;
5649                    alreadyTriedUserIds.put(targetUserId, true);
5650                }
5651            }
5652        }
5653        return null;
5654    }
5655
5656    /**
5657     * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that
5658     * will forward the intent to the filter's target user.
5659     * Otherwise, returns null.
5660     */
5661    private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent,
5662            String resolvedType, int flags, int sourceUserId) {
5663        int targetUserId = filter.getTargetUserId();
5664        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
5665                resolvedType, flags, targetUserId);
5666        if (resultTargetUser != null && isUserEnabled(targetUserId)) {
5667            // If all the matches in the target profile are suspended, return null.
5668            for (int i = resultTargetUser.size() - 1; i >= 0; i--) {
5669                if ((resultTargetUser.get(i).activityInfo.applicationInfo.flags
5670                        & ApplicationInfo.FLAG_SUSPENDED) == 0) {
5671                    return createForwardingResolveInfoUnchecked(filter, sourceUserId,
5672                            targetUserId);
5673                }
5674            }
5675        }
5676        return null;
5677    }
5678
5679    private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter,
5680            int sourceUserId, int targetUserId) {
5681        ResolveInfo forwardingResolveInfo = new ResolveInfo();
5682        long ident = Binder.clearCallingIdentity();
5683        boolean targetIsProfile;
5684        try {
5685            targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile();
5686        } finally {
5687            Binder.restoreCallingIdentity(ident);
5688        }
5689        String className;
5690        if (targetIsProfile) {
5691            className = FORWARD_INTENT_TO_MANAGED_PROFILE;
5692        } else {
5693            className = FORWARD_INTENT_TO_PARENT;
5694        }
5695        ComponentName forwardingActivityComponentName = new ComponentName(
5696                mAndroidApplication.packageName, className);
5697        ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
5698                sourceUserId);
5699        if (!targetIsProfile) {
5700            forwardingActivityInfo.showUserIcon = targetUserId;
5701            forwardingResolveInfo.noResourceId = true;
5702        }
5703        forwardingResolveInfo.activityInfo = forwardingActivityInfo;
5704        forwardingResolveInfo.priority = 0;
5705        forwardingResolveInfo.preferredOrder = 0;
5706        forwardingResolveInfo.match = 0;
5707        forwardingResolveInfo.isDefault = true;
5708        forwardingResolveInfo.filter = filter;
5709        forwardingResolveInfo.targetUserId = targetUserId;
5710        return forwardingResolveInfo;
5711    }
5712
5713    @Override
5714    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
5715            Intent[] specifics, String[] specificTypes, Intent intent,
5716            String resolvedType, int flags, int userId) {
5717        return new ParceledListSlice<>(queryIntentActivityOptionsInternal(caller, specifics,
5718                specificTypes, intent, resolvedType, flags, userId));
5719    }
5720
5721    private @NonNull List<ResolveInfo> queryIntentActivityOptionsInternal(ComponentName caller,
5722            Intent[] specifics, String[] specificTypes, Intent intent,
5723            String resolvedType, int flags, int userId) {
5724        if (!sUserManager.exists(userId)) return Collections.emptyList();
5725        flags = updateFlagsForResolve(flags, userId, intent);
5726        enforceCrossUserPermission(Binder.getCallingUid(), userId,
5727                false /* requireFullPermission */, false /* checkShell */,
5728                "query intent activity options");
5729        final String resultsAction = intent.getAction();
5730
5731        final List<ResolveInfo> results = queryIntentActivitiesInternal(intent, resolvedType, flags
5732                | PackageManager.GET_RESOLVED_FILTER, userId);
5733
5734        if (DEBUG_INTENT_MATCHING) {
5735            Log.v(TAG, "Query " + intent + ": " + results);
5736        }
5737
5738        int specificsPos = 0;
5739        int N;
5740
5741        // todo: note that the algorithm used here is O(N^2).  This
5742        // isn't a problem in our current environment, but if we start running
5743        // into situations where we have more than 5 or 10 matches then this
5744        // should probably be changed to something smarter...
5745
5746        // First we go through and resolve each of the specific items
5747        // that were supplied, taking care of removing any corresponding
5748        // duplicate items in the generic resolve list.
5749        if (specifics != null) {
5750            for (int i=0; i<specifics.length; i++) {
5751                final Intent sintent = specifics[i];
5752                if (sintent == null) {
5753                    continue;
5754                }
5755
5756                if (DEBUG_INTENT_MATCHING) {
5757                    Log.v(TAG, "Specific #" + i + ": " + sintent);
5758                }
5759
5760                String action = sintent.getAction();
5761                if (resultsAction != null && resultsAction.equals(action)) {
5762                    // If this action was explicitly requested, then don't
5763                    // remove things that have it.
5764                    action = null;
5765                }
5766
5767                ResolveInfo ri = null;
5768                ActivityInfo ai = null;
5769
5770                ComponentName comp = sintent.getComponent();
5771                if (comp == null) {
5772                    ri = resolveIntent(
5773                        sintent,
5774                        specificTypes != null ? specificTypes[i] : null,
5775                            flags, userId);
5776                    if (ri == null) {
5777                        continue;
5778                    }
5779                    if (ri == mResolveInfo) {
5780                        // ACK!  Must do something better with this.
5781                    }
5782                    ai = ri.activityInfo;
5783                    comp = new ComponentName(ai.applicationInfo.packageName,
5784                            ai.name);
5785                } else {
5786                    ai = getActivityInfo(comp, flags, userId);
5787                    if (ai == null) {
5788                        continue;
5789                    }
5790                }
5791
5792                // Look for any generic query activities that are duplicates
5793                // of this specific one, and remove them from the results.
5794                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
5795                N = results.size();
5796                int j;
5797                for (j=specificsPos; j<N; j++) {
5798                    ResolveInfo sri = results.get(j);
5799                    if ((sri.activityInfo.name.equals(comp.getClassName())
5800                            && sri.activityInfo.applicationInfo.packageName.equals(
5801                                    comp.getPackageName()))
5802                        || (action != null && sri.filter.matchAction(action))) {
5803                        results.remove(j);
5804                        if (DEBUG_INTENT_MATCHING) Log.v(
5805                            TAG, "Removing duplicate item from " + j
5806                            + " due to specific " + specificsPos);
5807                        if (ri == null) {
5808                            ri = sri;
5809                        }
5810                        j--;
5811                        N--;
5812                    }
5813                }
5814
5815                // Add this specific item to its proper place.
5816                if (ri == null) {
5817                    ri = new ResolveInfo();
5818                    ri.activityInfo = ai;
5819                }
5820                results.add(specificsPos, ri);
5821                ri.specificIndex = i;
5822                specificsPos++;
5823            }
5824        }
5825
5826        // Now we go through the remaining generic results and remove any
5827        // duplicate actions that are found here.
5828        N = results.size();
5829        for (int i=specificsPos; i<N-1; i++) {
5830            final ResolveInfo rii = results.get(i);
5831            if (rii.filter == null) {
5832                continue;
5833            }
5834
5835            // Iterate over all of the actions of this result's intent
5836            // filter...  typically this should be just one.
5837            final Iterator<String> it = rii.filter.actionsIterator();
5838            if (it == null) {
5839                continue;
5840            }
5841            while (it.hasNext()) {
5842                final String action = it.next();
5843                if (resultsAction != null && resultsAction.equals(action)) {
5844                    // If this action was explicitly requested, then don't
5845                    // remove things that have it.
5846                    continue;
5847                }
5848                for (int j=i+1; j<N; j++) {
5849                    final ResolveInfo rij = results.get(j);
5850                    if (rij.filter != null && rij.filter.hasAction(action)) {
5851                        results.remove(j);
5852                        if (DEBUG_INTENT_MATCHING) Log.v(
5853                            TAG, "Removing duplicate item from " + j
5854                            + " due to action " + action + " at " + i);
5855                        j--;
5856                        N--;
5857                    }
5858                }
5859            }
5860
5861            // If the caller didn't request filter information, drop it now
5862            // so we don't have to marshall/unmarshall it.
5863            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
5864                rii.filter = null;
5865            }
5866        }
5867
5868        // Filter out the caller activity if so requested.
5869        if (caller != null) {
5870            N = results.size();
5871            for (int i=0; i<N; i++) {
5872                ActivityInfo ainfo = results.get(i).activityInfo;
5873                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
5874                        && caller.getClassName().equals(ainfo.name)) {
5875                    results.remove(i);
5876                    break;
5877                }
5878            }
5879        }
5880
5881        // If the caller didn't request filter information,
5882        // drop them now so we don't have to
5883        // marshall/unmarshall it.
5884        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
5885            N = results.size();
5886            for (int i=0; i<N; i++) {
5887                results.get(i).filter = null;
5888            }
5889        }
5890
5891        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
5892        return results;
5893    }
5894
5895    @Override
5896    public @NonNull ParceledListSlice<ResolveInfo> queryIntentReceivers(Intent intent,
5897            String resolvedType, int flags, int userId) {
5898        return new ParceledListSlice<>(
5899                queryIntentReceiversInternal(intent, resolvedType, flags, userId));
5900    }
5901
5902    private @NonNull List<ResolveInfo> queryIntentReceiversInternal(Intent intent,
5903            String resolvedType, int flags, int userId) {
5904        if (!sUserManager.exists(userId)) return Collections.emptyList();
5905        flags = updateFlagsForResolve(flags, userId, intent);
5906        ComponentName comp = intent.getComponent();
5907        if (comp == null) {
5908            if (intent.getSelector() != null) {
5909                intent = intent.getSelector();
5910                comp = intent.getComponent();
5911            }
5912        }
5913        if (comp != null) {
5914            List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5915            ActivityInfo ai = getReceiverInfo(comp, flags, userId);
5916            if (ai != null) {
5917                ResolveInfo ri = new ResolveInfo();
5918                ri.activityInfo = ai;
5919                list.add(ri);
5920            }
5921            return list;
5922        }
5923
5924        // reader
5925        synchronized (mPackages) {
5926            String pkgName = intent.getPackage();
5927            if (pkgName == null) {
5928                return mReceivers.queryIntent(intent, resolvedType, flags, userId);
5929            }
5930            final PackageParser.Package pkg = mPackages.get(pkgName);
5931            if (pkg != null) {
5932                return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers,
5933                        userId);
5934            }
5935            return Collections.emptyList();
5936        }
5937    }
5938
5939    @Override
5940    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
5941        if (!sUserManager.exists(userId)) return null;
5942        flags = updateFlagsForResolve(flags, userId, intent);
5943        List<ResolveInfo> query = queryIntentServicesInternal(intent, resolvedType, flags, userId);
5944        if (query != null) {
5945            if (query.size() >= 1) {
5946                // If there is more than one service with the same priority,
5947                // just arbitrarily pick the first one.
5948                return query.get(0);
5949            }
5950        }
5951        return null;
5952    }
5953
5954    @Override
5955    public @NonNull ParceledListSlice<ResolveInfo> queryIntentServices(Intent intent,
5956            String resolvedType, int flags, int userId) {
5957        return new ParceledListSlice<>(
5958                queryIntentServicesInternal(intent, resolvedType, flags, userId));
5959    }
5960
5961    private @NonNull List<ResolveInfo> queryIntentServicesInternal(Intent intent,
5962            String resolvedType, int flags, int userId) {
5963        if (!sUserManager.exists(userId)) return Collections.emptyList();
5964        flags = updateFlagsForResolve(flags, userId, intent);
5965        ComponentName comp = intent.getComponent();
5966        if (comp == null) {
5967            if (intent.getSelector() != null) {
5968                intent = intent.getSelector();
5969                comp = intent.getComponent();
5970            }
5971        }
5972        if (comp != null) {
5973            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5974            final ServiceInfo si = getServiceInfo(comp, flags, userId);
5975            if (si != null) {
5976                final ResolveInfo ri = new ResolveInfo();
5977                ri.serviceInfo = si;
5978                list.add(ri);
5979            }
5980            return list;
5981        }
5982
5983        // reader
5984        synchronized (mPackages) {
5985            String pkgName = intent.getPackage();
5986            if (pkgName == null) {
5987                return mServices.queryIntent(intent, resolvedType, flags, userId);
5988            }
5989            final PackageParser.Package pkg = mPackages.get(pkgName);
5990            if (pkg != null) {
5991                return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
5992                        userId);
5993            }
5994            return Collections.emptyList();
5995        }
5996    }
5997
5998    @Override
5999    public @NonNull ParceledListSlice<ResolveInfo> queryIntentContentProviders(Intent intent,
6000            String resolvedType, int flags, int userId) {
6001        return new ParceledListSlice<>(
6002                queryIntentContentProvidersInternal(intent, resolvedType, flags, userId));
6003    }
6004
6005    private @NonNull List<ResolveInfo> queryIntentContentProvidersInternal(
6006            Intent intent, String resolvedType, int flags, int userId) {
6007        if (!sUserManager.exists(userId)) return Collections.emptyList();
6008        flags = updateFlagsForResolve(flags, userId, intent);
6009        ComponentName comp = intent.getComponent();
6010        if (comp == null) {
6011            if (intent.getSelector() != null) {
6012                intent = intent.getSelector();
6013                comp = intent.getComponent();
6014            }
6015        }
6016        if (comp != null) {
6017            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
6018            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
6019            if (pi != null) {
6020                final ResolveInfo ri = new ResolveInfo();
6021                ri.providerInfo = pi;
6022                list.add(ri);
6023            }
6024            return list;
6025        }
6026
6027        // reader
6028        synchronized (mPackages) {
6029            String pkgName = intent.getPackage();
6030            if (pkgName == null) {
6031                return mProviders.queryIntent(intent, resolvedType, flags, userId);
6032            }
6033            final PackageParser.Package pkg = mPackages.get(pkgName);
6034            if (pkg != null) {
6035                return mProviders.queryIntentForPackage(
6036                        intent, resolvedType, flags, pkg.providers, userId);
6037            }
6038            return Collections.emptyList();
6039        }
6040    }
6041
6042    @Override
6043    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
6044        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
6045        flags = updateFlagsForPackage(flags, userId, null);
6046        final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0;
6047        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6048                true /* requireFullPermission */, false /* checkShell */,
6049                "get installed packages");
6050
6051        // writer
6052        synchronized (mPackages) {
6053            ArrayList<PackageInfo> list;
6054            if (listUninstalled) {
6055                list = new ArrayList<PackageInfo>(mSettings.mPackages.size());
6056                for (PackageSetting ps : mSettings.mPackages.values()) {
6057                    final PackageInfo pi;
6058                    if (ps.pkg != null) {
6059                        pi = generatePackageInfo(ps, flags, userId);
6060                    } else {
6061                        pi = generatePackageInfo(ps, flags, userId);
6062                    }
6063                    if (pi != null) {
6064                        list.add(pi);
6065                    }
6066                }
6067            } else {
6068                list = new ArrayList<PackageInfo>(mPackages.size());
6069                for (PackageParser.Package p : mPackages.values()) {
6070                    final PackageInfo pi =
6071                            generatePackageInfo((PackageSetting)p.mExtras, flags, userId);
6072                    if (pi != null) {
6073                        list.add(pi);
6074                    }
6075                }
6076            }
6077
6078            return new ParceledListSlice<PackageInfo>(list);
6079        }
6080    }
6081
6082    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
6083            String[] permissions, boolean[] tmp, int flags, int userId) {
6084        int numMatch = 0;
6085        final PermissionsState permissionsState = ps.getPermissionsState();
6086        for (int i=0; i<permissions.length; i++) {
6087            final String permission = permissions[i];
6088            if (permissionsState.hasPermission(permission, userId)) {
6089                tmp[i] = true;
6090                numMatch++;
6091            } else {
6092                tmp[i] = false;
6093            }
6094        }
6095        if (numMatch == 0) {
6096            return;
6097        }
6098        final PackageInfo pi;
6099        if (ps.pkg != null) {
6100            pi = generatePackageInfo(ps, flags, userId);
6101        } else {
6102            pi = generatePackageInfo(ps, flags, userId);
6103        }
6104        // The above might return null in cases of uninstalled apps or install-state
6105        // skew across users/profiles.
6106        if (pi != null) {
6107            if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
6108                if (numMatch == permissions.length) {
6109                    pi.requestedPermissions = permissions;
6110                } else {
6111                    pi.requestedPermissions = new String[numMatch];
6112                    numMatch = 0;
6113                    for (int i=0; i<permissions.length; i++) {
6114                        if (tmp[i]) {
6115                            pi.requestedPermissions[numMatch] = permissions[i];
6116                            numMatch++;
6117                        }
6118                    }
6119                }
6120            }
6121            list.add(pi);
6122        }
6123    }
6124
6125    @Override
6126    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
6127            String[] permissions, int flags, int userId) {
6128        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
6129        flags = updateFlagsForPackage(flags, userId, permissions);
6130        final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0;
6131
6132        // writer
6133        synchronized (mPackages) {
6134            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
6135            boolean[] tmpBools = new boolean[permissions.length];
6136            if (listUninstalled) {
6137                for (PackageSetting ps : mSettings.mPackages.values()) {
6138                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId);
6139                }
6140            } else {
6141                for (PackageParser.Package pkg : mPackages.values()) {
6142                    PackageSetting ps = (PackageSetting)pkg.mExtras;
6143                    if (ps != null) {
6144                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
6145                                userId);
6146                    }
6147                }
6148            }
6149
6150            return new ParceledListSlice<PackageInfo>(list);
6151        }
6152    }
6153
6154    @Override
6155    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
6156        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
6157        flags = updateFlagsForApplication(flags, userId, null);
6158        final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0;
6159
6160        // writer
6161        synchronized (mPackages) {
6162            ArrayList<ApplicationInfo> list;
6163            if (listUninstalled) {
6164                list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size());
6165                for (PackageSetting ps : mSettings.mPackages.values()) {
6166                    ApplicationInfo ai;
6167                    if (ps.pkg != null) {
6168                        ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
6169                                ps.readUserState(userId), userId);
6170                    } else {
6171                        ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId);
6172                    }
6173                    if (ai != null) {
6174                        list.add(ai);
6175                    }
6176                }
6177            } else {
6178                list = new ArrayList<ApplicationInfo>(mPackages.size());
6179                for (PackageParser.Package p : mPackages.values()) {
6180                    if (p.mExtras != null) {
6181                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
6182                                ((PackageSetting)p.mExtras).readUserState(userId), userId);
6183                        if (ai != null) {
6184                            list.add(ai);
6185                        }
6186                    }
6187                }
6188            }
6189
6190            return new ParceledListSlice<ApplicationInfo>(list);
6191        }
6192    }
6193
6194    @Override
6195    public ParceledListSlice<EphemeralApplicationInfo> getEphemeralApplications(int userId) {
6196        if (DISABLE_EPHEMERAL_APPS) {
6197            return null;
6198        }
6199
6200        mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS,
6201                "getEphemeralApplications");
6202        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6203                true /* requireFullPermission */, false /* checkShell */,
6204                "getEphemeralApplications");
6205        synchronized (mPackages) {
6206            List<EphemeralApplicationInfo> ephemeralApps = mEphemeralApplicationRegistry
6207                    .getEphemeralApplicationsLPw(userId);
6208            if (ephemeralApps != null) {
6209                return new ParceledListSlice<>(ephemeralApps);
6210            }
6211        }
6212        return null;
6213    }
6214
6215    @Override
6216    public boolean isEphemeralApplication(String packageName, int userId) {
6217        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6218                true /* requireFullPermission */, false /* checkShell */,
6219                "isEphemeral");
6220        if (DISABLE_EPHEMERAL_APPS) {
6221            return false;
6222        }
6223
6224        if (!isCallerSameApp(packageName)) {
6225            return false;
6226        }
6227        synchronized (mPackages) {
6228            PackageParser.Package pkg = mPackages.get(packageName);
6229            if (pkg != null) {
6230                return pkg.applicationInfo.isEphemeralApp();
6231            }
6232        }
6233        return false;
6234    }
6235
6236    @Override
6237    public byte[] getEphemeralApplicationCookie(String packageName, int userId) {
6238        if (DISABLE_EPHEMERAL_APPS) {
6239            return null;
6240        }
6241
6242        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6243                true /* requireFullPermission */, false /* checkShell */,
6244                "getCookie");
6245        if (!isCallerSameApp(packageName)) {
6246            return null;
6247        }
6248        synchronized (mPackages) {
6249            return mEphemeralApplicationRegistry.getEphemeralApplicationCookieLPw(
6250                    packageName, userId);
6251        }
6252    }
6253
6254    @Override
6255    public boolean setEphemeralApplicationCookie(String packageName, byte[] cookie, int userId) {
6256        if (DISABLE_EPHEMERAL_APPS) {
6257            return true;
6258        }
6259
6260        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6261                true /* requireFullPermission */, true /* checkShell */,
6262                "setCookie");
6263        if (!isCallerSameApp(packageName)) {
6264            return false;
6265        }
6266        synchronized (mPackages) {
6267            return mEphemeralApplicationRegistry.setEphemeralApplicationCookieLPw(
6268                    packageName, cookie, userId);
6269        }
6270    }
6271
6272    @Override
6273    public Bitmap getEphemeralApplicationIcon(String packageName, int userId) {
6274        if (DISABLE_EPHEMERAL_APPS) {
6275            return null;
6276        }
6277
6278        mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS,
6279                "getEphemeralApplicationIcon");
6280        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6281                true /* requireFullPermission */, false /* checkShell */,
6282                "getEphemeralApplicationIcon");
6283        synchronized (mPackages) {
6284            return mEphemeralApplicationRegistry.getEphemeralApplicationIconLPw(
6285                    packageName, userId);
6286        }
6287    }
6288
6289    private boolean isCallerSameApp(String packageName) {
6290        PackageParser.Package pkg = mPackages.get(packageName);
6291        return pkg != null
6292                && UserHandle.getAppId(Binder.getCallingUid()) == pkg.applicationInfo.uid;
6293    }
6294
6295    @Override
6296    public @NonNull ParceledListSlice<ApplicationInfo> getPersistentApplications(int flags) {
6297        return new ParceledListSlice<>(getPersistentApplicationsInternal(flags));
6298    }
6299
6300    private @NonNull List<ApplicationInfo> getPersistentApplicationsInternal(int flags) {
6301        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
6302
6303        // reader
6304        synchronized (mPackages) {
6305            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
6306            final int userId = UserHandle.getCallingUserId();
6307            while (i.hasNext()) {
6308                final PackageParser.Package p = i.next();
6309                if (p.applicationInfo == null) continue;
6310
6311                final boolean matchesUnaware = ((flags & MATCH_DIRECT_BOOT_UNAWARE) != 0)
6312                        && !p.applicationInfo.isDirectBootAware();
6313                final boolean matchesAware = ((flags & MATCH_DIRECT_BOOT_AWARE) != 0)
6314                        && p.applicationInfo.isDirectBootAware();
6315
6316                if ((p.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0
6317                        && (!mSafeMode || isSystemApp(p))
6318                        && (matchesUnaware || matchesAware)) {
6319                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
6320                    if (ps != null) {
6321                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
6322                                ps.readUserState(userId), userId);
6323                        if (ai != null) {
6324                            finalList.add(ai);
6325                        }
6326                    }
6327                }
6328            }
6329        }
6330
6331        return finalList;
6332    }
6333
6334    @Override
6335    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
6336        if (!sUserManager.exists(userId)) return null;
6337        flags = updateFlagsForComponent(flags, userId, name);
6338        // reader
6339        synchronized (mPackages) {
6340            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
6341            PackageSetting ps = provider != null
6342                    ? mSettings.mPackages.get(provider.owner.packageName)
6343                    : null;
6344            return ps != null
6345                    && mSettings.isEnabledAndMatchLPr(provider.info, flags, userId)
6346                    ? PackageParser.generateProviderInfo(provider, flags,
6347                            ps.readUserState(userId), userId)
6348                    : null;
6349        }
6350    }
6351
6352    /**
6353     * @deprecated
6354     */
6355    @Deprecated
6356    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
6357        // reader
6358        synchronized (mPackages) {
6359            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
6360                    .entrySet().iterator();
6361            final int userId = UserHandle.getCallingUserId();
6362            while (i.hasNext()) {
6363                Map.Entry<String, PackageParser.Provider> entry = i.next();
6364                PackageParser.Provider p = entry.getValue();
6365                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
6366
6367                if (ps != null && p.syncable
6368                        && (!mSafeMode || (p.info.applicationInfo.flags
6369                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
6370                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
6371                            ps.readUserState(userId), userId);
6372                    if (info != null) {
6373                        outNames.add(entry.getKey());
6374                        outInfo.add(info);
6375                    }
6376                }
6377            }
6378        }
6379    }
6380
6381    @Override
6382    public @NonNull ParceledListSlice<ProviderInfo> queryContentProviders(String processName,
6383            int uid, int flags) {
6384        final int userId = processName != null ? UserHandle.getUserId(uid)
6385                : UserHandle.getCallingUserId();
6386        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
6387        flags = updateFlagsForComponent(flags, userId, processName);
6388
6389        ArrayList<ProviderInfo> finalList = null;
6390        // reader
6391        synchronized (mPackages) {
6392            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
6393            while (i.hasNext()) {
6394                final PackageParser.Provider p = i.next();
6395                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
6396                if (ps != null && p.info.authority != null
6397                        && (processName == null
6398                                || (p.info.processName.equals(processName)
6399                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
6400                        && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
6401                    if (finalList == null) {
6402                        finalList = new ArrayList<ProviderInfo>(3);
6403                    }
6404                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
6405                            ps.readUserState(userId), userId);
6406                    if (info != null) {
6407                        finalList.add(info);
6408                    }
6409                }
6410            }
6411        }
6412
6413        if (finalList != null) {
6414            Collections.sort(finalList, mProviderInitOrderSorter);
6415            return new ParceledListSlice<ProviderInfo>(finalList);
6416        }
6417
6418        return ParceledListSlice.emptyList();
6419    }
6420
6421    @Override
6422    public InstrumentationInfo getInstrumentationInfo(ComponentName name, int flags) {
6423        // reader
6424        synchronized (mPackages) {
6425            final PackageParser.Instrumentation i = mInstrumentation.get(name);
6426            return PackageParser.generateInstrumentationInfo(i, flags);
6427        }
6428    }
6429
6430    @Override
6431    public @NonNull ParceledListSlice<InstrumentationInfo> queryInstrumentation(
6432            String targetPackage, int flags) {
6433        return new ParceledListSlice<>(queryInstrumentationInternal(targetPackage, flags));
6434    }
6435
6436    private @NonNull List<InstrumentationInfo> queryInstrumentationInternal(String targetPackage,
6437            int flags) {
6438        ArrayList<InstrumentationInfo> finalList = new ArrayList<InstrumentationInfo>();
6439
6440        // reader
6441        synchronized (mPackages) {
6442            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
6443            while (i.hasNext()) {
6444                final PackageParser.Instrumentation p = i.next();
6445                if (targetPackage == null
6446                        || targetPackage.equals(p.info.targetPackage)) {
6447                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
6448                            flags);
6449                    if (ii != null) {
6450                        finalList.add(ii);
6451                    }
6452                }
6453            }
6454        }
6455
6456        return finalList;
6457    }
6458
6459    private void createIdmapsForPackageLI(PackageParser.Package pkg) {
6460        ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName);
6461        if (overlays == null) {
6462            Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages");
6463            return;
6464        }
6465        for (PackageParser.Package opkg : overlays.values()) {
6466            // Not much to do if idmap fails: we already logged the error
6467            // and we certainly don't want to abort installation of pkg simply
6468            // because an overlay didn't fit properly. For these reasons,
6469            // ignore the return value of createIdmapForPackagePairLI.
6470            createIdmapForPackagePairLI(pkg, opkg);
6471        }
6472    }
6473
6474    private boolean createIdmapForPackagePairLI(PackageParser.Package pkg,
6475            PackageParser.Package opkg) {
6476        if (!opkg.mTrustedOverlay) {
6477            Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " +
6478                    opkg.baseCodePath + ": overlay not trusted");
6479            return false;
6480        }
6481        ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName);
6482        if (overlaySet == null) {
6483            Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " +
6484                    opkg.baseCodePath + " but target package has no known overlays");
6485            return false;
6486        }
6487        final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
6488        // TODO: generate idmap for split APKs
6489        try {
6490            mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid);
6491        } catch (InstallerException e) {
6492            Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and "
6493                    + opkg.baseCodePath);
6494            return false;
6495        }
6496        PackageParser.Package[] overlayArray =
6497            overlaySet.values().toArray(new PackageParser.Package[0]);
6498        Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() {
6499            public int compare(PackageParser.Package p1, PackageParser.Package p2) {
6500                return p1.mOverlayPriority - p2.mOverlayPriority;
6501            }
6502        };
6503        Arrays.sort(overlayArray, cmp);
6504
6505        pkg.applicationInfo.resourceDirs = new String[overlayArray.length];
6506        int i = 0;
6507        for (PackageParser.Package p : overlayArray) {
6508            pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath;
6509        }
6510        return true;
6511    }
6512
6513    private void scanDirTracedLI(File dir, final int parseFlags, int scanFlags, long currentTime) {
6514        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir");
6515        try {
6516            scanDirLI(dir, parseFlags, scanFlags, currentTime);
6517        } finally {
6518            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6519        }
6520    }
6521
6522    private void scanDirLI(File dir, final int parseFlags, int scanFlags, long currentTime) {
6523        final File[] files = dir.listFiles();
6524        if (ArrayUtils.isEmpty(files)) {
6525            Log.d(TAG, "No files in app dir " + dir);
6526            return;
6527        }
6528
6529        if (DEBUG_PACKAGE_SCANNING) {
6530            Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags
6531                    + " flags=0x" + Integer.toHexString(parseFlags));
6532        }
6533
6534        for (File file : files) {
6535            final boolean isPackage = (isApkFile(file) || file.isDirectory())
6536                    && !PackageInstallerService.isStageName(file.getName());
6537            if (!isPackage) {
6538                // Ignore entries which are not packages
6539                continue;
6540            }
6541            try {
6542                scanPackageTracedLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK,
6543                        scanFlags, currentTime, null);
6544            } catch (PackageManagerException e) {
6545                Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage());
6546
6547                // Delete invalid userdata apps
6548                if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
6549                        e.error == PackageManager.INSTALL_FAILED_INVALID_APK) {
6550                    logCriticalInfo(Log.WARN, "Deleting invalid package at " + file);
6551                    removeCodePathLI(file);
6552                }
6553            }
6554        }
6555    }
6556
6557    private static File getSettingsProblemFile() {
6558        File dataDir = Environment.getDataDirectory();
6559        File systemDir = new File(dataDir, "system");
6560        File fname = new File(systemDir, "uiderrors.txt");
6561        return fname;
6562    }
6563
6564    static void reportSettingsProblem(int priority, String msg) {
6565        logCriticalInfo(priority, msg);
6566    }
6567
6568    static void logCriticalInfo(int priority, String msg) {
6569        Slog.println(priority, TAG, msg);
6570        EventLogTags.writePmCriticalInfo(msg);
6571        try {
6572            File fname = getSettingsProblemFile();
6573            FileOutputStream out = new FileOutputStream(fname, true);
6574            PrintWriter pw = new FastPrintWriter(out);
6575            SimpleDateFormat formatter = new SimpleDateFormat();
6576            String dateString = formatter.format(new Date(System.currentTimeMillis()));
6577            pw.println(dateString + ": " + msg);
6578            pw.close();
6579            FileUtils.setPermissions(
6580                    fname.toString(),
6581                    FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
6582                    -1, -1);
6583        } catch (java.io.IOException e) {
6584        }
6585    }
6586
6587    private void collectCertificatesLI(PackageSetting ps, PackageParser.Package pkg, File srcFile,
6588            final int policyFlags) throws PackageManagerException {
6589        if (ps != null
6590                && ps.codePath.equals(srcFile)
6591                && ps.timeStamp == srcFile.lastModified()
6592                && !isCompatSignatureUpdateNeeded(pkg)
6593                && !isRecoverSignatureUpdateNeeded(pkg)) {
6594            long mSigningKeySetId = ps.keySetData.getProperSigningKeySet();
6595            KeySetManagerService ksms = mSettings.mKeySetManagerService;
6596            ArraySet<PublicKey> signingKs;
6597            synchronized (mPackages) {
6598                signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId);
6599            }
6600            if (ps.signatures.mSignatures != null
6601                    && ps.signatures.mSignatures.length != 0
6602                    && signingKs != null) {
6603                // Optimization: reuse the existing cached certificates
6604                // if the package appears to be unchanged.
6605                pkg.mSignatures = ps.signatures.mSignatures;
6606                pkg.mSigningKeys = signingKs;
6607                return;
6608            }
6609
6610            Slog.w(TAG, "PackageSetting for " + ps.name
6611                    + " is missing signatures.  Collecting certs again to recover them.");
6612        } else {
6613            Log.i(TAG, srcFile.toString() + " changed; collecting certs");
6614        }
6615
6616        try {
6617            PackageParser.collectCertificates(pkg, policyFlags);
6618        } catch (PackageParserException e) {
6619            throw PackageManagerException.from(e);
6620        }
6621    }
6622
6623    /**
6624     *  Traces a package scan.
6625     *  @see #scanPackageLI(File, int, int, long, UserHandle)
6626     */
6627    private PackageParser.Package scanPackageTracedLI(File scanFile, final int parseFlags,
6628            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
6629        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage");
6630        try {
6631            return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user);
6632        } finally {
6633            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6634        }
6635    }
6636
6637    /**
6638     *  Scans a package and returns the newly parsed package.
6639     *  Returns {@code null} in case of errors and the error code is stored in mLastScanError
6640     */
6641    private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags,
6642            long currentTime, UserHandle user) throws PackageManagerException {
6643        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
6644        PackageParser pp = new PackageParser();
6645        pp.setSeparateProcesses(mSeparateProcesses);
6646        pp.setOnlyCoreApps(mOnlyCore);
6647        pp.setDisplayMetrics(mMetrics);
6648
6649        if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) {
6650            parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY;
6651        }
6652
6653        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
6654        final PackageParser.Package pkg;
6655        try {
6656            pkg = pp.parsePackage(scanFile, parseFlags);
6657        } catch (PackageParserException e) {
6658            throw PackageManagerException.from(e);
6659        } finally {
6660            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6661        }
6662
6663        return scanPackageLI(pkg, scanFile, parseFlags, scanFlags, currentTime, user);
6664    }
6665
6666    /**
6667     *  Scans a package and returns the newly parsed package.
6668     *  @throws PackageManagerException on a parse error.
6669     */
6670    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, File scanFile,
6671            final int policyFlags, int scanFlags, long currentTime, UserHandle user)
6672            throws PackageManagerException {
6673        // If the package has children and this is the first dive in the function
6674        // we scan the package with the SCAN_CHECK_ONLY flag set to see whether all
6675        // packages (parent and children) would be successfully scanned before the
6676        // actual scan since scanning mutates internal state and we want to atomically
6677        // install the package and its children.
6678        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
6679            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
6680                scanFlags |= SCAN_CHECK_ONLY;
6681            }
6682        } else {
6683            scanFlags &= ~SCAN_CHECK_ONLY;
6684        }
6685
6686        // Scan the parent
6687        PackageParser.Package scannedPkg = scanPackageInternalLI(pkg, scanFile, policyFlags,
6688                scanFlags, currentTime, user);
6689
6690        // Scan the children
6691        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
6692        for (int i = 0; i < childCount; i++) {
6693            PackageParser.Package childPackage = pkg.childPackages.get(i);
6694            scanPackageInternalLI(childPackage, scanFile, policyFlags, scanFlags,
6695                    currentTime, user);
6696        }
6697
6698
6699        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
6700            return scanPackageLI(pkg, scanFile, policyFlags, scanFlags, currentTime, user);
6701        }
6702
6703        return scannedPkg;
6704    }
6705
6706    /**
6707     *  Scans a package and returns the newly parsed package.
6708     *  @throws PackageManagerException on a parse error.
6709     */
6710    private PackageParser.Package scanPackageInternalLI(PackageParser.Package pkg, File scanFile,
6711            int policyFlags, int scanFlags, long currentTime, UserHandle user)
6712            throws PackageManagerException {
6713        PackageSetting ps = null;
6714        PackageSetting updatedPkg;
6715        // reader
6716        synchronized (mPackages) {
6717            // Look to see if we already know about this package.
6718            String oldName = mSettings.mRenamedPackages.get(pkg.packageName);
6719            if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
6720                // This package has been renamed to its original name.  Let's
6721                // use that.
6722                ps = mSettings.peekPackageLPr(oldName);
6723            }
6724            // If there was no original package, see one for the real package name.
6725            if (ps == null) {
6726                ps = mSettings.peekPackageLPr(pkg.packageName);
6727            }
6728            // Check to see if this package could be hiding/updating a system
6729            // package.  Must look for it either under the original or real
6730            // package name depending on our state.
6731            updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName);
6732            if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg);
6733
6734            // If this is a package we don't know about on the system partition, we
6735            // may need to remove disabled child packages on the system partition
6736            // or may need to not add child packages if the parent apk is updated
6737            // on the data partition and no longer defines this child package.
6738            if ((policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) {
6739                // If this is a parent package for an updated system app and this system
6740                // app got an OTA update which no longer defines some of the child packages
6741                // we have to prune them from the disabled system packages.
6742                PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName);
6743                if (disabledPs != null) {
6744                    final int scannedChildCount = (pkg.childPackages != null)
6745                            ? pkg.childPackages.size() : 0;
6746                    final int disabledChildCount = disabledPs.childPackageNames != null
6747                            ? disabledPs.childPackageNames.size() : 0;
6748                    for (int i = 0; i < disabledChildCount; i++) {
6749                        String disabledChildPackageName = disabledPs.childPackageNames.get(i);
6750                        boolean disabledPackageAvailable = false;
6751                        for (int j = 0; j < scannedChildCount; j++) {
6752                            PackageParser.Package childPkg = pkg.childPackages.get(j);
6753                            if (childPkg.packageName.equals(disabledChildPackageName)) {
6754                                disabledPackageAvailable = true;
6755                                break;
6756                            }
6757                         }
6758                         if (!disabledPackageAvailable) {
6759                             mSettings.removeDisabledSystemPackageLPw(disabledChildPackageName);
6760                         }
6761                    }
6762                }
6763            }
6764        }
6765
6766        boolean updatedPkgBetter = false;
6767        // First check if this is a system package that may involve an update
6768        if (updatedPkg != null && (policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) {
6769            // If new package is not located in "/system/priv-app" (e.g. due to an OTA),
6770            // it needs to drop FLAG_PRIVILEGED.
6771            if (locationIsPrivileged(scanFile)) {
6772                updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
6773            } else {
6774                updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
6775            }
6776
6777            if (ps != null && !ps.codePath.equals(scanFile)) {
6778                // The path has changed from what was last scanned...  check the
6779                // version of the new path against what we have stored to determine
6780                // what to do.
6781                if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath);
6782                if (pkg.mVersionCode <= ps.versionCode) {
6783                    // The system package has been updated and the code path does not match
6784                    // Ignore entry. Skip it.
6785                    if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile
6786                            + " ignored: updated version " + ps.versionCode
6787                            + " better than this " + pkg.mVersionCode);
6788                    if (!updatedPkg.codePath.equals(scanFile)) {
6789                        Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg "
6790                                + ps.name + " changing from " + updatedPkg.codePathString
6791                                + " to " + scanFile);
6792                        updatedPkg.codePath = scanFile;
6793                        updatedPkg.codePathString = scanFile.toString();
6794                        updatedPkg.resourcePath = scanFile;
6795                        updatedPkg.resourcePathString = scanFile.toString();
6796                    }
6797                    updatedPkg.pkg = pkg;
6798                    updatedPkg.versionCode = pkg.mVersionCode;
6799
6800                    // Update the disabled system child packages to point to the package too.
6801                    final int childCount = updatedPkg.childPackageNames != null
6802                            ? updatedPkg.childPackageNames.size() : 0;
6803                    for (int i = 0; i < childCount; i++) {
6804                        String childPackageName = updatedPkg.childPackageNames.get(i);
6805                        PackageSetting updatedChildPkg = mSettings.getDisabledSystemPkgLPr(
6806                                childPackageName);
6807                        if (updatedChildPkg != null) {
6808                            updatedChildPkg.pkg = pkg;
6809                            updatedChildPkg.versionCode = pkg.mVersionCode;
6810                        }
6811                    }
6812
6813                    throw new PackageManagerException(Log.WARN, "Package " + ps.name + " at "
6814                            + scanFile + " ignored: updated version " + ps.versionCode
6815                            + " better than this " + pkg.mVersionCode);
6816                } else {
6817                    // The current app on the system partition is better than
6818                    // what we have updated to on the data partition; switch
6819                    // back to the system partition version.
6820                    // At this point, its safely assumed that package installation for
6821                    // apps in system partition will go through. If not there won't be a working
6822                    // version of the app
6823                    // writer
6824                    synchronized (mPackages) {
6825                        // Just remove the loaded entries from package lists.
6826                        mPackages.remove(ps.name);
6827                    }
6828
6829                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
6830                            + " reverting from " + ps.codePathString
6831                            + ": new version " + pkg.mVersionCode
6832                            + " better than installed " + ps.versionCode);
6833
6834                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
6835                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
6836                    synchronized (mInstallLock) {
6837                        args.cleanUpResourcesLI();
6838                    }
6839                    synchronized (mPackages) {
6840                        mSettings.enableSystemPackageLPw(ps.name);
6841                    }
6842                    updatedPkgBetter = true;
6843                }
6844            }
6845        }
6846
6847        if (updatedPkg != null) {
6848            // An updated system app will not have the PARSE_IS_SYSTEM flag set
6849            // initially
6850            policyFlags |= PackageParser.PARSE_IS_SYSTEM;
6851
6852            // An updated privileged app will not have the PARSE_IS_PRIVILEGED
6853            // flag set initially
6854            if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
6855                policyFlags |= PackageParser.PARSE_IS_PRIVILEGED;
6856            }
6857        }
6858
6859        // Verify certificates against what was last scanned
6860        collectCertificatesLI(ps, pkg, scanFile, policyFlags);
6861
6862        /*
6863         * A new system app appeared, but we already had a non-system one of the
6864         * same name installed earlier.
6865         */
6866        boolean shouldHideSystemApp = false;
6867        if (updatedPkg == null && ps != null
6868                && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) {
6869            /*
6870             * Check to make sure the signatures match first. If they don't,
6871             * wipe the installed application and its data.
6872             */
6873            if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures)
6874                    != PackageManager.SIGNATURE_MATCH) {
6875                logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but"
6876                        + " signatures don't match existing userdata copy; removing");
6877                try (PackageFreezer freezer = freezePackage(pkg.packageName,
6878                        "scanPackageInternalLI")) {
6879                    deletePackageLIF(pkg.packageName, null, true, null, 0, null, false, null);
6880                }
6881                ps = null;
6882            } else {
6883                /*
6884                 * If the newly-added system app is an older version than the
6885                 * already installed version, hide it. It will be scanned later
6886                 * and re-added like an update.
6887                 */
6888                if (pkg.mVersionCode <= ps.versionCode) {
6889                    shouldHideSystemApp = true;
6890                    logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile
6891                            + " but new version " + pkg.mVersionCode + " better than installed "
6892                            + ps.versionCode + "; hiding system");
6893                } else {
6894                    /*
6895                     * The newly found system app is a newer version that the
6896                     * one previously installed. Simply remove the
6897                     * already-installed application and replace it with our own
6898                     * while keeping the application data.
6899                     */
6900                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
6901                            + " reverting from " + ps.codePathString + ": new version "
6902                            + pkg.mVersionCode + " better than installed " + ps.versionCode);
6903                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
6904                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
6905                    synchronized (mInstallLock) {
6906                        args.cleanUpResourcesLI();
6907                    }
6908                }
6909            }
6910        }
6911
6912        // The apk is forward locked (not public) if its code and resources
6913        // are kept in different files. (except for app in either system or
6914        // vendor path).
6915        // TODO grab this value from PackageSettings
6916        if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
6917            if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
6918                policyFlags |= PackageParser.PARSE_FORWARD_LOCK;
6919            }
6920        }
6921
6922        // TODO: extend to support forward-locked splits
6923        String resourcePath = null;
6924        String baseResourcePath = null;
6925        if ((policyFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) {
6926            if (ps != null && ps.resourcePathString != null) {
6927                resourcePath = ps.resourcePathString;
6928                baseResourcePath = ps.resourcePathString;
6929            } else {
6930                // Should not happen at all. Just log an error.
6931                Slog.e(TAG, "Resource path not set for package " + pkg.packageName);
6932            }
6933        } else {
6934            resourcePath = pkg.codePath;
6935            baseResourcePath = pkg.baseCodePath;
6936        }
6937
6938        // Set application objects path explicitly.
6939        pkg.setApplicationVolumeUuid(pkg.volumeUuid);
6940        pkg.setApplicationInfoCodePath(pkg.codePath);
6941        pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
6942        pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
6943        pkg.setApplicationInfoResourcePath(resourcePath);
6944        pkg.setApplicationInfoBaseResourcePath(baseResourcePath);
6945        pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
6946
6947        // Note that we invoke the following method only if we are about to unpack an application
6948        PackageParser.Package scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags
6949                | SCAN_UPDATE_SIGNATURE, currentTime, user);
6950
6951        /*
6952         * If the system app should be overridden by a previously installed
6953         * data, hide the system app now and let the /data/app scan pick it up
6954         * again.
6955         */
6956        if (shouldHideSystemApp) {
6957            synchronized (mPackages) {
6958                mSettings.disableSystemPackageLPw(pkg.packageName, true);
6959            }
6960        }
6961
6962        return scannedPkg;
6963    }
6964
6965    private static String fixProcessName(String defProcessName,
6966            String processName, int uid) {
6967        if (processName == null) {
6968            return defProcessName;
6969        }
6970        return processName;
6971    }
6972
6973    private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg)
6974            throws PackageManagerException {
6975        if (pkgSetting.signatures.mSignatures != null) {
6976            // Already existing package. Make sure signatures match
6977            boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures)
6978                    == PackageManager.SIGNATURE_MATCH;
6979            if (!match) {
6980                match = compareSignaturesCompat(pkgSetting.signatures, pkg)
6981                        == PackageManager.SIGNATURE_MATCH;
6982            }
6983            if (!match) {
6984                match = compareSignaturesRecover(pkgSetting.signatures, pkg)
6985                        == PackageManager.SIGNATURE_MATCH;
6986            }
6987            if (!match) {
6988                throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
6989                        + pkg.packageName + " signatures do not match the "
6990                        + "previously installed version; ignoring!");
6991            }
6992        }
6993
6994        // Check for shared user signatures
6995        if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
6996            // Already existing package. Make sure signatures match
6997            boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
6998                    pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
6999            if (!match) {
7000                match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg)
7001                        == PackageManager.SIGNATURE_MATCH;
7002            }
7003            if (!match) {
7004                match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg)
7005                        == PackageManager.SIGNATURE_MATCH;
7006            }
7007            if (!match) {
7008                throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
7009                        "Package " + pkg.packageName
7010                        + " has no signatures that match those in shared user "
7011                        + pkgSetting.sharedUser.name + "; ignoring!");
7012            }
7013        }
7014    }
7015
7016    /**
7017     * Enforces that only the system UID or root's UID can call a method exposed
7018     * via Binder.
7019     *
7020     * @param message used as message if SecurityException is thrown
7021     * @throws SecurityException if the caller is not system or root
7022     */
7023    private static final void enforceSystemOrRoot(String message) {
7024        final int uid = Binder.getCallingUid();
7025        if (uid != Process.SYSTEM_UID && uid != 0) {
7026            throw new SecurityException(message);
7027        }
7028    }
7029
7030    @Override
7031    public void performFstrimIfNeeded() {
7032        enforceSystemOrRoot("Only the system can request fstrim");
7033
7034        // Before everything else, see whether we need to fstrim.
7035        try {
7036            IMountService ms = PackageHelper.getMountService();
7037            if (ms != null) {
7038                final boolean isUpgrade = isUpgrade();
7039                boolean doTrim = isUpgrade;
7040                if (doTrim) {
7041                    Slog.w(TAG, "Running disk maintenance immediately due to system update");
7042                } else {
7043                    final long interval = android.provider.Settings.Global.getLong(
7044                            mContext.getContentResolver(),
7045                            android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL,
7046                            DEFAULT_MANDATORY_FSTRIM_INTERVAL);
7047                    if (interval > 0) {
7048                        final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance();
7049                        if (timeSinceLast > interval) {
7050                            doTrim = true;
7051                            Slog.w(TAG, "No disk maintenance in " + timeSinceLast
7052                                    + "; running immediately");
7053                        }
7054                    }
7055                }
7056                if (doTrim) {
7057                    if (!isFirstBoot()) {
7058                        try {
7059                            ActivityManagerNative.getDefault().showBootMessage(
7060                                    mContext.getResources().getString(
7061                                            R.string.android_upgrading_fstrim), true);
7062                        } catch (RemoteException e) {
7063                        }
7064                    }
7065                    ms.runMaintenance();
7066                }
7067            } else {
7068                Slog.e(TAG, "Mount service unavailable!");
7069            }
7070        } catch (RemoteException e) {
7071            // Can't happen; MountService is local
7072        }
7073    }
7074
7075    @Override
7076    public void updatePackagesIfNeeded() {
7077        enforceSystemOrRoot("Only the system can request package update");
7078
7079        // We need to re-extract after an OTA.
7080        boolean causeUpgrade = isUpgrade();
7081
7082        // First boot or factory reset.
7083        // Note: we also handle devices that are upgrading to N right now as if it is their
7084        //       first boot, as they do not have profile data.
7085        boolean causeFirstBoot = isFirstBoot() || mIsPreNUpgrade;
7086
7087        // We need to re-extract after a pruned cache, as AoT-ed files will be out of date.
7088        boolean causePrunedCache = VMRuntime.didPruneDalvikCache();
7089
7090        if (!causeUpgrade && !causeFirstBoot && !causePrunedCache) {
7091            return;
7092        }
7093
7094        List<PackageParser.Package> pkgs;
7095        synchronized (mPackages) {
7096            pkgs = PackageManagerServiceUtils.getPackagesForDexopt(mPackages.values(), this);
7097        }
7098
7099        int curr = 0;
7100        int total = pkgs.size();
7101        for (PackageParser.Package pkg : pkgs) {
7102            curr++;
7103
7104            if (!PackageDexOptimizer.canOptimizePackage(pkg)) {
7105                if (DEBUG_DEXOPT) {
7106                    Log.i(TAG, "Skipping update of of non-optimizable app " + pkg.packageName);
7107                }
7108                continue;
7109            }
7110
7111            if (DEBUG_DEXOPT) {
7112                Log.i(TAG, "Extracting app " + curr + " of " + total + ": " + pkg.packageName);
7113            }
7114
7115            if (!isFirstBoot()) {
7116                try {
7117                    ActivityManagerNative.getDefault().showBootMessage(
7118                            mContext.getResources().getString(R.string.android_upgrading_apk,
7119                                    curr, total), true);
7120                } catch (RemoteException e) {
7121                }
7122            }
7123
7124            performDexOpt(pkg.packageName,
7125                    null /* instructionSet */,
7126                    false /* checkProfiles */,
7127                    causeFirstBoot ? REASON_FIRST_BOOT : REASON_BOOT,
7128                    false /* force */);
7129        }
7130    }
7131
7132    @Override
7133    public void notifyPackageUse(String packageName) {
7134        synchronized (mPackages) {
7135            PackageParser.Package p = mPackages.get(packageName);
7136            if (p == null) {
7137                return;
7138            }
7139            p.mLastPackageUsageTimeInMills = System.currentTimeMillis();
7140        }
7141    }
7142
7143    // TODO: this is not used nor needed. Delete it.
7144    @Override
7145    public boolean performDexOptIfNeeded(String packageName, String instructionSet) {
7146        return performDexOptTraced(packageName, instructionSet, false /* checkProfiles */,
7147                getFullCompilerFilter(), false /* force */);
7148    }
7149
7150    @Override
7151    public boolean performDexOpt(String packageName, String instructionSet,
7152            boolean checkProfiles, int compileReason, boolean force) {
7153        return performDexOptTraced(packageName, instructionSet, checkProfiles,
7154                getCompilerFilterForReason(compileReason), force);
7155    }
7156
7157    @Override
7158    public boolean performDexOptMode(String packageName, String instructionSet,
7159            boolean checkProfiles, String targetCompilerFilter, boolean force) {
7160        return performDexOptTraced(packageName, instructionSet, checkProfiles,
7161                targetCompilerFilter, force);
7162    }
7163
7164    private boolean performDexOptTraced(String packageName, String instructionSet,
7165                boolean checkProfiles, String targetCompilerFilter, boolean force) {
7166        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
7167        try {
7168            return performDexOptInternal(packageName, instructionSet, checkProfiles,
7169                    targetCompilerFilter, force);
7170        } finally {
7171            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7172        }
7173    }
7174
7175    // Run dexopt on a given package. Returns true if dexopt did not fail, i.e.
7176    // if the package can now be considered up to date for the given filter.
7177    private boolean performDexOptInternal(String packageName, String instructionSet,
7178                boolean checkProfiles, String targetCompilerFilter, boolean force) {
7179        PackageParser.Package p;
7180        final String targetInstructionSet;
7181        synchronized (mPackages) {
7182            p = mPackages.get(packageName);
7183            if (p == null) {
7184                return false;
7185            }
7186            mPackageUsage.write(false);
7187
7188            targetInstructionSet = instructionSet != null ? instructionSet :
7189                    getPrimaryInstructionSet(p.applicationInfo);
7190        }
7191        long callingId = Binder.clearCallingIdentity();
7192        try {
7193            synchronized (mInstallLock) {
7194                final String[] instructionSets = new String[] { targetInstructionSet };
7195                int result = performDexOptInternalWithDependenciesLI(p, instructionSets,
7196                        checkProfiles, targetCompilerFilter, force);
7197                return result != PackageDexOptimizer.DEX_OPT_FAILED;
7198            }
7199        } finally {
7200            Binder.restoreCallingIdentity(callingId);
7201        }
7202    }
7203
7204    public ArraySet<String> getOptimizablePackages() {
7205        ArraySet<String> pkgs = new ArraySet<String>();
7206        synchronized (mPackages) {
7207            for (PackageParser.Package p : mPackages.values()) {
7208                if (PackageDexOptimizer.canOptimizePackage(p)) {
7209                    pkgs.add(p.packageName);
7210                }
7211            }
7212        }
7213        return pkgs;
7214    }
7215
7216    private int performDexOptInternalWithDependenciesLI(PackageParser.Package p,
7217            String instructionSets[], boolean checkProfiles, String targetCompilerFilter,
7218            boolean force) {
7219        // Select the dex optimizer based on the force parameter.
7220        // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to
7221        //       allocate an object here.
7222        PackageDexOptimizer pdo = force
7223                ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer)
7224                : mPackageDexOptimizer;
7225
7226        // Optimize all dependencies first. Note: we ignore the return value and march on
7227        // on errors.
7228        Collection<PackageParser.Package> deps = findSharedNonSystemLibraries(p);
7229        if (!deps.isEmpty()) {
7230            for (PackageParser.Package depPackage : deps) {
7231                // TODO: Analyze and investigate if we (should) profile libraries.
7232                // Currently this will do a full compilation of the library by default.
7233                pdo.performDexOpt(depPackage, instructionSets, false /* checkProfiles */,
7234                        getCompilerFilterForReason(REASON_NON_SYSTEM_LIBRARY));
7235            }
7236        }
7237
7238        return pdo.performDexOpt(p, instructionSets, checkProfiles, targetCompilerFilter);
7239    }
7240
7241    Collection<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package p) {
7242        if (p.usesLibraries != null || p.usesOptionalLibraries != null) {
7243            ArrayList<PackageParser.Package> retValue = new ArrayList<>();
7244            Set<String> collectedNames = new HashSet<>();
7245            findSharedNonSystemLibrariesRecursive(p, retValue, collectedNames);
7246
7247            retValue.remove(p);
7248
7249            return retValue;
7250        } else {
7251            return Collections.emptyList();
7252        }
7253    }
7254
7255    private void findSharedNonSystemLibrariesRecursive(PackageParser.Package p,
7256            Collection<PackageParser.Package> collected, Set<String> collectedNames) {
7257        if (!collectedNames.contains(p.packageName)) {
7258            collectedNames.add(p.packageName);
7259            collected.add(p);
7260
7261            if (p.usesLibraries != null) {
7262                findSharedNonSystemLibrariesRecursive(p.usesLibraries, collected, collectedNames);
7263            }
7264            if (p.usesOptionalLibraries != null) {
7265                findSharedNonSystemLibrariesRecursive(p.usesOptionalLibraries, collected,
7266                        collectedNames);
7267            }
7268        }
7269    }
7270
7271    private void findSharedNonSystemLibrariesRecursive(Collection<String> libs,
7272            Collection<PackageParser.Package> collected, Set<String> collectedNames) {
7273        for (String libName : libs) {
7274            PackageParser.Package libPkg = findSharedNonSystemLibrary(libName);
7275            if (libPkg != null) {
7276                findSharedNonSystemLibrariesRecursive(libPkg, collected, collectedNames);
7277            }
7278        }
7279    }
7280
7281    private PackageParser.Package findSharedNonSystemLibrary(String libName) {
7282        synchronized (mPackages) {
7283            PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName);
7284            if (lib != null && lib.apk != null) {
7285                return mPackages.get(lib.apk);
7286            }
7287        }
7288        return null;
7289    }
7290
7291    public void shutdown() {
7292        mPackageUsage.write(true);
7293    }
7294
7295    @Override
7296    public void forceDexOpt(String packageName) {
7297        enforceSystemOrRoot("forceDexOpt");
7298
7299        PackageParser.Package pkg;
7300        synchronized (mPackages) {
7301            pkg = mPackages.get(packageName);
7302            if (pkg == null) {
7303                throw new IllegalArgumentException("Unknown package: " + packageName);
7304            }
7305        }
7306
7307        synchronized (mInstallLock) {
7308            final String[] instructionSets = new String[] {
7309                    getPrimaryInstructionSet(pkg.applicationInfo) };
7310
7311            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
7312
7313            // Whoever is calling forceDexOpt wants a fully compiled package.
7314            // Don't use profiles since that may cause compilation to be skipped.
7315            final int res = performDexOptInternalWithDependenciesLI(pkg, instructionSets,
7316                    false /* checkProfiles */, getCompilerFilterForReason(REASON_FORCED_DEXOPT),
7317                    true /* force */);
7318
7319            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7320            if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) {
7321                throw new IllegalStateException("Failed to dexopt: " + res);
7322            }
7323        }
7324    }
7325
7326    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
7327        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
7328            Slog.w(TAG, "Unable to update from " + oldPkg.name
7329                    + " to " + newPkg.packageName
7330                    + ": old package not in system partition");
7331            return false;
7332        } else if (mPackages.get(oldPkg.name) != null) {
7333            Slog.w(TAG, "Unable to update from " + oldPkg.name
7334                    + " to " + newPkg.packageName
7335                    + ": old package still exists");
7336            return false;
7337        }
7338        return true;
7339    }
7340
7341    void removeCodePathLI(File codePath) {
7342        if (codePath.isDirectory()) {
7343            try {
7344                mInstaller.rmPackageDir(codePath.getAbsolutePath());
7345            } catch (InstallerException e) {
7346                Slog.w(TAG, "Failed to remove code path", e);
7347            }
7348        } else {
7349            codePath.delete();
7350        }
7351    }
7352
7353    private int[] resolveUserIds(int userId) {
7354        return (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() : new int[] { userId };
7355    }
7356
7357    private void clearAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
7358        if (pkg == null) {
7359            Slog.wtf(TAG, "Package was null!", new Throwable());
7360            return;
7361        }
7362        clearAppDataLeafLIF(pkg, userId, flags);
7363        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7364        for (int i = 0; i < childCount; i++) {
7365            clearAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
7366        }
7367    }
7368
7369    private void clearAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
7370        final PackageSetting ps;
7371        synchronized (mPackages) {
7372            ps = mSettings.mPackages.get(pkg.packageName);
7373        }
7374        for (int realUserId : resolveUserIds(userId)) {
7375            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
7376            try {
7377                mInstaller.clearAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
7378                        ceDataInode);
7379            } catch (InstallerException e) {
7380                Slog.w(TAG, String.valueOf(e));
7381            }
7382        }
7383    }
7384
7385    private void destroyAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
7386        if (pkg == null) {
7387            Slog.wtf(TAG, "Package was null!", new Throwable());
7388            return;
7389        }
7390        destroyAppDataLeafLIF(pkg, userId, flags);
7391        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7392        for (int i = 0; i < childCount; i++) {
7393            destroyAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
7394        }
7395    }
7396
7397    private void destroyAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
7398        final PackageSetting ps;
7399        synchronized (mPackages) {
7400            ps = mSettings.mPackages.get(pkg.packageName);
7401        }
7402        for (int realUserId : resolveUserIds(userId)) {
7403            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
7404            try {
7405                mInstaller.destroyAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
7406                        ceDataInode);
7407            } catch (InstallerException e) {
7408                Slog.w(TAG, String.valueOf(e));
7409            }
7410        }
7411    }
7412
7413    private void destroyAppProfilesLIF(PackageParser.Package pkg) {
7414        if (pkg == null) {
7415            Slog.wtf(TAG, "Package was null!", new Throwable());
7416            return;
7417        }
7418        destroyAppProfilesLeafLIF(pkg);
7419        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7420        for (int i = 0; i < childCount; i++) {
7421            destroyAppProfilesLeafLIF(pkg.childPackages.get(i));
7422        }
7423    }
7424
7425    private void destroyAppProfilesLeafLIF(PackageParser.Package pkg) {
7426        try {
7427            mInstaller.destroyAppProfiles(pkg.packageName);
7428        } catch (InstallerException e) {
7429            Slog.w(TAG, String.valueOf(e));
7430        }
7431    }
7432
7433    private void clearAppProfilesLIF(PackageParser.Package pkg) {
7434        if (pkg == null) {
7435            Slog.wtf(TAG, "Package was null!", new Throwable());
7436            return;
7437        }
7438        clearAppProfilesLeafLIF(pkg);
7439        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7440        for (int i = 0; i < childCount; i++) {
7441            clearAppProfilesLeafLIF(pkg.childPackages.get(i));
7442        }
7443    }
7444
7445    private void clearAppProfilesLeafLIF(PackageParser.Package pkg) {
7446        try {
7447            mInstaller.clearAppProfiles(pkg.packageName);
7448        } catch (InstallerException e) {
7449            Slog.w(TAG, String.valueOf(e));
7450        }
7451    }
7452
7453    private void setInstallAndUpdateTime(PackageParser.Package pkg, long firstInstallTime,
7454            long lastUpdateTime) {
7455        // Set parent install/update time
7456        PackageSetting ps = (PackageSetting) pkg.mExtras;
7457        if (ps != null) {
7458            ps.firstInstallTime = firstInstallTime;
7459            ps.lastUpdateTime = lastUpdateTime;
7460        }
7461        // Set children install/update time
7462        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7463        for (int i = 0; i < childCount; i++) {
7464            PackageParser.Package childPkg = pkg.childPackages.get(i);
7465            ps = (PackageSetting) childPkg.mExtras;
7466            if (ps != null) {
7467                ps.firstInstallTime = firstInstallTime;
7468                ps.lastUpdateTime = lastUpdateTime;
7469            }
7470        }
7471    }
7472
7473    private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file,
7474            PackageParser.Package changingLib) {
7475        if (file.path != null) {
7476            usesLibraryFiles.add(file.path);
7477            return;
7478        }
7479        PackageParser.Package p = mPackages.get(file.apk);
7480        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
7481            // If we are doing this while in the middle of updating a library apk,
7482            // then we need to make sure to use that new apk for determining the
7483            // dependencies here.  (We haven't yet finished committing the new apk
7484            // to the package manager state.)
7485            if (p == null || p.packageName.equals(changingLib.packageName)) {
7486                p = changingLib;
7487            }
7488        }
7489        if (p != null) {
7490            usesLibraryFiles.addAll(p.getAllCodePaths());
7491        }
7492    }
7493
7494    private void updateSharedLibrariesLPw(PackageParser.Package pkg,
7495            PackageParser.Package changingLib) throws PackageManagerException {
7496        if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) {
7497            final ArraySet<String> usesLibraryFiles = new ArraySet<>();
7498            int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0;
7499            for (int i=0; i<N; i++) {
7500                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i));
7501                if (file == null) {
7502                    throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
7503                            "Package " + pkg.packageName + " requires unavailable shared library "
7504                            + pkg.usesLibraries.get(i) + "; failing!");
7505                }
7506                addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
7507            }
7508            N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0;
7509            for (int i=0; i<N; i++) {
7510                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i));
7511                if (file == null) {
7512                    Slog.w(TAG, "Package " + pkg.packageName
7513                            + " desires unavailable shared library "
7514                            + pkg.usesOptionalLibraries.get(i) + "; ignoring!");
7515                } else {
7516                    addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
7517                }
7518            }
7519            N = usesLibraryFiles.size();
7520            if (N > 0) {
7521                pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]);
7522            } else {
7523                pkg.usesLibraryFiles = null;
7524            }
7525        }
7526    }
7527
7528    private static boolean hasString(List<String> list, List<String> which) {
7529        if (list == null) {
7530            return false;
7531        }
7532        for (int i=list.size()-1; i>=0; i--) {
7533            for (int j=which.size()-1; j>=0; j--) {
7534                if (which.get(j).equals(list.get(i))) {
7535                    return true;
7536                }
7537            }
7538        }
7539        return false;
7540    }
7541
7542    private void updateAllSharedLibrariesLPw() {
7543        for (PackageParser.Package pkg : mPackages.values()) {
7544            try {
7545                updateSharedLibrariesLPw(pkg, null);
7546            } catch (PackageManagerException e) {
7547                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
7548            }
7549        }
7550    }
7551
7552    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
7553            PackageParser.Package changingPkg) {
7554        ArrayList<PackageParser.Package> res = null;
7555        for (PackageParser.Package pkg : mPackages.values()) {
7556            if (hasString(pkg.usesLibraries, changingPkg.libraryNames)
7557                    || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) {
7558                if (res == null) {
7559                    res = new ArrayList<PackageParser.Package>();
7560                }
7561                res.add(pkg);
7562                try {
7563                    updateSharedLibrariesLPw(pkg, changingPkg);
7564                } catch (PackageManagerException e) {
7565                    Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
7566                }
7567            }
7568        }
7569        return res;
7570    }
7571
7572    /**
7573     * Derive the value of the {@code cpuAbiOverride} based on the provided
7574     * value and an optional stored value from the package settings.
7575     */
7576    private static String deriveAbiOverride(String abiOverride, PackageSetting settings) {
7577        String cpuAbiOverride = null;
7578
7579        if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) {
7580            cpuAbiOverride = null;
7581        } else if (abiOverride != null) {
7582            cpuAbiOverride = abiOverride;
7583        } else if (settings != null) {
7584            cpuAbiOverride = settings.cpuAbiOverrideString;
7585        }
7586
7587        return cpuAbiOverride;
7588    }
7589
7590    private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg,
7591            final int policyFlags, int scanFlags, long currentTime, UserHandle user)
7592                    throws PackageManagerException {
7593        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage");
7594        // If the package has children and this is the first dive in the function
7595        // we recursively scan the package with the SCAN_CHECK_ONLY flag set to see
7596        // whether all packages (parent and children) would be successfully scanned
7597        // before the actual scan since scanning mutates internal state and we want
7598        // to atomically install the package and its children.
7599        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
7600            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
7601                scanFlags |= SCAN_CHECK_ONLY;
7602            }
7603        } else {
7604            scanFlags &= ~SCAN_CHECK_ONLY;
7605        }
7606
7607        final PackageParser.Package scannedPkg;
7608        try {
7609            // Scan the parent
7610            scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags, currentTime, user);
7611            // Scan the children
7612            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7613            for (int i = 0; i < childCount; i++) {
7614                PackageParser.Package childPkg = pkg.childPackages.get(i);
7615                scanPackageLI(childPkg, policyFlags,
7616                        scanFlags, currentTime, user);
7617            }
7618        } finally {
7619            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7620        }
7621
7622        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
7623            return scanPackageTracedLI(pkg, policyFlags, scanFlags, currentTime, user);
7624        }
7625
7626        return scannedPkg;
7627    }
7628
7629    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, final int policyFlags,
7630            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
7631        boolean success = false;
7632        try {
7633            final PackageParser.Package res = scanPackageDirtyLI(pkg, policyFlags, scanFlags,
7634                    currentTime, user);
7635            success = true;
7636            return res;
7637        } finally {
7638            if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
7639                // DELETE_DATA_ON_FAILURES is only used by frozen paths
7640                destroyAppDataLIF(pkg, UserHandle.USER_ALL,
7641                        StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
7642                destroyAppProfilesLIF(pkg);
7643            }
7644        }
7645    }
7646
7647    /**
7648     * Returns {@code true} if the given file contains code. Otherwise {@code false}.
7649     */
7650    private static boolean apkHasCode(String fileName) {
7651        StrictJarFile jarFile = null;
7652        try {
7653            jarFile = new StrictJarFile(fileName,
7654                    false /*verify*/, false /*signatureSchemeRollbackProtectionsEnforced*/);
7655            return jarFile.findEntry("classes.dex") != null;
7656        } catch (IOException ignore) {
7657        } finally {
7658            try {
7659                jarFile.close();
7660            } catch (IOException ignore) {}
7661        }
7662        return false;
7663    }
7664
7665    /**
7666     * Enforces code policy for the package. This ensures that if an APK has
7667     * declared hasCode="true" in its manifest that the APK actually contains
7668     * code.
7669     *
7670     * @throws PackageManagerException If bytecode could not be found when it should exist
7671     */
7672    private static void enforceCodePolicy(PackageParser.Package pkg)
7673            throws PackageManagerException {
7674        final boolean shouldHaveCode =
7675                (pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) != 0;
7676        if (shouldHaveCode && !apkHasCode(pkg.baseCodePath)) {
7677            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
7678                    "Package " + pkg.baseCodePath + " code is missing");
7679        }
7680
7681        if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
7682            for (int i = 0; i < pkg.splitCodePaths.length; i++) {
7683                final boolean splitShouldHaveCode =
7684                        (pkg.splitFlags[i] & ApplicationInfo.FLAG_HAS_CODE) != 0;
7685                if (splitShouldHaveCode && !apkHasCode(pkg.splitCodePaths[i])) {
7686                    throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
7687                            "Package " + pkg.splitCodePaths[i] + " code is missing");
7688                }
7689            }
7690        }
7691    }
7692
7693    private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg,
7694            final int policyFlags, final int scanFlags, long currentTime, UserHandle user)
7695            throws PackageManagerException {
7696        final File scanFile = new File(pkg.codePath);
7697        if (pkg.applicationInfo.getCodePath() == null ||
7698                pkg.applicationInfo.getResourcePath() == null) {
7699            // Bail out. The resource and code paths haven't been set.
7700            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
7701                    "Code and resource paths haven't been set correctly");
7702        }
7703
7704        // Apply policy
7705        if ((policyFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
7706            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
7707            if (pkg.applicationInfo.isDirectBootAware()) {
7708                // we're direct boot aware; set for all components
7709                for (PackageParser.Service s : pkg.services) {
7710                    s.info.encryptionAware = s.info.directBootAware = true;
7711                }
7712                for (PackageParser.Provider p : pkg.providers) {
7713                    p.info.encryptionAware = p.info.directBootAware = true;
7714                }
7715                for (PackageParser.Activity a : pkg.activities) {
7716                    a.info.encryptionAware = a.info.directBootAware = true;
7717                }
7718                for (PackageParser.Activity r : pkg.receivers) {
7719                    r.info.encryptionAware = r.info.directBootAware = true;
7720                }
7721            }
7722        } else {
7723            // Only allow system apps to be flagged as core apps.
7724            pkg.coreApp = false;
7725            // clear flags not applicable to regular apps
7726            pkg.applicationInfo.privateFlags &=
7727                    ~ApplicationInfo.PRIVATE_FLAG_DEFAULT_TO_DEVICE_PROTECTED_STORAGE;
7728            pkg.applicationInfo.privateFlags &=
7729                    ~ApplicationInfo.PRIVATE_FLAG_DIRECT_BOOT_AWARE;
7730        }
7731        pkg.mTrustedOverlay = (policyFlags&PackageParser.PARSE_TRUSTED_OVERLAY) != 0;
7732
7733        if ((policyFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) {
7734            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
7735        }
7736
7737        if ((policyFlags & PackageParser.PARSE_ENFORCE_CODE) != 0) {
7738            enforceCodePolicy(pkg);
7739        }
7740
7741        if (mCustomResolverComponentName != null &&
7742                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
7743            setUpCustomResolverActivity(pkg);
7744        }
7745
7746        if (pkg.packageName.equals("android")) {
7747            synchronized (mPackages) {
7748                if (mAndroidApplication != null) {
7749                    Slog.w(TAG, "*************************************************");
7750                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
7751                    Slog.w(TAG, " file=" + scanFile);
7752                    Slog.w(TAG, "*************************************************");
7753                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
7754                            "Core android package being redefined.  Skipping.");
7755                }
7756
7757                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
7758                    // Set up information for our fall-back user intent resolution activity.
7759                    mPlatformPackage = pkg;
7760                    pkg.mVersionCode = mSdkVersion;
7761                    mAndroidApplication = pkg.applicationInfo;
7762
7763                    if (!mResolverReplaced) {
7764                        mResolveActivity.applicationInfo = mAndroidApplication;
7765                        mResolveActivity.name = ResolverActivity.class.getName();
7766                        mResolveActivity.packageName = mAndroidApplication.packageName;
7767                        mResolveActivity.processName = "system:ui";
7768                        mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
7769                        mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
7770                        mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
7771                        mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert;
7772                        mResolveActivity.exported = true;
7773                        mResolveActivity.enabled = true;
7774                        mResolveInfo.activityInfo = mResolveActivity;
7775                        mResolveInfo.priority = 0;
7776                        mResolveInfo.preferredOrder = 0;
7777                        mResolveInfo.match = 0;
7778                        mResolveComponentName = new ComponentName(
7779                                mAndroidApplication.packageName, mResolveActivity.name);
7780                    }
7781                }
7782            }
7783        }
7784
7785        if (DEBUG_PACKAGE_SCANNING) {
7786            if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
7787                Log.d(TAG, "Scanning package " + pkg.packageName);
7788        }
7789
7790        synchronized (mPackages) {
7791            if (mPackages.containsKey(pkg.packageName)
7792                    || mSharedLibraries.containsKey(pkg.packageName)) {
7793                throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
7794                        "Application package " + pkg.packageName
7795                                + " already installed.  Skipping duplicate.");
7796            }
7797
7798            // If we're only installing presumed-existing packages, require that the
7799            // scanned APK is both already known and at the path previously established
7800            // for it.  Previously unknown packages we pick up normally, but if we have an
7801            // a priori expectation about this package's install presence, enforce it.
7802            // With a singular exception for new system packages. When an OTA contains
7803            // a new system package, we allow the codepath to change from a system location
7804            // to the user-installed location. If we don't allow this change, any newer,
7805            // user-installed version of the application will be ignored.
7806            if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) {
7807                if (mExpectingBetter.containsKey(pkg.packageName)) {
7808                    logCriticalInfo(Log.WARN,
7809                            "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName);
7810                } else {
7811                    PackageSetting known = mSettings.peekPackageLPr(pkg.packageName);
7812                    if (known != null) {
7813                        if (DEBUG_PACKAGE_SCANNING) {
7814                            Log.d(TAG, "Examining " + pkg.codePath
7815                                    + " and requiring known paths " + known.codePathString
7816                                    + " & " + known.resourcePathString);
7817                        }
7818                        if (!pkg.applicationInfo.getCodePath().equals(known.codePathString)
7819                                || !pkg.applicationInfo.getResourcePath().equals(
7820                                known.resourcePathString)) {
7821                            throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED,
7822                                    "Application package " + pkg.packageName
7823                                            + " found at " + pkg.applicationInfo.getCodePath()
7824                                            + " but expected at " + known.codePathString
7825                                            + "; ignoring.");
7826                        }
7827                    }
7828                }
7829            }
7830        }
7831
7832        // Initialize package source and resource directories
7833        File destCodeFile = new File(pkg.applicationInfo.getCodePath());
7834        File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
7835
7836        SharedUserSetting suid = null;
7837        PackageSetting pkgSetting = null;
7838
7839        if (!isSystemApp(pkg)) {
7840            // Only system apps can use these features.
7841            pkg.mOriginalPackages = null;
7842            pkg.mRealPackage = null;
7843            pkg.mAdoptPermissions = null;
7844        }
7845
7846        // Getting the package setting may have a side-effect, so if we
7847        // are only checking if scan would succeed, stash a copy of the
7848        // old setting to restore at the end.
7849        PackageSetting nonMutatedPs = null;
7850
7851        // writer
7852        synchronized (mPackages) {
7853            if (pkg.mSharedUserId != null) {
7854                suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true);
7855                if (suid == null) {
7856                    throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
7857                            "Creating application package " + pkg.packageName
7858                            + " for shared user failed");
7859                }
7860                if (DEBUG_PACKAGE_SCANNING) {
7861                    if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
7862                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId
7863                                + "): packages=" + suid.packages);
7864                }
7865            }
7866
7867            // Check if we are renaming from an original package name.
7868            PackageSetting origPackage = null;
7869            String realName = null;
7870            if (pkg.mOriginalPackages != null) {
7871                // This package may need to be renamed to a previously
7872                // installed name.  Let's check on that...
7873                final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage);
7874                if (pkg.mOriginalPackages.contains(renamed)) {
7875                    // This package had originally been installed as the
7876                    // original name, and we have already taken care of
7877                    // transitioning to the new one.  Just update the new
7878                    // one to continue using the old name.
7879                    realName = pkg.mRealPackage;
7880                    if (!pkg.packageName.equals(renamed)) {
7881                        // Callers into this function may have already taken
7882                        // care of renaming the package; only do it here if
7883                        // it is not already done.
7884                        pkg.setPackageName(renamed);
7885                    }
7886
7887                } else {
7888                    for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
7889                        if ((origPackage = mSettings.peekPackageLPr(
7890                                pkg.mOriginalPackages.get(i))) != null) {
7891                            // We do have the package already installed under its
7892                            // original name...  should we use it?
7893                            if (!verifyPackageUpdateLPr(origPackage, pkg)) {
7894                                // New package is not compatible with original.
7895                                origPackage = null;
7896                                continue;
7897                            } else if (origPackage.sharedUser != null) {
7898                                // Make sure uid is compatible between packages.
7899                                if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
7900                                    Slog.w(TAG, "Unable to migrate data from " + origPackage.name
7901                                            + " to " + pkg.packageName + ": old uid "
7902                                            + origPackage.sharedUser.name
7903                                            + " differs from " + pkg.mSharedUserId);
7904                                    origPackage = null;
7905                                    continue;
7906                                }
7907                                // TODO: Add case when shared user id is added [b/28144775]
7908                            } else {
7909                                if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
7910                                        + pkg.packageName + " to old name " + origPackage.name);
7911                            }
7912                            break;
7913                        }
7914                    }
7915                }
7916            }
7917
7918            if (mTransferedPackages.contains(pkg.packageName)) {
7919                Slog.w(TAG, "Package " + pkg.packageName
7920                        + " was transferred to another, but its .apk remains");
7921            }
7922
7923            // See comments in nonMutatedPs declaration
7924            if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
7925                PackageSetting foundPs = mSettings.peekPackageLPr(pkg.packageName);
7926                if (foundPs != null) {
7927                    nonMutatedPs = new PackageSetting(foundPs);
7928                }
7929            }
7930
7931            // Just create the setting, don't add it yet. For already existing packages
7932            // the PkgSetting exists already and doesn't have to be created.
7933            pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile,
7934                    destResourceFile, pkg.applicationInfo.nativeLibraryRootDir,
7935                    pkg.applicationInfo.primaryCpuAbi,
7936                    pkg.applicationInfo.secondaryCpuAbi,
7937                    pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags,
7938                    user, false);
7939            if (pkgSetting == null) {
7940                throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
7941                        "Creating application package " + pkg.packageName + " failed");
7942            }
7943
7944            if (pkgSetting.origPackage != null) {
7945                // If we are first transitioning from an original package,
7946                // fix up the new package's name now.  We need to do this after
7947                // looking up the package under its new name, so getPackageLP
7948                // can take care of fiddling things correctly.
7949                pkg.setPackageName(origPackage.name);
7950
7951                // File a report about this.
7952                String msg = "New package " + pkgSetting.realName
7953                        + " renamed to replace old package " + pkgSetting.name;
7954                reportSettingsProblem(Log.WARN, msg);
7955
7956                // Make a note of it.
7957                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
7958                    mTransferedPackages.add(origPackage.name);
7959                }
7960
7961                // No longer need to retain this.
7962                pkgSetting.origPackage = null;
7963            }
7964
7965            if ((scanFlags & SCAN_CHECK_ONLY) == 0 && realName != null) {
7966                // Make a note of it.
7967                mTransferedPackages.add(pkg.packageName);
7968            }
7969
7970            if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) {
7971                pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
7972            }
7973
7974            if ((policyFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
7975                // Check all shared libraries and map to their actual file path.
7976                // We only do this here for apps not on a system dir, because those
7977                // are the only ones that can fail an install due to this.  We
7978                // will take care of the system apps by updating all of their
7979                // library paths after the scan is done.
7980                updateSharedLibrariesLPw(pkg, null);
7981            }
7982
7983            if (mFoundPolicyFile) {
7984                SELinuxMMAC.assignSeinfoValue(pkg);
7985            }
7986
7987            pkg.applicationInfo.uid = pkgSetting.appId;
7988            pkg.mExtras = pkgSetting;
7989            if (shouldCheckUpgradeKeySetLP(pkgSetting, scanFlags)) {
7990                if (checkUpgradeKeySetLP(pkgSetting, pkg)) {
7991                    // We just determined the app is signed correctly, so bring
7992                    // over the latest parsed certs.
7993                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
7994                } else {
7995                    if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
7996                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
7997                                "Package " + pkg.packageName + " upgrade keys do not match the "
7998                                + "previously installed version");
7999                    } else {
8000                        pkgSetting.signatures.mSignatures = pkg.mSignatures;
8001                        String msg = "System package " + pkg.packageName
8002                            + " signature changed; retaining data.";
8003                        reportSettingsProblem(Log.WARN, msg);
8004                    }
8005                }
8006            } else {
8007                try {
8008                    verifySignaturesLP(pkgSetting, pkg);
8009                    // We just determined the app is signed correctly, so bring
8010                    // over the latest parsed certs.
8011                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
8012                } catch (PackageManagerException e) {
8013                    if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
8014                        throw e;
8015                    }
8016                    // The signature has changed, but this package is in the system
8017                    // image...  let's recover!
8018                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
8019                    // However...  if this package is part of a shared user, but it
8020                    // doesn't match the signature of the shared user, let's fail.
8021                    // What this means is that you can't change the signatures
8022                    // associated with an overall shared user, which doesn't seem all
8023                    // that unreasonable.
8024                    if (pkgSetting.sharedUser != null) {
8025                        if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
8026                                              pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
8027                            throw new PackageManagerException(
8028                                    INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
8029                                            "Signature mismatch for shared user: "
8030                                            + pkgSetting.sharedUser);
8031                        }
8032                    }
8033                    // File a report about this.
8034                    String msg = "System package " + pkg.packageName
8035                        + " signature changed; retaining data.";
8036                    reportSettingsProblem(Log.WARN, msg);
8037                }
8038            }
8039            // Verify that this new package doesn't have any content providers
8040            // that conflict with existing packages.  Only do this if the
8041            // package isn't already installed, since we don't want to break
8042            // things that are installed.
8043            if ((scanFlags & SCAN_NEW_INSTALL) != 0) {
8044                final int N = pkg.providers.size();
8045                int i;
8046                for (i=0; i<N; i++) {
8047                    PackageParser.Provider p = pkg.providers.get(i);
8048                    if (p.info.authority != null) {
8049                        String names[] = p.info.authority.split(";");
8050                        for (int j = 0; j < names.length; j++) {
8051                            if (mProvidersByAuthority.containsKey(names[j])) {
8052                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
8053                                final String otherPackageName =
8054                                        ((other != null && other.getComponentName() != null) ?
8055                                                other.getComponentName().getPackageName() : "?");
8056                                throw new PackageManagerException(
8057                                        INSTALL_FAILED_CONFLICTING_PROVIDER,
8058                                                "Can't install because provider name " + names[j]
8059                                                + " (in package " + pkg.applicationInfo.packageName
8060                                                + ") is already used by " + otherPackageName);
8061                            }
8062                        }
8063                    }
8064                }
8065            }
8066
8067            if ((scanFlags & SCAN_CHECK_ONLY) == 0 && pkg.mAdoptPermissions != null) {
8068                // This package wants to adopt ownership of permissions from
8069                // another package.
8070                for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
8071                    final String origName = pkg.mAdoptPermissions.get(i);
8072                    final PackageSetting orig = mSettings.peekPackageLPr(origName);
8073                    if (orig != null) {
8074                        if (verifyPackageUpdateLPr(orig, pkg)) {
8075                            Slog.i(TAG, "Adopting permissions from " + origName + " to "
8076                                    + pkg.packageName);
8077                            mSettings.transferPermissionsLPw(origName, pkg.packageName);
8078                        }
8079                    }
8080                }
8081            }
8082        }
8083
8084        final String pkgName = pkg.packageName;
8085
8086        final long scanFileTime = scanFile.lastModified();
8087        final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0;
8088        pkg.applicationInfo.processName = fixProcessName(
8089                pkg.applicationInfo.packageName,
8090                pkg.applicationInfo.processName,
8091                pkg.applicationInfo.uid);
8092
8093        if (pkg != mPlatformPackage) {
8094            // Get all of our default paths setup
8095            pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM);
8096        }
8097
8098        final String path = scanFile.getPath();
8099        final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
8100
8101        if ((scanFlags & SCAN_NEW_INSTALL) == 0) {
8102            derivePackageAbi(pkg, scanFile, cpuAbiOverride, true /* extract libs */);
8103
8104            // Some system apps still use directory structure for native libraries
8105            // in which case we might end up not detecting abi solely based on apk
8106            // structure. Try to detect abi based on directory structure.
8107            if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() &&
8108                    pkg.applicationInfo.primaryCpuAbi == null) {
8109                setBundledAppAbisAndRoots(pkg, pkgSetting);
8110                setNativeLibraryPaths(pkg);
8111            }
8112
8113        } else {
8114            if ((scanFlags & SCAN_MOVE) != 0) {
8115                // We haven't run dex-opt for this move (since we've moved the compiled output too)
8116                // but we already have this packages package info in the PackageSetting. We just
8117                // use that and derive the native library path based on the new codepath.
8118                pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString;
8119                pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString;
8120            }
8121
8122            // Set native library paths again. For moves, the path will be updated based on the
8123            // ABIs we've determined above. For non-moves, the path will be updated based on the
8124            // ABIs we determined during compilation, but the path will depend on the final
8125            // package path (after the rename away from the stage path).
8126            setNativeLibraryPaths(pkg);
8127        }
8128
8129        // This is a special case for the "system" package, where the ABI is
8130        // dictated by the zygote configuration (and init.rc). We should keep track
8131        // of this ABI so that we can deal with "normal" applications that run under
8132        // the same UID correctly.
8133        if (mPlatformPackage == pkg) {
8134            pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
8135                    Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
8136        }
8137
8138        // If there's a mismatch between the abi-override in the package setting
8139        // and the abiOverride specified for the install. Warn about this because we
8140        // would've already compiled the app without taking the package setting into
8141        // account.
8142        if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) {
8143            if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) {
8144                Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride +
8145                        " for package " + pkg.packageName);
8146            }
8147        }
8148
8149        pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
8150        pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
8151        pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
8152
8153        // Copy the derived override back to the parsed package, so that we can
8154        // update the package settings accordingly.
8155        pkg.cpuAbiOverride = cpuAbiOverride;
8156
8157        if (DEBUG_ABI_SELECTION) {
8158            Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName
8159                    + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
8160                    + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
8161        }
8162
8163        // Push the derived path down into PackageSettings so we know what to
8164        // clean up at uninstall time.
8165        pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
8166
8167        if (DEBUG_ABI_SELECTION) {
8168            Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
8169                    " primary=" + pkg.applicationInfo.primaryCpuAbi +
8170                    " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
8171        }
8172
8173        if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
8174            // We don't do this here during boot because we can do it all
8175            // at once after scanning all existing packages.
8176            //
8177            // We also do this *before* we perform dexopt on this package, so that
8178            // we can avoid redundant dexopts, and also to make sure we've got the
8179            // code and package path correct.
8180            adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages,
8181                    pkg, true /* boot complete */);
8182        }
8183
8184        if (mFactoryTest && pkg.requestedPermissions.contains(
8185                android.Manifest.permission.FACTORY_TEST)) {
8186            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
8187        }
8188
8189        ArrayList<PackageParser.Package> clientLibPkgs = null;
8190
8191        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
8192            if (nonMutatedPs != null) {
8193                synchronized (mPackages) {
8194                    mSettings.mPackages.put(nonMutatedPs.name, nonMutatedPs);
8195                }
8196            }
8197            return pkg;
8198        }
8199
8200        // Only privileged apps and updated privileged apps can add child packages.
8201        if (pkg.childPackages != null && !pkg.childPackages.isEmpty()) {
8202            if ((policyFlags & PARSE_IS_PRIVILEGED) == 0) {
8203                throw new PackageManagerException("Only privileged apps and updated "
8204                        + "privileged apps can add child packages. Ignoring package "
8205                        + pkg.packageName);
8206            }
8207            final int childCount = pkg.childPackages.size();
8208            for (int i = 0; i < childCount; i++) {
8209                PackageParser.Package childPkg = pkg.childPackages.get(i);
8210                if (mSettings.hasOtherDisabledSystemPkgWithChildLPr(pkg.packageName,
8211                        childPkg.packageName)) {
8212                    throw new PackageManagerException("Cannot override a child package of "
8213                            + "another disabled system app. Ignoring package " + pkg.packageName);
8214                }
8215            }
8216        }
8217
8218        // writer
8219        synchronized (mPackages) {
8220            if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
8221                // Only system apps can add new shared libraries.
8222                if (pkg.libraryNames != null) {
8223                    for (int i=0; i<pkg.libraryNames.size(); i++) {
8224                        String name = pkg.libraryNames.get(i);
8225                        boolean allowed = false;
8226                        if (pkg.isUpdatedSystemApp()) {
8227                            // New library entries can only be added through the
8228                            // system image.  This is important to get rid of a lot
8229                            // of nasty edge cases: for example if we allowed a non-
8230                            // system update of the app to add a library, then uninstalling
8231                            // the update would make the library go away, and assumptions
8232                            // we made such as through app install filtering would now
8233                            // have allowed apps on the device which aren't compatible
8234                            // with it.  Better to just have the restriction here, be
8235                            // conservative, and create many fewer cases that can negatively
8236                            // impact the user experience.
8237                            final PackageSetting sysPs = mSettings
8238                                    .getDisabledSystemPkgLPr(pkg.packageName);
8239                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
8240                                for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) {
8241                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
8242                                        allowed = true;
8243                                        break;
8244                                    }
8245                                }
8246                            }
8247                        } else {
8248                            allowed = true;
8249                        }
8250                        if (allowed) {
8251                            if (!mSharedLibraries.containsKey(name)) {
8252                                mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName));
8253                            } else if (!name.equals(pkg.packageName)) {
8254                                Slog.w(TAG, "Package " + pkg.packageName + " library "
8255                                        + name + " already exists; skipping");
8256                            }
8257                        } else {
8258                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
8259                                    + name + " that is not declared on system image; skipping");
8260                        }
8261                    }
8262                    if ((scanFlags & SCAN_BOOTING) == 0) {
8263                        // If we are not booting, we need to update any applications
8264                        // that are clients of our shared library.  If we are booting,
8265                        // this will all be done once the scan is complete.
8266                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
8267                    }
8268                }
8269            }
8270        }
8271
8272        if ((scanFlags & SCAN_BOOTING) != 0) {
8273            // No apps can run during boot scan, so they don't need to be frozen
8274        } else if ((scanFlags & SCAN_DONT_KILL_APP) != 0) {
8275            // Caller asked to not kill app, so it's probably not frozen
8276        } else if ((scanFlags & SCAN_IGNORE_FROZEN) != 0) {
8277            // Caller asked us to ignore frozen check for some reason; they
8278            // probably didn't know the package name
8279        } else {
8280            // We're doing major surgery on this package, so it better be frozen
8281            // right now to keep it from launching
8282            checkPackageFrozen(pkgName);
8283        }
8284
8285        // Also need to kill any apps that are dependent on the library.
8286        if (clientLibPkgs != null) {
8287            for (int i=0; i<clientLibPkgs.size(); i++) {
8288                PackageParser.Package clientPkg = clientLibPkgs.get(i);
8289                killApplication(clientPkg.applicationInfo.packageName,
8290                        clientPkg.applicationInfo.uid, "update lib");
8291            }
8292        }
8293
8294        // Make sure we're not adding any bogus keyset info
8295        KeySetManagerService ksms = mSettings.mKeySetManagerService;
8296        ksms.assertScannedPackageValid(pkg);
8297
8298        // writer
8299        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
8300
8301        boolean createIdmapFailed = false;
8302        synchronized (mPackages) {
8303            // We don't expect installation to fail beyond this point
8304
8305            // Add the new setting to mSettings
8306            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
8307            // Add the new setting to mPackages
8308            mPackages.put(pkg.applicationInfo.packageName, pkg);
8309            // Make sure we don't accidentally delete its data.
8310            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
8311            while (iter.hasNext()) {
8312                PackageCleanItem item = iter.next();
8313                if (pkgName.equals(item.packageName)) {
8314                    iter.remove();
8315                }
8316            }
8317
8318            // Take care of first install / last update times.
8319            if (currentTime != 0) {
8320                if (pkgSetting.firstInstallTime == 0) {
8321                    pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
8322                } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) {
8323                    pkgSetting.lastUpdateTime = currentTime;
8324                }
8325            } else if (pkgSetting.firstInstallTime == 0) {
8326                // We need *something*.  Take time time stamp of the file.
8327                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
8328            } else if ((policyFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
8329                if (scanFileTime != pkgSetting.timeStamp) {
8330                    // A package on the system image has changed; consider this
8331                    // to be an update.
8332                    pkgSetting.lastUpdateTime = scanFileTime;
8333                }
8334            }
8335
8336            // Add the package's KeySets to the global KeySetManagerService
8337            ksms.addScannedPackageLPw(pkg);
8338
8339            int N = pkg.providers.size();
8340            StringBuilder r = null;
8341            int i;
8342            for (i=0; i<N; i++) {
8343                PackageParser.Provider p = pkg.providers.get(i);
8344                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
8345                        p.info.processName, pkg.applicationInfo.uid);
8346                mProviders.addProvider(p);
8347                p.syncable = p.info.isSyncable;
8348                if (p.info.authority != null) {
8349                    String names[] = p.info.authority.split(";");
8350                    p.info.authority = null;
8351                    for (int j = 0; j < names.length; j++) {
8352                        if (j == 1 && p.syncable) {
8353                            // We only want the first authority for a provider to possibly be
8354                            // syncable, so if we already added this provider using a different
8355                            // authority clear the syncable flag. We copy the provider before
8356                            // changing it because the mProviders object contains a reference
8357                            // to a provider that we don't want to change.
8358                            // Only do this for the second authority since the resulting provider
8359                            // object can be the same for all future authorities for this provider.
8360                            p = new PackageParser.Provider(p);
8361                            p.syncable = false;
8362                        }
8363                        if (!mProvidersByAuthority.containsKey(names[j])) {
8364                            mProvidersByAuthority.put(names[j], p);
8365                            if (p.info.authority == null) {
8366                                p.info.authority = names[j];
8367                            } else {
8368                                p.info.authority = p.info.authority + ";" + names[j];
8369                            }
8370                            if (DEBUG_PACKAGE_SCANNING) {
8371                                if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
8372                                    Log.d(TAG, "Registered content provider: " + names[j]
8373                                            + ", className = " + p.info.name + ", isSyncable = "
8374                                            + p.info.isSyncable);
8375                            }
8376                        } else {
8377                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
8378                            Slog.w(TAG, "Skipping provider name " + names[j] +
8379                                    " (in package " + pkg.applicationInfo.packageName +
8380                                    "): name already used by "
8381                                    + ((other != null && other.getComponentName() != null)
8382                                            ? other.getComponentName().getPackageName() : "?"));
8383                        }
8384                    }
8385                }
8386                if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8387                    if (r == null) {
8388                        r = new StringBuilder(256);
8389                    } else {
8390                        r.append(' ');
8391                    }
8392                    r.append(p.info.name);
8393                }
8394            }
8395            if (r != null) {
8396                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
8397            }
8398
8399            N = pkg.services.size();
8400            r = null;
8401            for (i=0; i<N; i++) {
8402                PackageParser.Service s = pkg.services.get(i);
8403                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
8404                        s.info.processName, pkg.applicationInfo.uid);
8405                mServices.addService(s);
8406                if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8407                    if (r == null) {
8408                        r = new StringBuilder(256);
8409                    } else {
8410                        r.append(' ');
8411                    }
8412                    r.append(s.info.name);
8413                }
8414            }
8415            if (r != null) {
8416                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
8417            }
8418
8419            N = pkg.receivers.size();
8420            r = null;
8421            for (i=0; i<N; i++) {
8422                PackageParser.Activity a = pkg.receivers.get(i);
8423                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
8424                        a.info.processName, pkg.applicationInfo.uid);
8425                mReceivers.addActivity(a, "receiver");
8426                if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8427                    if (r == null) {
8428                        r = new StringBuilder(256);
8429                    } else {
8430                        r.append(' ');
8431                    }
8432                    r.append(a.info.name);
8433                }
8434            }
8435            if (r != null) {
8436                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
8437            }
8438
8439            N = pkg.activities.size();
8440            r = null;
8441            for (i=0; i<N; i++) {
8442                PackageParser.Activity a = pkg.activities.get(i);
8443                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
8444                        a.info.processName, pkg.applicationInfo.uid);
8445                mActivities.addActivity(a, "activity");
8446                if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8447                    if (r == null) {
8448                        r = new StringBuilder(256);
8449                    } else {
8450                        r.append(' ');
8451                    }
8452                    r.append(a.info.name);
8453                }
8454            }
8455            if (r != null) {
8456                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
8457            }
8458
8459            N = pkg.permissionGroups.size();
8460            r = null;
8461            for (i=0; i<N; i++) {
8462                PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
8463                PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
8464                if (cur == null) {
8465                    mPermissionGroups.put(pg.info.name, pg);
8466                    if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8467                        if (r == null) {
8468                            r = new StringBuilder(256);
8469                        } else {
8470                            r.append(' ');
8471                        }
8472                        r.append(pg.info.name);
8473                    }
8474                } else {
8475                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
8476                            + pg.info.packageName + " ignored: original from "
8477                            + cur.info.packageName);
8478                    if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8479                        if (r == null) {
8480                            r = new StringBuilder(256);
8481                        } else {
8482                            r.append(' ');
8483                        }
8484                        r.append("DUP:");
8485                        r.append(pg.info.name);
8486                    }
8487                }
8488            }
8489            if (r != null) {
8490                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permission Groups: " + r);
8491            }
8492
8493            N = pkg.permissions.size();
8494            r = null;
8495            for (i=0; i<N; i++) {
8496                PackageParser.Permission p = pkg.permissions.get(i);
8497
8498                // Assume by default that we did not install this permission into the system.
8499                p.info.flags &= ~PermissionInfo.FLAG_INSTALLED;
8500
8501                // Now that permission groups have a special meaning, we ignore permission
8502                // groups for legacy apps to prevent unexpected behavior. In particular,
8503                // permissions for one app being granted to someone just becase they happen
8504                // to be in a group defined by another app (before this had no implications).
8505                if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) {
8506                    p.group = mPermissionGroups.get(p.info.group);
8507                    // Warn for a permission in an unknown group.
8508                    if (p.info.group != null && p.group == null) {
8509                        Slog.w(TAG, "Permission " + p.info.name + " from package "
8510                                + p.info.packageName + " in an unknown group " + p.info.group);
8511                    }
8512                }
8513
8514                ArrayMap<String, BasePermission> permissionMap =
8515                        p.tree ? mSettings.mPermissionTrees
8516                                : mSettings.mPermissions;
8517                BasePermission bp = permissionMap.get(p.info.name);
8518
8519                // Allow system apps to redefine non-system permissions
8520                if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) {
8521                    final boolean currentOwnerIsSystem = (bp.perm != null
8522                            && isSystemApp(bp.perm.owner));
8523                    if (isSystemApp(p.owner)) {
8524                        if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) {
8525                            // It's a built-in permission and no owner, take ownership now
8526                            bp.packageSetting = pkgSetting;
8527                            bp.perm = p;
8528                            bp.uid = pkg.applicationInfo.uid;
8529                            bp.sourcePackage = p.info.packageName;
8530                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
8531                        } else if (!currentOwnerIsSystem) {
8532                            String msg = "New decl " + p.owner + " of permission  "
8533                                    + p.info.name + " is system; overriding " + bp.sourcePackage;
8534                            reportSettingsProblem(Log.WARN, msg);
8535                            bp = null;
8536                        }
8537                    }
8538                }
8539
8540                if (bp == null) {
8541                    bp = new BasePermission(p.info.name, p.info.packageName,
8542                            BasePermission.TYPE_NORMAL);
8543                    permissionMap.put(p.info.name, bp);
8544                }
8545
8546                if (bp.perm == null) {
8547                    if (bp.sourcePackage == null
8548                            || bp.sourcePackage.equals(p.info.packageName)) {
8549                        BasePermission tree = findPermissionTreeLP(p.info.name);
8550                        if (tree == null
8551                                || tree.sourcePackage.equals(p.info.packageName)) {
8552                            bp.packageSetting = pkgSetting;
8553                            bp.perm = p;
8554                            bp.uid = pkg.applicationInfo.uid;
8555                            bp.sourcePackage = p.info.packageName;
8556                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
8557                            if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8558                                if (r == null) {
8559                                    r = new StringBuilder(256);
8560                                } else {
8561                                    r.append(' ');
8562                                }
8563                                r.append(p.info.name);
8564                            }
8565                        } else {
8566                            Slog.w(TAG, "Permission " + p.info.name + " from package "
8567                                    + p.info.packageName + " ignored: base tree "
8568                                    + tree.name + " is from package "
8569                                    + tree.sourcePackage);
8570                        }
8571                    } else {
8572                        Slog.w(TAG, "Permission " + p.info.name + " from package "
8573                                + p.info.packageName + " ignored: original from "
8574                                + bp.sourcePackage);
8575                    }
8576                } else if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8577                    if (r == null) {
8578                        r = new StringBuilder(256);
8579                    } else {
8580                        r.append(' ');
8581                    }
8582                    r.append("DUP:");
8583                    r.append(p.info.name);
8584                }
8585                if (bp.perm == p) {
8586                    bp.protectionLevel = p.info.protectionLevel;
8587                }
8588            }
8589
8590            if (r != null) {
8591                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permissions: " + r);
8592            }
8593
8594            N = pkg.instrumentation.size();
8595            r = null;
8596            for (i=0; i<N; i++) {
8597                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
8598                a.info.packageName = pkg.applicationInfo.packageName;
8599                a.info.sourceDir = pkg.applicationInfo.sourceDir;
8600                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
8601                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
8602                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
8603                a.info.dataDir = pkg.applicationInfo.dataDir;
8604                a.info.deviceProtectedDataDir = pkg.applicationInfo.deviceProtectedDataDir;
8605                a.info.credentialProtectedDataDir = pkg.applicationInfo.credentialProtectedDataDir;
8606
8607                // TODO: Update instrumentation.nativeLibraryDir as well ? Does it
8608                // need other information about the application, like the ABI and what not ?
8609                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
8610                mInstrumentation.put(a.getComponentName(), a);
8611                if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8612                    if (r == null) {
8613                        r = new StringBuilder(256);
8614                    } else {
8615                        r.append(' ');
8616                    }
8617                    r.append(a.info.name);
8618                }
8619            }
8620            if (r != null) {
8621                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
8622            }
8623
8624            if (pkg.protectedBroadcasts != null) {
8625                N = pkg.protectedBroadcasts.size();
8626                for (i=0; i<N; i++) {
8627                    mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
8628                }
8629            }
8630
8631            pkgSetting.setTimeStamp(scanFileTime);
8632
8633            // Create idmap files for pairs of (packages, overlay packages).
8634            // Note: "android", ie framework-res.apk, is handled by native layers.
8635            if (pkg.mOverlayTarget != null) {
8636                // This is an overlay package.
8637                if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) {
8638                    if (!mOverlays.containsKey(pkg.mOverlayTarget)) {
8639                        mOverlays.put(pkg.mOverlayTarget,
8640                                new ArrayMap<String, PackageParser.Package>());
8641                    }
8642                    ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget);
8643                    map.put(pkg.packageName, pkg);
8644                    PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget);
8645                    if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) {
8646                        createIdmapFailed = true;
8647                    }
8648                }
8649            } else if (mOverlays.containsKey(pkg.packageName) &&
8650                    !pkg.packageName.equals("android")) {
8651                // This is a regular package, with one or more known overlay packages.
8652                createIdmapsForPackageLI(pkg);
8653            }
8654        }
8655
8656        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8657
8658        if (createIdmapFailed) {
8659            throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
8660                    "scanPackageLI failed to createIdmap");
8661        }
8662        return pkg;
8663    }
8664
8665    /**
8666     * Derive the ABI of a non-system package located at {@code scanFile}. This information
8667     * is derived purely on the basis of the contents of {@code scanFile} and
8668     * {@code cpuAbiOverride}.
8669     *
8670     * If {@code extractLibs} is true, native libraries are extracted from the app if required.
8671     */
8672    private void derivePackageAbi(PackageParser.Package pkg, File scanFile,
8673                                 String cpuAbiOverride, boolean extractLibs)
8674            throws PackageManagerException {
8675        // TODO: We can probably be smarter about this stuff. For installed apps,
8676        // we can calculate this information at install time once and for all. For
8677        // system apps, we can probably assume that this information doesn't change
8678        // after the first boot scan. As things stand, we do lots of unnecessary work.
8679
8680        // Give ourselves some initial paths; we'll come back for another
8681        // pass once we've determined ABI below.
8682        setNativeLibraryPaths(pkg);
8683
8684        // We would never need to extract libs for forward-locked and external packages,
8685        // since the container service will do it for us. We shouldn't attempt to
8686        // extract libs from system app when it was not updated.
8687        if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() ||
8688                (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) {
8689            extractLibs = false;
8690        }
8691
8692        final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
8693        final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
8694
8695        NativeLibraryHelper.Handle handle = null;
8696        try {
8697            handle = NativeLibraryHelper.Handle.create(pkg);
8698            // TODO(multiArch): This can be null for apps that didn't go through the
8699            // usual installation process. We can calculate it again, like we
8700            // do during install time.
8701            //
8702            // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
8703            // unnecessary.
8704            final File nativeLibraryRoot = new File(nativeLibraryRootStr);
8705
8706            // Null out the abis so that they can be recalculated.
8707            pkg.applicationInfo.primaryCpuAbi = null;
8708            pkg.applicationInfo.secondaryCpuAbi = null;
8709            if (isMultiArch(pkg.applicationInfo)) {
8710                // Warn if we've set an abiOverride for multi-lib packages..
8711                // By definition, we need to copy both 32 and 64 bit libraries for
8712                // such packages.
8713                if (pkg.cpuAbiOverride != null
8714                        && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
8715                    Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
8716                }
8717
8718                int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
8719                int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
8720                if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
8721                    if (extractLibs) {
8722                        abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
8723                                nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
8724                                useIsaSpecificSubdirs);
8725                    } else {
8726                        abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
8727                    }
8728                }
8729
8730                maybeThrowExceptionForMultiArchCopy(
8731                        "Error unpackaging 32 bit native libs for multiarch app.", abi32);
8732
8733                if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
8734                    if (extractLibs) {
8735                        abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
8736                                nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
8737                                useIsaSpecificSubdirs);
8738                    } else {
8739                        abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
8740                    }
8741                }
8742
8743                maybeThrowExceptionForMultiArchCopy(
8744                        "Error unpackaging 64 bit native libs for multiarch app.", abi64);
8745
8746                if (abi64 >= 0) {
8747                    pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
8748                }
8749
8750                if (abi32 >= 0) {
8751                    final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
8752                    if (abi64 >= 0) {
8753                        if (pkg.use32bitAbi) {
8754                            pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi;
8755                            pkg.applicationInfo.primaryCpuAbi = abi;
8756                        } else {
8757                            pkg.applicationInfo.secondaryCpuAbi = abi;
8758                        }
8759                    } else {
8760                        pkg.applicationInfo.primaryCpuAbi = abi;
8761                    }
8762                }
8763
8764            } else {
8765                String[] abiList = (cpuAbiOverride != null) ?
8766                        new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
8767
8768                // Enable gross and lame hacks for apps that are built with old
8769                // SDK tools. We must scan their APKs for renderscript bitcode and
8770                // not launch them if it's present. Don't bother checking on devices
8771                // that don't have 64 bit support.
8772                boolean needsRenderScriptOverride = false;
8773                if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
8774                        NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
8775                    abiList = Build.SUPPORTED_32_BIT_ABIS;
8776                    needsRenderScriptOverride = true;
8777                }
8778
8779                final int copyRet;
8780                if (extractLibs) {
8781                    copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
8782                            nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
8783                } else {
8784                    copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
8785                }
8786
8787                if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
8788                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
8789                            "Error unpackaging native libs for app, errorCode=" + copyRet);
8790                }
8791
8792                if (copyRet >= 0) {
8793                    pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
8794                } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
8795                    pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
8796                } else if (needsRenderScriptOverride) {
8797                    pkg.applicationInfo.primaryCpuAbi = abiList[0];
8798                }
8799            }
8800        } catch (IOException ioe) {
8801            Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
8802        } finally {
8803            IoUtils.closeQuietly(handle);
8804        }
8805
8806        // Now that we've calculated the ABIs and determined if it's an internal app,
8807        // we will go ahead and populate the nativeLibraryPath.
8808        setNativeLibraryPaths(pkg);
8809    }
8810
8811    /**
8812     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
8813     * i.e, so that all packages can be run inside a single process if required.
8814     *
8815     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
8816     * this function will either try and make the ABI for all packages in {@code packagesForUser}
8817     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
8818     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
8819     * updating a package that belongs to a shared user.
8820     *
8821     * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
8822     * adds unnecessary complexity.
8823     */
8824    private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser,
8825            PackageParser.Package scannedPackage, boolean bootComplete) {
8826        String requiredInstructionSet = null;
8827        if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
8828            requiredInstructionSet = VMRuntime.getInstructionSet(
8829                     scannedPackage.applicationInfo.primaryCpuAbi);
8830        }
8831
8832        PackageSetting requirer = null;
8833        for (PackageSetting ps : packagesForUser) {
8834            // If packagesForUser contains scannedPackage, we skip it. This will happen
8835            // when scannedPackage is an update of an existing package. Without this check,
8836            // we will never be able to change the ABI of any package belonging to a shared
8837            // user, even if it's compatible with other packages.
8838            if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
8839                if (ps.primaryCpuAbiString == null) {
8840                    continue;
8841                }
8842
8843                final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
8844                if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
8845                    // We have a mismatch between instruction sets (say arm vs arm64) warn about
8846                    // this but there's not much we can do.
8847                    String errorMessage = "Instruction set mismatch, "
8848                            + ((requirer == null) ? "[caller]" : requirer)
8849                            + " requires " + requiredInstructionSet + " whereas " + ps
8850                            + " requires " + instructionSet;
8851                    Slog.w(TAG, errorMessage);
8852                }
8853
8854                if (requiredInstructionSet == null) {
8855                    requiredInstructionSet = instructionSet;
8856                    requirer = ps;
8857                }
8858            }
8859        }
8860
8861        if (requiredInstructionSet != null) {
8862            String adjustedAbi;
8863            if (requirer != null) {
8864                // requirer != null implies that either scannedPackage was null or that scannedPackage
8865                // did not require an ABI, in which case we have to adjust scannedPackage to match
8866                // the ABI of the set (which is the same as requirer's ABI)
8867                adjustedAbi = requirer.primaryCpuAbiString;
8868                if (scannedPackage != null) {
8869                    scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
8870                }
8871            } else {
8872                // requirer == null implies that we're updating all ABIs in the set to
8873                // match scannedPackage.
8874                adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
8875            }
8876
8877            for (PackageSetting ps : packagesForUser) {
8878                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
8879                    if (ps.primaryCpuAbiString != null) {
8880                        continue;
8881                    }
8882
8883                    ps.primaryCpuAbiString = adjustedAbi;
8884                    if (ps.pkg != null && ps.pkg.applicationInfo != null &&
8885                            !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) {
8886                        ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
8887                        Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi
8888                                + " (requirer="
8889                                + (requirer == null ? "null" : requirer.pkg.packageName)
8890                                + ", scannedPackage="
8891                                + (scannedPackage != null ? scannedPackage.packageName : "null")
8892                                + ")");
8893                        try {
8894                            mInstaller.rmdex(ps.codePathString,
8895                                    getDexCodeInstructionSet(getPreferredInstructionSet()));
8896                        } catch (InstallerException ignored) {
8897                        }
8898                    }
8899                }
8900            }
8901        }
8902    }
8903
8904    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
8905        synchronized (mPackages) {
8906            mResolverReplaced = true;
8907            // Set up information for custom user intent resolution activity.
8908            mResolveActivity.applicationInfo = pkg.applicationInfo;
8909            mResolveActivity.name = mCustomResolverComponentName.getClassName();
8910            mResolveActivity.packageName = pkg.applicationInfo.packageName;
8911            mResolveActivity.processName = pkg.applicationInfo.packageName;
8912            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
8913            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
8914                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
8915            mResolveActivity.theme = 0;
8916            mResolveActivity.exported = true;
8917            mResolveActivity.enabled = true;
8918            mResolveInfo.activityInfo = mResolveActivity;
8919            mResolveInfo.priority = 0;
8920            mResolveInfo.preferredOrder = 0;
8921            mResolveInfo.match = 0;
8922            mResolveComponentName = mCustomResolverComponentName;
8923            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
8924                    mResolveComponentName);
8925        }
8926    }
8927
8928    private void setUpEphemeralInstallerActivityLP(ComponentName installerComponent) {
8929        final PackageParser.Package pkg = mPackages.get(installerComponent.getPackageName());
8930
8931        // Set up information for ephemeral installer activity
8932        mEphemeralInstallerActivity.applicationInfo = pkg.applicationInfo;
8933        mEphemeralInstallerActivity.name = mEphemeralInstallerComponent.getClassName();
8934        mEphemeralInstallerActivity.packageName = pkg.applicationInfo.packageName;
8935        mEphemeralInstallerActivity.processName = pkg.applicationInfo.packageName;
8936        mEphemeralInstallerActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
8937        mEphemeralInstallerActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
8938                ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
8939        mEphemeralInstallerActivity.theme = 0;
8940        mEphemeralInstallerActivity.exported = true;
8941        mEphemeralInstallerActivity.enabled = true;
8942        mEphemeralInstallerInfo.activityInfo = mEphemeralInstallerActivity;
8943        mEphemeralInstallerInfo.priority = 0;
8944        mEphemeralInstallerInfo.preferredOrder = 0;
8945        mEphemeralInstallerInfo.match = 0;
8946
8947        if (DEBUG_EPHEMERAL) {
8948            Slog.d(TAG, "Set ephemeral installer activity: " + mEphemeralInstallerComponent);
8949        }
8950    }
8951
8952    private static String calculateBundledApkRoot(final String codePathString) {
8953        final File codePath = new File(codePathString);
8954        final File codeRoot;
8955        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
8956            codeRoot = Environment.getRootDirectory();
8957        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
8958            codeRoot = Environment.getOemDirectory();
8959        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
8960            codeRoot = Environment.getVendorDirectory();
8961        } else {
8962            // Unrecognized code path; take its top real segment as the apk root:
8963            // e.g. /something/app/blah.apk => /something
8964            try {
8965                File f = codePath.getCanonicalFile();
8966                File parent = f.getParentFile();    // non-null because codePath is a file
8967                File tmp;
8968                while ((tmp = parent.getParentFile()) != null) {
8969                    f = parent;
8970                    parent = tmp;
8971                }
8972                codeRoot = f;
8973                Slog.w(TAG, "Unrecognized code path "
8974                        + codePath + " - using " + codeRoot);
8975            } catch (IOException e) {
8976                // Can't canonicalize the code path -- shenanigans?
8977                Slog.w(TAG, "Can't canonicalize code path " + codePath);
8978                return Environment.getRootDirectory().getPath();
8979            }
8980        }
8981        return codeRoot.getPath();
8982    }
8983
8984    /**
8985     * Derive and set the location of native libraries for the given package,
8986     * which varies depending on where and how the package was installed.
8987     */
8988    private void setNativeLibraryPaths(PackageParser.Package pkg) {
8989        final ApplicationInfo info = pkg.applicationInfo;
8990        final String codePath = pkg.codePath;
8991        final File codeFile = new File(codePath);
8992        final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp();
8993        final boolean asecApp = info.isForwardLocked() || info.isExternalAsec();
8994
8995        info.nativeLibraryRootDir = null;
8996        info.nativeLibraryRootRequiresIsa = false;
8997        info.nativeLibraryDir = null;
8998        info.secondaryNativeLibraryDir = null;
8999
9000        if (isApkFile(codeFile)) {
9001            // Monolithic install
9002            if (bundledApp) {
9003                // If "/system/lib64/apkname" exists, assume that is the per-package
9004                // native library directory to use; otherwise use "/system/lib/apkname".
9005                final String apkRoot = calculateBundledApkRoot(info.sourceDir);
9006                final boolean is64Bit = VMRuntime.is64BitInstructionSet(
9007                        getPrimaryInstructionSet(info));
9008
9009                // This is a bundled system app so choose the path based on the ABI.
9010                // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
9011                // is just the default path.
9012                final String apkName = deriveCodePathName(codePath);
9013                final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
9014                info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
9015                        apkName).getAbsolutePath();
9016
9017                if (info.secondaryCpuAbi != null) {
9018                    final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
9019                    info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
9020                            secondaryLibDir, apkName).getAbsolutePath();
9021                }
9022            } else if (asecApp) {
9023                info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
9024                        .getAbsolutePath();
9025            } else {
9026                final String apkName = deriveCodePathName(codePath);
9027                info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName)
9028                        .getAbsolutePath();
9029            }
9030
9031            info.nativeLibraryRootRequiresIsa = false;
9032            info.nativeLibraryDir = info.nativeLibraryRootDir;
9033        } else {
9034            // Cluster install
9035            info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
9036            info.nativeLibraryRootRequiresIsa = true;
9037
9038            info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
9039                    getPrimaryInstructionSet(info)).getAbsolutePath();
9040
9041            if (info.secondaryCpuAbi != null) {
9042                info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
9043                        VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
9044            }
9045        }
9046    }
9047
9048    /**
9049     * Calculate the abis and roots for a bundled app. These can uniquely
9050     * be determined from the contents of the system partition, i.e whether
9051     * it contains 64 or 32 bit shared libraries etc. We do not validate any
9052     * of this information, and instead assume that the system was built
9053     * sensibly.
9054     */
9055    private void setBundledAppAbisAndRoots(PackageParser.Package pkg,
9056                                           PackageSetting pkgSetting) {
9057        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
9058
9059        // If "/system/lib64/apkname" exists, assume that is the per-package
9060        // native library directory to use; otherwise use "/system/lib/apkname".
9061        final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
9062        setBundledAppAbi(pkg, apkRoot, apkName);
9063        // pkgSetting might be null during rescan following uninstall of updates
9064        // to a bundled app, so accommodate that possibility.  The settings in
9065        // that case will be established later from the parsed package.
9066        //
9067        // If the settings aren't null, sync them up with what we've just derived.
9068        // note that apkRoot isn't stored in the package settings.
9069        if (pkgSetting != null) {
9070            pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
9071            pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
9072        }
9073    }
9074
9075    /**
9076     * Deduces the ABI of a bundled app and sets the relevant fields on the
9077     * parsed pkg object.
9078     *
9079     * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
9080     *        under which system libraries are installed.
9081     * @param apkName the name of the installed package.
9082     */
9083    private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
9084        final File codeFile = new File(pkg.codePath);
9085
9086        final boolean has64BitLibs;
9087        final boolean has32BitLibs;
9088        if (isApkFile(codeFile)) {
9089            // Monolithic install
9090            has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
9091            has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
9092        } else {
9093            // Cluster install
9094            final File rootDir = new File(codeFile, LIB_DIR_NAME);
9095            if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
9096                    && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
9097                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
9098                has64BitLibs = (new File(rootDir, isa)).exists();
9099            } else {
9100                has64BitLibs = false;
9101            }
9102            if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
9103                    && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
9104                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
9105                has32BitLibs = (new File(rootDir, isa)).exists();
9106            } else {
9107                has32BitLibs = false;
9108            }
9109        }
9110
9111        if (has64BitLibs && !has32BitLibs) {
9112            // The package has 64 bit libs, but not 32 bit libs. Its primary
9113            // ABI should be 64 bit. We can safely assume here that the bundled
9114            // native libraries correspond to the most preferred ABI in the list.
9115
9116            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
9117            pkg.applicationInfo.secondaryCpuAbi = null;
9118        } else if (has32BitLibs && !has64BitLibs) {
9119            // The package has 32 bit libs but not 64 bit libs. Its primary
9120            // ABI should be 32 bit.
9121
9122            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
9123            pkg.applicationInfo.secondaryCpuAbi = null;
9124        } else if (has32BitLibs && has64BitLibs) {
9125            // The application has both 64 and 32 bit bundled libraries. We check
9126            // here that the app declares multiArch support, and warn if it doesn't.
9127            //
9128            // We will be lenient here and record both ABIs. The primary will be the
9129            // ABI that's higher on the list, i.e, a device that's configured to prefer
9130            // 64 bit apps will see a 64 bit primary ABI,
9131
9132            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
9133                Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch.");
9134            }
9135
9136            if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
9137                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
9138                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
9139            } else {
9140                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
9141                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
9142            }
9143        } else {
9144            pkg.applicationInfo.primaryCpuAbi = null;
9145            pkg.applicationInfo.secondaryCpuAbi = null;
9146        }
9147    }
9148
9149    private void killApplication(String pkgName, int appId, String reason) {
9150        // Request the ActivityManager to kill the process(only for existing packages)
9151        // so that we do not end up in a confused state while the user is still using the older
9152        // version of the application while the new one gets installed.
9153        final long token = Binder.clearCallingIdentity();
9154        try {
9155            IActivityManager am = ActivityManagerNative.getDefault();
9156            if (am != null) {
9157                try {
9158                    am.killApplicationWithAppId(pkgName, appId, reason);
9159                } catch (RemoteException e) {
9160                }
9161            }
9162        } finally {
9163            Binder.restoreCallingIdentity(token);
9164        }
9165    }
9166
9167    private void removePackageLI(PackageParser.Package pkg, boolean chatty) {
9168        // Remove the parent package setting
9169        PackageSetting ps = (PackageSetting) pkg.mExtras;
9170        if (ps != null) {
9171            removePackageLI(ps, chatty);
9172        }
9173        // Remove the child package setting
9174        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9175        for (int i = 0; i < childCount; i++) {
9176            PackageParser.Package childPkg = pkg.childPackages.get(i);
9177            ps = (PackageSetting) childPkg.mExtras;
9178            if (ps != null) {
9179                removePackageLI(ps, chatty);
9180            }
9181        }
9182    }
9183
9184    void removePackageLI(PackageSetting ps, boolean chatty) {
9185        if (DEBUG_INSTALL) {
9186            if (chatty)
9187                Log.d(TAG, "Removing package " + ps.name);
9188        }
9189
9190        // writer
9191        synchronized (mPackages) {
9192            mPackages.remove(ps.name);
9193            final PackageParser.Package pkg = ps.pkg;
9194            if (pkg != null) {
9195                cleanPackageDataStructuresLILPw(pkg, chatty);
9196            }
9197        }
9198    }
9199
9200    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
9201        if (DEBUG_INSTALL) {
9202            if (chatty)
9203                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
9204        }
9205
9206        // writer
9207        synchronized (mPackages) {
9208            // Remove the parent package
9209            mPackages.remove(pkg.applicationInfo.packageName);
9210            cleanPackageDataStructuresLILPw(pkg, chatty);
9211
9212            // Remove the child packages
9213            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9214            for (int i = 0; i < childCount; i++) {
9215                PackageParser.Package childPkg = pkg.childPackages.get(i);
9216                mPackages.remove(childPkg.applicationInfo.packageName);
9217                cleanPackageDataStructuresLILPw(childPkg, chatty);
9218            }
9219        }
9220    }
9221
9222    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
9223        int N = pkg.providers.size();
9224        StringBuilder r = null;
9225        int i;
9226        for (i=0; i<N; i++) {
9227            PackageParser.Provider p = pkg.providers.get(i);
9228            mProviders.removeProvider(p);
9229            if (p.info.authority == null) {
9230
9231                /* There was another ContentProvider with this authority when
9232                 * this app was installed so this authority is null,
9233                 * Ignore it as we don't have to unregister the provider.
9234                 */
9235                continue;
9236            }
9237            String names[] = p.info.authority.split(";");
9238            for (int j = 0; j < names.length; j++) {
9239                if (mProvidersByAuthority.get(names[j]) == p) {
9240                    mProvidersByAuthority.remove(names[j]);
9241                    if (DEBUG_REMOVE) {
9242                        if (chatty)
9243                            Log.d(TAG, "Unregistered content provider: " + names[j]
9244                                    + ", className = " + p.info.name + ", isSyncable = "
9245                                    + p.info.isSyncable);
9246                    }
9247                }
9248            }
9249            if (DEBUG_REMOVE && chatty) {
9250                if (r == null) {
9251                    r = new StringBuilder(256);
9252                } else {
9253                    r.append(' ');
9254                }
9255                r.append(p.info.name);
9256            }
9257        }
9258        if (r != null) {
9259            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
9260        }
9261
9262        N = pkg.services.size();
9263        r = null;
9264        for (i=0; i<N; i++) {
9265            PackageParser.Service s = pkg.services.get(i);
9266            mServices.removeService(s);
9267            if (chatty) {
9268                if (r == null) {
9269                    r = new StringBuilder(256);
9270                } else {
9271                    r.append(' ');
9272                }
9273                r.append(s.info.name);
9274            }
9275        }
9276        if (r != null) {
9277            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
9278        }
9279
9280        N = pkg.receivers.size();
9281        r = null;
9282        for (i=0; i<N; i++) {
9283            PackageParser.Activity a = pkg.receivers.get(i);
9284            mReceivers.removeActivity(a, "receiver");
9285            if (DEBUG_REMOVE && chatty) {
9286                if (r == null) {
9287                    r = new StringBuilder(256);
9288                } else {
9289                    r.append(' ');
9290                }
9291                r.append(a.info.name);
9292            }
9293        }
9294        if (r != null) {
9295            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
9296        }
9297
9298        N = pkg.activities.size();
9299        r = null;
9300        for (i=0; i<N; i++) {
9301            PackageParser.Activity a = pkg.activities.get(i);
9302            mActivities.removeActivity(a, "activity");
9303            if (DEBUG_REMOVE && chatty) {
9304                if (r == null) {
9305                    r = new StringBuilder(256);
9306                } else {
9307                    r.append(' ');
9308                }
9309                r.append(a.info.name);
9310            }
9311        }
9312        if (r != null) {
9313            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
9314        }
9315
9316        N = pkg.permissions.size();
9317        r = null;
9318        for (i=0; i<N; i++) {
9319            PackageParser.Permission p = pkg.permissions.get(i);
9320            BasePermission bp = mSettings.mPermissions.get(p.info.name);
9321            if (bp == null) {
9322                bp = mSettings.mPermissionTrees.get(p.info.name);
9323            }
9324            if (bp != null && bp.perm == p) {
9325                bp.perm = null;
9326                if (DEBUG_REMOVE && chatty) {
9327                    if (r == null) {
9328                        r = new StringBuilder(256);
9329                    } else {
9330                        r.append(' ');
9331                    }
9332                    r.append(p.info.name);
9333                }
9334            }
9335            if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
9336                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(p.info.name);
9337                if (appOpPkgs != null) {
9338                    appOpPkgs.remove(pkg.packageName);
9339                }
9340            }
9341        }
9342        if (r != null) {
9343            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
9344        }
9345
9346        N = pkg.requestedPermissions.size();
9347        r = null;
9348        for (i=0; i<N; i++) {
9349            String perm = pkg.requestedPermissions.get(i);
9350            BasePermission bp = mSettings.mPermissions.get(perm);
9351            if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
9352                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(perm);
9353                if (appOpPkgs != null) {
9354                    appOpPkgs.remove(pkg.packageName);
9355                    if (appOpPkgs.isEmpty()) {
9356                        mAppOpPermissionPackages.remove(perm);
9357                    }
9358                }
9359            }
9360        }
9361        if (r != null) {
9362            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
9363        }
9364
9365        N = pkg.instrumentation.size();
9366        r = null;
9367        for (i=0; i<N; i++) {
9368            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
9369            mInstrumentation.remove(a.getComponentName());
9370            if (DEBUG_REMOVE && chatty) {
9371                if (r == null) {
9372                    r = new StringBuilder(256);
9373                } else {
9374                    r.append(' ');
9375                }
9376                r.append(a.info.name);
9377            }
9378        }
9379        if (r != null) {
9380            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
9381        }
9382
9383        r = null;
9384        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
9385            // Only system apps can hold shared libraries.
9386            if (pkg.libraryNames != null) {
9387                for (i=0; i<pkg.libraryNames.size(); i++) {
9388                    String name = pkg.libraryNames.get(i);
9389                    SharedLibraryEntry cur = mSharedLibraries.get(name);
9390                    if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) {
9391                        mSharedLibraries.remove(name);
9392                        if (DEBUG_REMOVE && chatty) {
9393                            if (r == null) {
9394                                r = new StringBuilder(256);
9395                            } else {
9396                                r.append(' ');
9397                            }
9398                            r.append(name);
9399                        }
9400                    }
9401                }
9402            }
9403        }
9404        if (r != null) {
9405            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
9406        }
9407    }
9408
9409    private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
9410        for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
9411            if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
9412                return true;
9413            }
9414        }
9415        return false;
9416    }
9417
9418    static final int UPDATE_PERMISSIONS_ALL = 1<<0;
9419    static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
9420    static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
9421
9422    private void updatePermissionsLPw(PackageParser.Package pkg, int flags) {
9423        // Update the parent permissions
9424        updatePermissionsLPw(pkg.packageName, pkg, flags);
9425        // Update the child permissions
9426        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9427        for (int i = 0; i < childCount; i++) {
9428            PackageParser.Package childPkg = pkg.childPackages.get(i);
9429            updatePermissionsLPw(childPkg.packageName, childPkg, flags);
9430        }
9431    }
9432
9433    private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo,
9434            int flags) {
9435        final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null;
9436        updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags);
9437    }
9438
9439    private void updatePermissionsLPw(String changingPkg,
9440            PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) {
9441        // Make sure there are no dangling permission trees.
9442        Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator();
9443        while (it.hasNext()) {
9444            final BasePermission bp = it.next();
9445            if (bp.packageSetting == null) {
9446                // We may not yet have parsed the package, so just see if
9447                // we still know about its settings.
9448                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
9449            }
9450            if (bp.packageSetting == null) {
9451                Slog.w(TAG, "Removing dangling permission tree: " + bp.name
9452                        + " from package " + bp.sourcePackage);
9453                it.remove();
9454            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
9455                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
9456                    Slog.i(TAG, "Removing old permission tree: " + bp.name
9457                            + " from package " + bp.sourcePackage);
9458                    flags |= UPDATE_PERMISSIONS_ALL;
9459                    it.remove();
9460                }
9461            }
9462        }
9463
9464        // Make sure all dynamic permissions have been assigned to a package,
9465        // and make sure there are no dangling permissions.
9466        it = mSettings.mPermissions.values().iterator();
9467        while (it.hasNext()) {
9468            final BasePermission bp = it.next();
9469            if (bp.type == BasePermission.TYPE_DYNAMIC) {
9470                if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
9471                        + bp.name + " pkg=" + bp.sourcePackage
9472                        + " info=" + bp.pendingInfo);
9473                if (bp.packageSetting == null && bp.pendingInfo != null) {
9474                    final BasePermission tree = findPermissionTreeLP(bp.name);
9475                    if (tree != null && tree.perm != null) {
9476                        bp.packageSetting = tree.packageSetting;
9477                        bp.perm = new PackageParser.Permission(tree.perm.owner,
9478                                new PermissionInfo(bp.pendingInfo));
9479                        bp.perm.info.packageName = tree.perm.info.packageName;
9480                        bp.perm.info.name = bp.name;
9481                        bp.uid = tree.uid;
9482                    }
9483                }
9484            }
9485            if (bp.packageSetting == null) {
9486                // We may not yet have parsed the package, so just see if
9487                // we still know about its settings.
9488                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
9489            }
9490            if (bp.packageSetting == null) {
9491                Slog.w(TAG, "Removing dangling permission: " + bp.name
9492                        + " from package " + bp.sourcePackage);
9493                it.remove();
9494            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
9495                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
9496                    Slog.i(TAG, "Removing old permission: " + bp.name
9497                            + " from package " + bp.sourcePackage);
9498                    flags |= UPDATE_PERMISSIONS_ALL;
9499                    it.remove();
9500                }
9501            }
9502        }
9503
9504        // Now update the permissions for all packages, in particular
9505        // replace the granted permissions of the system packages.
9506        if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
9507            for (PackageParser.Package pkg : mPackages.values()) {
9508                if (pkg != pkgInfo) {
9509                    // Only replace for packages on requested volume
9510                    final String volumeUuid = getVolumeUuidForPackage(pkg);
9511                    final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0)
9512                            && Objects.equals(replaceVolumeUuid, volumeUuid);
9513                    grantPermissionsLPw(pkg, replace, changingPkg);
9514                }
9515            }
9516        }
9517
9518        if (pkgInfo != null) {
9519            // Only replace for packages on requested volume
9520            final String volumeUuid = getVolumeUuidForPackage(pkgInfo);
9521            final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0)
9522                    && Objects.equals(replaceVolumeUuid, volumeUuid);
9523            grantPermissionsLPw(pkgInfo, replace, changingPkg);
9524        }
9525    }
9526
9527    private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace,
9528            String packageOfInterest) {
9529        // IMPORTANT: There are two types of permissions: install and runtime.
9530        // Install time permissions are granted when the app is installed to
9531        // all device users and users added in the future. Runtime permissions
9532        // are granted at runtime explicitly to specific users. Normal and signature
9533        // protected permissions are install time permissions. Dangerous permissions
9534        // are install permissions if the app's target SDK is Lollipop MR1 or older,
9535        // otherwise they are runtime permissions. This function does not manage
9536        // runtime permissions except for the case an app targeting Lollipop MR1
9537        // being upgraded to target a newer SDK, in which case dangerous permissions
9538        // are transformed from install time to runtime ones.
9539
9540        final PackageSetting ps = (PackageSetting) pkg.mExtras;
9541        if (ps == null) {
9542            return;
9543        }
9544
9545        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions");
9546
9547        PermissionsState permissionsState = ps.getPermissionsState();
9548        PermissionsState origPermissions = permissionsState;
9549
9550        final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
9551
9552        boolean runtimePermissionsRevoked = false;
9553        int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY;
9554
9555        boolean changedInstallPermission = false;
9556
9557        if (replace) {
9558            ps.installPermissionsFixed = false;
9559            if (!ps.isSharedUser()) {
9560                origPermissions = new PermissionsState(permissionsState);
9561                permissionsState.reset();
9562            } else {
9563                // We need to know only about runtime permission changes since the
9564                // calling code always writes the install permissions state but
9565                // the runtime ones are written only if changed. The only cases of
9566                // changed runtime permissions here are promotion of an install to
9567                // runtime and revocation of a runtime from a shared user.
9568                changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw(
9569                        ps.sharedUser, UserManagerService.getInstance().getUserIds());
9570                if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) {
9571                    runtimePermissionsRevoked = true;
9572                }
9573            }
9574        }
9575
9576        permissionsState.setGlobalGids(mGlobalGids);
9577
9578        final int N = pkg.requestedPermissions.size();
9579        for (int i=0; i<N; i++) {
9580            final String name = pkg.requestedPermissions.get(i);
9581            final BasePermission bp = mSettings.mPermissions.get(name);
9582
9583            if (DEBUG_INSTALL) {
9584                Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
9585            }
9586
9587            if (bp == null || bp.packageSetting == null) {
9588                if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
9589                    Slog.w(TAG, "Unknown permission " + name
9590                            + " in package " + pkg.packageName);
9591                }
9592                continue;
9593            }
9594
9595            final String perm = bp.name;
9596            boolean allowedSig = false;
9597            int grant = GRANT_DENIED;
9598
9599            // Keep track of app op permissions.
9600            if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
9601                ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name);
9602                if (pkgs == null) {
9603                    pkgs = new ArraySet<>();
9604                    mAppOpPermissionPackages.put(bp.name, pkgs);
9605                }
9606                pkgs.add(pkg.packageName);
9607            }
9608
9609            final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE;
9610            final boolean appSupportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion
9611                    >= Build.VERSION_CODES.M;
9612            switch (level) {
9613                case PermissionInfo.PROTECTION_NORMAL: {
9614                    // For all apps normal permissions are install time ones.
9615                    grant = GRANT_INSTALL;
9616                } break;
9617
9618                case PermissionInfo.PROTECTION_DANGEROUS: {
9619                    // If a permission review is required for legacy apps we represent
9620                    // their permissions as always granted runtime ones since we need
9621                    // to keep the review required permission flag per user while an
9622                    // install permission's state is shared across all users.
9623                    if (!appSupportsRuntimePermissions && !Build.PERMISSIONS_REVIEW_REQUIRED) {
9624                        // For legacy apps dangerous permissions are install time ones.
9625                        grant = GRANT_INSTALL;
9626                    } else if (origPermissions.hasInstallPermission(bp.name)) {
9627                        // For legacy apps that became modern, install becomes runtime.
9628                        grant = GRANT_UPGRADE;
9629                    } else if (mPromoteSystemApps
9630                            && isSystemApp(ps)
9631                            && mExistingSystemPackages.contains(ps.name)) {
9632                        // For legacy system apps, install becomes runtime.
9633                        // We cannot check hasInstallPermission() for system apps since those
9634                        // permissions were granted implicitly and not persisted pre-M.
9635                        grant = GRANT_UPGRADE;
9636                    } else {
9637                        // For modern apps keep runtime permissions unchanged.
9638                        grant = GRANT_RUNTIME;
9639                    }
9640                } break;
9641
9642                case PermissionInfo.PROTECTION_SIGNATURE: {
9643                    // For all apps signature permissions are install time ones.
9644                    allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions);
9645                    if (allowedSig) {
9646                        grant = GRANT_INSTALL;
9647                    }
9648                } break;
9649            }
9650
9651            if (DEBUG_INSTALL) {
9652                Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
9653            }
9654
9655            if (grant != GRANT_DENIED) {
9656                if (!isSystemApp(ps) && ps.installPermissionsFixed) {
9657                    // If this is an existing, non-system package, then
9658                    // we can't add any new permissions to it.
9659                    if (!allowedSig && !origPermissions.hasInstallPermission(perm)) {
9660                        // Except...  if this is a permission that was added
9661                        // to the platform (note: need to only do this when
9662                        // updating the platform).
9663                        if (!isNewPlatformPermissionForPackage(perm, pkg)) {
9664                            grant = GRANT_DENIED;
9665                        }
9666                    }
9667                }
9668
9669                switch (grant) {
9670                    case GRANT_INSTALL: {
9671                        // Revoke this as runtime permission to handle the case of
9672                        // a runtime permission being downgraded to an install one. Also in permission review mode we keep dangerous permissions for legacy apps
9673                        for (int userId : UserManagerService.getInstance().getUserIds()) {
9674                            if (origPermissions.getRuntimePermissionState(
9675                                    bp.name, userId) != null) {
9676                                // Revoke the runtime permission and clear the flags.
9677                                origPermissions.revokeRuntimePermission(bp, userId);
9678                                origPermissions.updatePermissionFlags(bp, userId,
9679                                      PackageManager.MASK_PERMISSION_FLAGS, 0);
9680                                // If we revoked a permission permission, we have to write.
9681                                changedRuntimePermissionUserIds = ArrayUtils.appendInt(
9682                                        changedRuntimePermissionUserIds, userId);
9683                            }
9684                        }
9685                        // Grant an install permission.
9686                        if (permissionsState.grantInstallPermission(bp) !=
9687                                PermissionsState.PERMISSION_OPERATION_FAILURE) {
9688                            changedInstallPermission = true;
9689                        }
9690                    } break;
9691
9692                    case GRANT_RUNTIME: {
9693                        // Grant previously granted runtime permissions.
9694                        for (int userId : UserManagerService.getInstance().getUserIds()) {
9695                            PermissionState permissionState = origPermissions
9696                                    .getRuntimePermissionState(bp.name, userId);
9697                            int flags = permissionState != null
9698                                    ? permissionState.getFlags() : 0;
9699                            if (origPermissions.hasRuntimePermission(bp.name, userId)) {
9700                                if (permissionsState.grantRuntimePermission(bp, userId) ==
9701                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
9702                                    // If we cannot put the permission as it was, we have to write.
9703                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
9704                                            changedRuntimePermissionUserIds, userId);
9705                                }
9706                                // If the app supports runtime permissions no need for a review.
9707                                if (Build.PERMISSIONS_REVIEW_REQUIRED
9708                                        && appSupportsRuntimePermissions
9709                                        && (flags & PackageManager
9710                                                .FLAG_PERMISSION_REVIEW_REQUIRED) != 0) {
9711                                    flags &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
9712                                    // Since we changed the flags, we have to write.
9713                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
9714                                            changedRuntimePermissionUserIds, userId);
9715                                }
9716                            } else if (Build.PERMISSIONS_REVIEW_REQUIRED
9717                                    && !appSupportsRuntimePermissions) {
9718                                // For legacy apps that need a permission review, every new
9719                                // runtime permission is granted but it is pending a review.
9720                                if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
9721                                    permissionsState.grantRuntimePermission(bp, userId);
9722                                    flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
9723                                    // We changed the permission and flags, hence have to write.
9724                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
9725                                            changedRuntimePermissionUserIds, userId);
9726                                }
9727                            }
9728                            // Propagate the permission flags.
9729                            permissionsState.updatePermissionFlags(bp, userId, flags, flags);
9730                        }
9731                    } break;
9732
9733                    case GRANT_UPGRADE: {
9734                        // Grant runtime permissions for a previously held install permission.
9735                        PermissionState permissionState = origPermissions
9736                                .getInstallPermissionState(bp.name);
9737                        final int flags = permissionState != null ? permissionState.getFlags() : 0;
9738
9739                        if (origPermissions.revokeInstallPermission(bp)
9740                                != PermissionsState.PERMISSION_OPERATION_FAILURE) {
9741                            // We will be transferring the permission flags, so clear them.
9742                            origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL,
9743                                    PackageManager.MASK_PERMISSION_FLAGS, 0);
9744                            changedInstallPermission = true;
9745                        }
9746
9747                        // If the permission is not to be promoted to runtime we ignore it and
9748                        // also its other flags as they are not applicable to install permissions.
9749                        if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) {
9750                            for (int userId : currentUserIds) {
9751                                if (permissionsState.grantRuntimePermission(bp, userId) !=
9752                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
9753                                    // Transfer the permission flags.
9754                                    permissionsState.updatePermissionFlags(bp, userId,
9755                                            flags, flags);
9756                                    // If we granted the permission, we have to write.
9757                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
9758                                            changedRuntimePermissionUserIds, userId);
9759                                }
9760                            }
9761                        }
9762                    } break;
9763
9764                    default: {
9765                        if (packageOfInterest == null
9766                                || packageOfInterest.equals(pkg.packageName)) {
9767                            Slog.w(TAG, "Not granting permission " + perm
9768                                    + " to package " + pkg.packageName
9769                                    + " because it was previously installed without");
9770                        }
9771                    } break;
9772                }
9773            } else {
9774                if (permissionsState.revokeInstallPermission(bp) !=
9775                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
9776                    // Also drop the permission flags.
9777                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
9778                            PackageManager.MASK_PERMISSION_FLAGS, 0);
9779                    changedInstallPermission = true;
9780                    Slog.i(TAG, "Un-granting permission " + perm
9781                            + " from package " + pkg.packageName
9782                            + " (protectionLevel=" + bp.protectionLevel
9783                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
9784                            + ")");
9785                } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) {
9786                    // Don't print warning for app op permissions, since it is fine for them
9787                    // not to be granted, there is a UI for the user to decide.
9788                    if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
9789                        Slog.w(TAG, "Not granting permission " + perm
9790                                + " to package " + pkg.packageName
9791                                + " (protectionLevel=" + bp.protectionLevel
9792                                + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
9793                                + ")");
9794                    }
9795                }
9796            }
9797        }
9798
9799        if ((changedInstallPermission || replace) && !ps.installPermissionsFixed &&
9800                !isSystemApp(ps) || isUpdatedSystemApp(ps)){
9801            // This is the first that we have heard about this package, so the
9802            // permissions we have now selected are fixed until explicitly
9803            // changed.
9804            ps.installPermissionsFixed = true;
9805        }
9806
9807        // Persist the runtime permissions state for users with changes. If permissions
9808        // were revoked because no app in the shared user declares them we have to
9809        // write synchronously to avoid losing runtime permissions state.
9810        for (int userId : changedRuntimePermissionUserIds) {
9811            mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked);
9812        }
9813
9814        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9815    }
9816
9817    private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) {
9818        boolean allowed = false;
9819        final int NP = PackageParser.NEW_PERMISSIONS.length;
9820        for (int ip=0; ip<NP; ip++) {
9821            final PackageParser.NewPermissionInfo npi
9822                    = PackageParser.NEW_PERMISSIONS[ip];
9823            if (npi.name.equals(perm)
9824                    && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
9825                allowed = true;
9826                Log.i(TAG, "Auto-granting " + perm + " to old pkg "
9827                        + pkg.packageName);
9828                break;
9829            }
9830        }
9831        return allowed;
9832    }
9833
9834    private boolean grantSignaturePermission(String perm, PackageParser.Package pkg,
9835            BasePermission bp, PermissionsState origPermissions) {
9836        boolean allowed;
9837        allowed = (compareSignatures(
9838                bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
9839                        == PackageManager.SIGNATURE_MATCH)
9840                || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
9841                        == PackageManager.SIGNATURE_MATCH);
9842        if (!allowed && (bp.protectionLevel
9843                & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0) {
9844            if (isSystemApp(pkg)) {
9845                // For updated system applications, a system permission
9846                // is granted only if it had been defined by the original application.
9847                if (pkg.isUpdatedSystemApp()) {
9848                    final PackageSetting sysPs = mSettings
9849                            .getDisabledSystemPkgLPr(pkg.packageName);
9850                    if (sysPs != null && sysPs.getPermissionsState().hasInstallPermission(perm)) {
9851                        // If the original was granted this permission, we take
9852                        // that grant decision as read and propagate it to the
9853                        // update.
9854                        if (sysPs.isPrivileged()) {
9855                            allowed = true;
9856                        }
9857                    } else {
9858                        // The system apk may have been updated with an older
9859                        // version of the one on the data partition, but which
9860                        // granted a new system permission that it didn't have
9861                        // before.  In this case we do want to allow the app to
9862                        // now get the new permission if the ancestral apk is
9863                        // privileged to get it.
9864                        if (sysPs != null && sysPs.pkg != null && sysPs.isPrivileged()) {
9865                            for (int j = 0; j < sysPs.pkg.requestedPermissions.size(); j++) {
9866                                if (perm.equals(sysPs.pkg.requestedPermissions.get(j))) {
9867                                    allowed = true;
9868                                    break;
9869                                }
9870                            }
9871                        }
9872                        // Also if a privileged parent package on the system image or any of
9873                        // its children requested a privileged permission, the updated child
9874                        // packages can also get the permission.
9875                        if (pkg.parentPackage != null) {
9876                            final PackageSetting disabledSysParentPs = mSettings
9877                                    .getDisabledSystemPkgLPr(pkg.parentPackage.packageName);
9878                            if (disabledSysParentPs != null && disabledSysParentPs.pkg != null
9879                                    && disabledSysParentPs.isPrivileged()) {
9880                                if (isPackageRequestingPermission(disabledSysParentPs.pkg, perm)) {
9881                                    allowed = true;
9882                                } else if (disabledSysParentPs.pkg.childPackages != null) {
9883                                    final int count = disabledSysParentPs.pkg.childPackages.size();
9884                                    for (int i = 0; i < count; i++) {
9885                                        PackageParser.Package disabledSysChildPkg =
9886                                                disabledSysParentPs.pkg.childPackages.get(i);
9887                                        if (isPackageRequestingPermission(disabledSysChildPkg,
9888                                                perm)) {
9889                                            allowed = true;
9890                                            break;
9891                                        }
9892                                    }
9893                                }
9894                            }
9895                        }
9896                    }
9897                } else {
9898                    allowed = isPrivilegedApp(pkg);
9899                }
9900            }
9901        }
9902        if (!allowed) {
9903            if (!allowed && (bp.protectionLevel
9904                    & PermissionInfo.PROTECTION_FLAG_PRE23) != 0
9905                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
9906                // If this was a previously normal/dangerous permission that got moved
9907                // to a system permission as part of the runtime permission redesign, then
9908                // we still want to blindly grant it to old apps.
9909                allowed = true;
9910            }
9911            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0
9912                    && pkg.packageName.equals(mRequiredInstallerPackage)) {
9913                // If this permission is to be granted to the system installer and
9914                // this app is an installer, then it gets the permission.
9915                allowed = true;
9916            }
9917            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0
9918                    && pkg.packageName.equals(mRequiredVerifierPackage)) {
9919                // If this permission is to be granted to the system verifier and
9920                // this app is a verifier, then it gets the permission.
9921                allowed = true;
9922            }
9923            if (!allowed && (bp.protectionLevel
9924                    & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0
9925                    && isSystemApp(pkg)) {
9926                // Any pre-installed system app is allowed to get this permission.
9927                allowed = true;
9928            }
9929            if (!allowed && (bp.protectionLevel
9930                    & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) {
9931                // For development permissions, a development permission
9932                // is granted only if it was already granted.
9933                allowed = origPermissions.hasInstallPermission(perm);
9934            }
9935            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_SETUP) != 0
9936                    && pkg.packageName.equals(mSetupWizardPackage)) {
9937                // If this permission is to be granted to the system setup wizard and
9938                // this app is a setup wizard, then it gets the permission.
9939                allowed = true;
9940            }
9941        }
9942        return allowed;
9943    }
9944
9945    private boolean isPackageRequestingPermission(PackageParser.Package pkg, String permission) {
9946        final int permCount = pkg.requestedPermissions.size();
9947        for (int j = 0; j < permCount; j++) {
9948            String requestedPermission = pkg.requestedPermissions.get(j);
9949            if (permission.equals(requestedPermission)) {
9950                return true;
9951            }
9952        }
9953        return false;
9954    }
9955
9956    final class ActivityIntentResolver
9957            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
9958        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
9959                boolean defaultOnly, int userId) {
9960            if (!sUserManager.exists(userId)) return null;
9961            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
9962            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
9963        }
9964
9965        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
9966                int userId) {
9967            if (!sUserManager.exists(userId)) return null;
9968            mFlags = flags;
9969            return super.queryIntent(intent, resolvedType,
9970                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
9971        }
9972
9973        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
9974                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
9975            if (!sUserManager.exists(userId)) return null;
9976            if (packageActivities == null) {
9977                return null;
9978            }
9979            mFlags = flags;
9980            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
9981            final int N = packageActivities.size();
9982            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
9983                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
9984
9985            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
9986            for (int i = 0; i < N; ++i) {
9987                intentFilters = packageActivities.get(i).intents;
9988                if (intentFilters != null && intentFilters.size() > 0) {
9989                    PackageParser.ActivityIntentInfo[] array =
9990                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
9991                    intentFilters.toArray(array);
9992                    listCut.add(array);
9993                }
9994            }
9995            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
9996        }
9997
9998        /**
9999         * Finds a privileged activity that matches the specified activity names.
10000         */
10001        private PackageParser.Activity findMatchingActivity(
10002                List<PackageParser.Activity> activityList, ActivityInfo activityInfo) {
10003            for (PackageParser.Activity sysActivity : activityList) {
10004                if (sysActivity.info.name.equals(activityInfo.name)) {
10005                    return sysActivity;
10006                }
10007                if (sysActivity.info.name.equals(activityInfo.targetActivity)) {
10008                    return sysActivity;
10009                }
10010                if (sysActivity.info.targetActivity != null) {
10011                    if (sysActivity.info.targetActivity.equals(activityInfo.name)) {
10012                        return sysActivity;
10013                    }
10014                    if (sysActivity.info.targetActivity.equals(activityInfo.targetActivity)) {
10015                        return sysActivity;
10016                    }
10017                }
10018            }
10019            return null;
10020        }
10021
10022        public class IterGenerator<E> {
10023            public Iterator<E> generate(ActivityIntentInfo info) {
10024                return null;
10025            }
10026        }
10027
10028        public class ActionIterGenerator extends IterGenerator<String> {
10029            @Override
10030            public Iterator<String> generate(ActivityIntentInfo info) {
10031                return info.actionsIterator();
10032            }
10033        }
10034
10035        public class CategoriesIterGenerator extends IterGenerator<String> {
10036            @Override
10037            public Iterator<String> generate(ActivityIntentInfo info) {
10038                return info.categoriesIterator();
10039            }
10040        }
10041
10042        public class SchemesIterGenerator extends IterGenerator<String> {
10043            @Override
10044            public Iterator<String> generate(ActivityIntentInfo info) {
10045                return info.schemesIterator();
10046            }
10047        }
10048
10049        public class AuthoritiesIterGenerator extends IterGenerator<IntentFilter.AuthorityEntry> {
10050            @Override
10051            public Iterator<IntentFilter.AuthorityEntry> generate(ActivityIntentInfo info) {
10052                return info.authoritiesIterator();
10053            }
10054        }
10055
10056        /**
10057         * <em>WARNING</em> for performance reasons, the passed in intentList WILL BE
10058         * MODIFIED. Do not pass in a list that should not be changed.
10059         */
10060        private <T> void getIntentListSubset(List<ActivityIntentInfo> intentList,
10061                IterGenerator<T> generator, Iterator<T> searchIterator) {
10062            // loop through the set of actions; every one must be found in the intent filter
10063            while (searchIterator.hasNext()) {
10064                // we must have at least one filter in the list to consider a match
10065                if (intentList.size() == 0) {
10066                    break;
10067                }
10068
10069                final T searchAction = searchIterator.next();
10070
10071                // loop through the set of intent filters
10072                final Iterator<ActivityIntentInfo> intentIter = intentList.iterator();
10073                while (intentIter.hasNext()) {
10074                    final ActivityIntentInfo intentInfo = intentIter.next();
10075                    boolean selectionFound = false;
10076
10077                    // loop through the intent filter's selection criteria; at least one
10078                    // of them must match the searched criteria
10079                    final Iterator<T> intentSelectionIter = generator.generate(intentInfo);
10080                    while (intentSelectionIter != null && intentSelectionIter.hasNext()) {
10081                        final T intentSelection = intentSelectionIter.next();
10082                        if (intentSelection != null && intentSelection.equals(searchAction)) {
10083                            selectionFound = true;
10084                            break;
10085                        }
10086                    }
10087
10088                    // the selection criteria wasn't found in this filter's set; this filter
10089                    // is not a potential match
10090                    if (!selectionFound) {
10091                        intentIter.remove();
10092                    }
10093                }
10094            }
10095        }
10096
10097        private boolean isProtectedAction(ActivityIntentInfo filter) {
10098            final Iterator<String> actionsIter = filter.actionsIterator();
10099            while (actionsIter != null && actionsIter.hasNext()) {
10100                final String filterAction = actionsIter.next();
10101                if (PROTECTED_ACTIONS.contains(filterAction)) {
10102                    return true;
10103                }
10104            }
10105            return false;
10106        }
10107
10108        /**
10109         * Adjusts the priority of the given intent filter according to policy.
10110         * <p>
10111         * <ul>
10112         * <li>The priority for non privileged applications is capped to '0'</li>
10113         * <li>The priority for protected actions on privileged applications is capped to '0'</li>
10114         * <li>The priority for unbundled updates to privileged applications is capped to the
10115         *      priority defined on the system partition</li>
10116         * </ul>
10117         * <p>
10118         * <em>NOTE:</em> There is one exception. For security reasons, the setup wizard is
10119         * allowed to obtain any priority on any action.
10120         */
10121        private void adjustPriority(
10122                List<PackageParser.Activity> systemActivities, ActivityIntentInfo intent) {
10123            // nothing to do; priority is fine as-is
10124            if (intent.getPriority() <= 0) {
10125                return;
10126            }
10127
10128            final ActivityInfo activityInfo = intent.activity.info;
10129            final ApplicationInfo applicationInfo = activityInfo.applicationInfo;
10130
10131            final boolean privilegedApp =
10132                    ((applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0);
10133            if (!privilegedApp) {
10134                // non-privileged applications can never define a priority >0
10135                Slog.w(TAG, "Non-privileged app; cap priority to 0;"
10136                        + " package: " + applicationInfo.packageName
10137                        + " activity: " + intent.activity.className
10138                        + " origPrio: " + intent.getPriority());
10139                intent.setPriority(0);
10140                return;
10141            }
10142
10143            if (systemActivities == null) {
10144                // the system package is not disabled; we're parsing the system partition
10145                if (isProtectedAction(intent)) {
10146                    if (mDeferProtectedFilters) {
10147                        // We can't deal with these just yet. No component should ever obtain a
10148                        // >0 priority for a protected actions, with ONE exception -- the setup
10149                        // wizard. The setup wizard, however, cannot be known until we're able to
10150                        // query it for the category CATEGORY_SETUP_WIZARD. Which we can't do
10151                        // until all intent filters have been processed. Chicken, meet egg.
10152                        // Let the filter temporarily have a high priority and rectify the
10153                        // priorities after all system packages have been scanned.
10154                        mProtectedFilters.add(intent);
10155                        if (DEBUG_FILTERS) {
10156                            Slog.i(TAG, "Protected action; save for later;"
10157                                    + " package: " + applicationInfo.packageName
10158                                    + " activity: " + intent.activity.className
10159                                    + " origPrio: " + intent.getPriority());
10160                        }
10161                        return;
10162                    } else {
10163                        if (DEBUG_FILTERS && mSetupWizardPackage == null) {
10164                            Slog.i(TAG, "No setup wizard;"
10165                                + " All protected intents capped to priority 0");
10166                        }
10167                        if (intent.activity.info.packageName.equals(mSetupWizardPackage)) {
10168                            if (DEBUG_FILTERS) {
10169                                Slog.i(TAG, "Found setup wizard;"
10170                                    + " allow priority " + intent.getPriority() + ";"
10171                                    + " package: " + intent.activity.info.packageName
10172                                    + " activity: " + intent.activity.className
10173                                    + " priority: " + intent.getPriority());
10174                            }
10175                            // setup wizard gets whatever it wants
10176                            return;
10177                        }
10178                        Slog.w(TAG, "Protected action; cap priority to 0;"
10179                                + " package: " + intent.activity.info.packageName
10180                                + " activity: " + intent.activity.className
10181                                + " origPrio: " + intent.getPriority());
10182                        intent.setPriority(0);
10183                        return;
10184                    }
10185                }
10186                // privileged apps on the system image get whatever priority they request
10187                return;
10188            }
10189
10190            // privileged app unbundled update ... try to find the same activity
10191            final PackageParser.Activity foundActivity =
10192                    findMatchingActivity(systemActivities, activityInfo);
10193            if (foundActivity == null) {
10194                // this is a new activity; it cannot obtain >0 priority
10195                if (DEBUG_FILTERS) {
10196                    Slog.i(TAG, "New activity; cap priority to 0;"
10197                            + " package: " + applicationInfo.packageName
10198                            + " activity: " + intent.activity.className
10199                            + " origPrio: " + intent.getPriority());
10200                }
10201                intent.setPriority(0);
10202                return;
10203            }
10204
10205            // found activity, now check for filter equivalence
10206
10207            // a shallow copy is enough; we modify the list, not its contents
10208            final List<ActivityIntentInfo> intentListCopy =
10209                    new ArrayList<>(foundActivity.intents);
10210            final List<ActivityIntentInfo> foundFilters = findFilters(intent);
10211
10212            // find matching action subsets
10213            final Iterator<String> actionsIterator = intent.actionsIterator();
10214            if (actionsIterator != null) {
10215                getIntentListSubset(
10216                        intentListCopy, new ActionIterGenerator(), actionsIterator);
10217                if (intentListCopy.size() == 0) {
10218                    // no more intents to match; we're not equivalent
10219                    if (DEBUG_FILTERS) {
10220                        Slog.i(TAG, "Mismatched action; cap priority to 0;"
10221                                + " package: " + applicationInfo.packageName
10222                                + " activity: " + intent.activity.className
10223                                + " origPrio: " + intent.getPriority());
10224                    }
10225                    intent.setPriority(0);
10226                    return;
10227                }
10228            }
10229
10230            // find matching category subsets
10231            final Iterator<String> categoriesIterator = intent.categoriesIterator();
10232            if (categoriesIterator != null) {
10233                getIntentListSubset(intentListCopy, new CategoriesIterGenerator(),
10234                        categoriesIterator);
10235                if (intentListCopy.size() == 0) {
10236                    // no more intents to match; we're not equivalent
10237                    if (DEBUG_FILTERS) {
10238                        Slog.i(TAG, "Mismatched category; cap priority to 0;"
10239                                + " package: " + applicationInfo.packageName
10240                                + " activity: " + intent.activity.className
10241                                + " origPrio: " + intent.getPriority());
10242                    }
10243                    intent.setPriority(0);
10244                    return;
10245                }
10246            }
10247
10248            // find matching schemes subsets
10249            final Iterator<String> schemesIterator = intent.schemesIterator();
10250            if (schemesIterator != null) {
10251                getIntentListSubset(intentListCopy, new SchemesIterGenerator(),
10252                        schemesIterator);
10253                if (intentListCopy.size() == 0) {
10254                    // no more intents to match; we're not equivalent
10255                    if (DEBUG_FILTERS) {
10256                        Slog.i(TAG, "Mismatched scheme; cap priority to 0;"
10257                                + " package: " + applicationInfo.packageName
10258                                + " activity: " + intent.activity.className
10259                                + " origPrio: " + intent.getPriority());
10260                    }
10261                    intent.setPriority(0);
10262                    return;
10263                }
10264            }
10265
10266            // find matching authorities subsets
10267            final Iterator<IntentFilter.AuthorityEntry>
10268                    authoritiesIterator = intent.authoritiesIterator();
10269            if (authoritiesIterator != null) {
10270                getIntentListSubset(intentListCopy,
10271                        new AuthoritiesIterGenerator(),
10272                        authoritiesIterator);
10273                if (intentListCopy.size() == 0) {
10274                    // no more intents to match; we're not equivalent
10275                    if (DEBUG_FILTERS) {
10276                        Slog.i(TAG, "Mismatched authority; cap priority to 0;"
10277                                + " package: " + applicationInfo.packageName
10278                                + " activity: " + intent.activity.className
10279                                + " origPrio: " + intent.getPriority());
10280                    }
10281                    intent.setPriority(0);
10282                    return;
10283                }
10284            }
10285
10286            // we found matching filter(s); app gets the max priority of all intents
10287            int cappedPriority = 0;
10288            for (int i = intentListCopy.size() - 1; i >= 0; --i) {
10289                cappedPriority = Math.max(cappedPriority, intentListCopy.get(i).getPriority());
10290            }
10291            if (intent.getPriority() > cappedPriority) {
10292                if (DEBUG_FILTERS) {
10293                    Slog.i(TAG, "Found matching filter(s);"
10294                            + " cap priority to " + cappedPriority + ";"
10295                            + " package: " + applicationInfo.packageName
10296                            + " activity: " + intent.activity.className
10297                            + " origPrio: " + intent.getPriority());
10298                }
10299                intent.setPriority(cappedPriority);
10300                return;
10301            }
10302            // all this for nothing; the requested priority was <= what was on the system
10303        }
10304
10305        public final void addActivity(PackageParser.Activity a, String type) {
10306            mActivities.put(a.getComponentName(), a);
10307            if (DEBUG_SHOW_INFO)
10308                Log.v(
10309                TAG, "  " + type + " " +
10310                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
10311            if (DEBUG_SHOW_INFO)
10312                Log.v(TAG, "    Class=" + a.info.name);
10313            final int NI = a.intents.size();
10314            for (int j=0; j<NI; j++) {
10315                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
10316                if ("activity".equals(type)) {
10317                    final PackageSetting ps =
10318                            mSettings.getDisabledSystemPkgLPr(intent.activity.info.packageName);
10319                    final List<PackageParser.Activity> systemActivities =
10320                            ps != null && ps.pkg != null ? ps.pkg.activities : null;
10321                    adjustPriority(systemActivities, intent);
10322                }
10323                if (DEBUG_SHOW_INFO) {
10324                    Log.v(TAG, "    IntentFilter:");
10325                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
10326                }
10327                if (!intent.debugCheck()) {
10328                    Log.w(TAG, "==> For Activity " + a.info.name);
10329                }
10330                addFilter(intent);
10331            }
10332        }
10333
10334        public final void removeActivity(PackageParser.Activity a, String type) {
10335            mActivities.remove(a.getComponentName());
10336            if (DEBUG_SHOW_INFO) {
10337                Log.v(TAG, "  " + type + " "
10338                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
10339                                : a.info.name) + ":");
10340                Log.v(TAG, "    Class=" + a.info.name);
10341            }
10342            final int NI = a.intents.size();
10343            for (int j=0; j<NI; j++) {
10344                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
10345                if (DEBUG_SHOW_INFO) {
10346                    Log.v(TAG, "    IntentFilter:");
10347                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
10348                }
10349                removeFilter(intent);
10350            }
10351        }
10352
10353        @Override
10354        protected boolean allowFilterResult(
10355                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
10356            ActivityInfo filterAi = filter.activity.info;
10357            for (int i=dest.size()-1; i>=0; i--) {
10358                ActivityInfo destAi = dest.get(i).activityInfo;
10359                if (destAi.name == filterAi.name
10360                        && destAi.packageName == filterAi.packageName) {
10361                    return false;
10362                }
10363            }
10364            return true;
10365        }
10366
10367        @Override
10368        protected ActivityIntentInfo[] newArray(int size) {
10369            return new ActivityIntentInfo[size];
10370        }
10371
10372        @Override
10373        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
10374            if (!sUserManager.exists(userId)) return true;
10375            PackageParser.Package p = filter.activity.owner;
10376            if (p != null) {
10377                PackageSetting ps = (PackageSetting)p.mExtras;
10378                if (ps != null) {
10379                    // System apps are never considered stopped for purposes of
10380                    // filtering, because there may be no way for the user to
10381                    // actually re-launch them.
10382                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
10383                            && ps.getStopped(userId);
10384                }
10385            }
10386            return false;
10387        }
10388
10389        @Override
10390        protected boolean isPackageForFilter(String packageName,
10391                PackageParser.ActivityIntentInfo info) {
10392            return packageName.equals(info.activity.owner.packageName);
10393        }
10394
10395        @Override
10396        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
10397                int match, int userId) {
10398            if (!sUserManager.exists(userId)) return null;
10399            if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) {
10400                return null;
10401            }
10402            final PackageParser.Activity activity = info.activity;
10403            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
10404            if (ps == null) {
10405                return null;
10406            }
10407            ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags,
10408                    ps.readUserState(userId), userId);
10409            if (ai == null) {
10410                return null;
10411            }
10412            final ResolveInfo res = new ResolveInfo();
10413            res.activityInfo = ai;
10414            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
10415                res.filter = info;
10416            }
10417            if (info != null) {
10418                res.handleAllWebDataURI = info.handleAllWebDataURI();
10419            }
10420            res.priority = info.getPriority();
10421            res.preferredOrder = activity.owner.mPreferredOrder;
10422            //System.out.println("Result: " + res.activityInfo.className +
10423            //                   " = " + res.priority);
10424            res.match = match;
10425            res.isDefault = info.hasDefault;
10426            res.labelRes = info.labelRes;
10427            res.nonLocalizedLabel = info.nonLocalizedLabel;
10428            if (userNeedsBadging(userId)) {
10429                res.noResourceId = true;
10430            } else {
10431                res.icon = info.icon;
10432            }
10433            res.iconResourceId = info.icon;
10434            res.system = res.activityInfo.applicationInfo.isSystemApp();
10435            return res;
10436        }
10437
10438        @Override
10439        protected void sortResults(List<ResolveInfo> results) {
10440            Collections.sort(results, mResolvePrioritySorter);
10441        }
10442
10443        @Override
10444        protected void dumpFilter(PrintWriter out, String prefix,
10445                PackageParser.ActivityIntentInfo filter) {
10446            out.print(prefix); out.print(
10447                    Integer.toHexString(System.identityHashCode(filter.activity)));
10448                    out.print(' ');
10449                    filter.activity.printComponentShortName(out);
10450                    out.print(" filter ");
10451                    out.println(Integer.toHexString(System.identityHashCode(filter)));
10452        }
10453
10454        @Override
10455        protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) {
10456            return filter.activity;
10457        }
10458
10459        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
10460            PackageParser.Activity activity = (PackageParser.Activity)label;
10461            out.print(prefix); out.print(
10462                    Integer.toHexString(System.identityHashCode(activity)));
10463                    out.print(' ');
10464                    activity.printComponentShortName(out);
10465            if (count > 1) {
10466                out.print(" ("); out.print(count); out.print(" filters)");
10467            }
10468            out.println();
10469        }
10470
10471        // Keys are String (activity class name), values are Activity.
10472        private final ArrayMap<ComponentName, PackageParser.Activity> mActivities
10473                = new ArrayMap<ComponentName, PackageParser.Activity>();
10474        private int mFlags;
10475    }
10476
10477    private final class ServiceIntentResolver
10478            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
10479        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
10480                boolean defaultOnly, int userId) {
10481            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
10482            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
10483        }
10484
10485        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
10486                int userId) {
10487            if (!sUserManager.exists(userId)) return null;
10488            mFlags = flags;
10489            return super.queryIntent(intent, resolvedType,
10490                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
10491        }
10492
10493        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
10494                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
10495            if (!sUserManager.exists(userId)) return null;
10496            if (packageServices == null) {
10497                return null;
10498            }
10499            mFlags = flags;
10500            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
10501            final int N = packageServices.size();
10502            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
10503                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
10504
10505            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
10506            for (int i = 0; i < N; ++i) {
10507                intentFilters = packageServices.get(i).intents;
10508                if (intentFilters != null && intentFilters.size() > 0) {
10509                    PackageParser.ServiceIntentInfo[] array =
10510                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
10511                    intentFilters.toArray(array);
10512                    listCut.add(array);
10513                }
10514            }
10515            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
10516        }
10517
10518        public final void addService(PackageParser.Service s) {
10519            mServices.put(s.getComponentName(), s);
10520            if (DEBUG_SHOW_INFO) {
10521                Log.v(TAG, "  "
10522                        + (s.info.nonLocalizedLabel != null
10523                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
10524                Log.v(TAG, "    Class=" + s.info.name);
10525            }
10526            final int NI = s.intents.size();
10527            int j;
10528            for (j=0; j<NI; j++) {
10529                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
10530                if (DEBUG_SHOW_INFO) {
10531                    Log.v(TAG, "    IntentFilter:");
10532                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
10533                }
10534                if (!intent.debugCheck()) {
10535                    Log.w(TAG, "==> For Service " + s.info.name);
10536                }
10537                addFilter(intent);
10538            }
10539        }
10540
10541        public final void removeService(PackageParser.Service s) {
10542            mServices.remove(s.getComponentName());
10543            if (DEBUG_SHOW_INFO) {
10544                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
10545                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
10546                Log.v(TAG, "    Class=" + s.info.name);
10547            }
10548            final int NI = s.intents.size();
10549            int j;
10550            for (j=0; j<NI; j++) {
10551                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
10552                if (DEBUG_SHOW_INFO) {
10553                    Log.v(TAG, "    IntentFilter:");
10554                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
10555                }
10556                removeFilter(intent);
10557            }
10558        }
10559
10560        @Override
10561        protected boolean allowFilterResult(
10562                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
10563            ServiceInfo filterSi = filter.service.info;
10564            for (int i=dest.size()-1; i>=0; i--) {
10565                ServiceInfo destAi = dest.get(i).serviceInfo;
10566                if (destAi.name == filterSi.name
10567                        && destAi.packageName == filterSi.packageName) {
10568                    return false;
10569                }
10570            }
10571            return true;
10572        }
10573
10574        @Override
10575        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
10576            return new PackageParser.ServiceIntentInfo[size];
10577        }
10578
10579        @Override
10580        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
10581            if (!sUserManager.exists(userId)) return true;
10582            PackageParser.Package p = filter.service.owner;
10583            if (p != null) {
10584                PackageSetting ps = (PackageSetting)p.mExtras;
10585                if (ps != null) {
10586                    // System apps are never considered stopped for purposes of
10587                    // filtering, because there may be no way for the user to
10588                    // actually re-launch them.
10589                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
10590                            && ps.getStopped(userId);
10591                }
10592            }
10593            return false;
10594        }
10595
10596        @Override
10597        protected boolean isPackageForFilter(String packageName,
10598                PackageParser.ServiceIntentInfo info) {
10599            return packageName.equals(info.service.owner.packageName);
10600        }
10601
10602        @Override
10603        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
10604                int match, int userId) {
10605            if (!sUserManager.exists(userId)) return null;
10606            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
10607            if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) {
10608                return null;
10609            }
10610            final PackageParser.Service service = info.service;
10611            PackageSetting ps = (PackageSetting) service.owner.mExtras;
10612            if (ps == null) {
10613                return null;
10614            }
10615            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
10616                    ps.readUserState(userId), userId);
10617            if (si == null) {
10618                return null;
10619            }
10620            final ResolveInfo res = new ResolveInfo();
10621            res.serviceInfo = si;
10622            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
10623                res.filter = filter;
10624            }
10625            res.priority = info.getPriority();
10626            res.preferredOrder = service.owner.mPreferredOrder;
10627            res.match = match;
10628            res.isDefault = info.hasDefault;
10629            res.labelRes = info.labelRes;
10630            res.nonLocalizedLabel = info.nonLocalizedLabel;
10631            res.icon = info.icon;
10632            res.system = res.serviceInfo.applicationInfo.isSystemApp();
10633            return res;
10634        }
10635
10636        @Override
10637        protected void sortResults(List<ResolveInfo> results) {
10638            Collections.sort(results, mResolvePrioritySorter);
10639        }
10640
10641        @Override
10642        protected void dumpFilter(PrintWriter out, String prefix,
10643                PackageParser.ServiceIntentInfo filter) {
10644            out.print(prefix); out.print(
10645                    Integer.toHexString(System.identityHashCode(filter.service)));
10646                    out.print(' ');
10647                    filter.service.printComponentShortName(out);
10648                    out.print(" filter ");
10649                    out.println(Integer.toHexString(System.identityHashCode(filter)));
10650        }
10651
10652        @Override
10653        protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) {
10654            return filter.service;
10655        }
10656
10657        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
10658            PackageParser.Service service = (PackageParser.Service)label;
10659            out.print(prefix); out.print(
10660                    Integer.toHexString(System.identityHashCode(service)));
10661                    out.print(' ');
10662                    service.printComponentShortName(out);
10663            if (count > 1) {
10664                out.print(" ("); out.print(count); out.print(" filters)");
10665            }
10666            out.println();
10667        }
10668
10669//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
10670//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
10671//            final List<ResolveInfo> retList = Lists.newArrayList();
10672//            while (i.hasNext()) {
10673//                final ResolveInfo resolveInfo = (ResolveInfo) i;
10674//                if (isEnabledLP(resolveInfo.serviceInfo)) {
10675//                    retList.add(resolveInfo);
10676//                }
10677//            }
10678//            return retList;
10679//        }
10680
10681        // Keys are String (activity class name), values are Activity.
10682        private final ArrayMap<ComponentName, PackageParser.Service> mServices
10683                = new ArrayMap<ComponentName, PackageParser.Service>();
10684        private int mFlags;
10685    };
10686
10687    private final class ProviderIntentResolver
10688            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
10689        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
10690                boolean defaultOnly, int userId) {
10691            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
10692            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
10693        }
10694
10695        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
10696                int userId) {
10697            if (!sUserManager.exists(userId))
10698                return null;
10699            mFlags = flags;
10700            return super.queryIntent(intent, resolvedType,
10701                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
10702        }
10703
10704        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
10705                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
10706            if (!sUserManager.exists(userId))
10707                return null;
10708            if (packageProviders == null) {
10709                return null;
10710            }
10711            mFlags = flags;
10712            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
10713            final int N = packageProviders.size();
10714            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
10715                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
10716
10717            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
10718            for (int i = 0; i < N; ++i) {
10719                intentFilters = packageProviders.get(i).intents;
10720                if (intentFilters != null && intentFilters.size() > 0) {
10721                    PackageParser.ProviderIntentInfo[] array =
10722                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
10723                    intentFilters.toArray(array);
10724                    listCut.add(array);
10725                }
10726            }
10727            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
10728        }
10729
10730        public final void addProvider(PackageParser.Provider p) {
10731            if (mProviders.containsKey(p.getComponentName())) {
10732                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
10733                return;
10734            }
10735
10736            mProviders.put(p.getComponentName(), p);
10737            if (DEBUG_SHOW_INFO) {
10738                Log.v(TAG, "  "
10739                        + (p.info.nonLocalizedLabel != null
10740                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
10741                Log.v(TAG, "    Class=" + p.info.name);
10742            }
10743            final int NI = p.intents.size();
10744            int j;
10745            for (j = 0; j < NI; j++) {
10746                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
10747                if (DEBUG_SHOW_INFO) {
10748                    Log.v(TAG, "    IntentFilter:");
10749                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
10750                }
10751                if (!intent.debugCheck()) {
10752                    Log.w(TAG, "==> For Provider " + p.info.name);
10753                }
10754                addFilter(intent);
10755            }
10756        }
10757
10758        public final void removeProvider(PackageParser.Provider p) {
10759            mProviders.remove(p.getComponentName());
10760            if (DEBUG_SHOW_INFO) {
10761                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
10762                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
10763                Log.v(TAG, "    Class=" + p.info.name);
10764            }
10765            final int NI = p.intents.size();
10766            int j;
10767            for (j = 0; j < NI; j++) {
10768                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
10769                if (DEBUG_SHOW_INFO) {
10770                    Log.v(TAG, "    IntentFilter:");
10771                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
10772                }
10773                removeFilter(intent);
10774            }
10775        }
10776
10777        @Override
10778        protected boolean allowFilterResult(
10779                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
10780            ProviderInfo filterPi = filter.provider.info;
10781            for (int i = dest.size() - 1; i >= 0; i--) {
10782                ProviderInfo destPi = dest.get(i).providerInfo;
10783                if (destPi.name == filterPi.name
10784                        && destPi.packageName == filterPi.packageName) {
10785                    return false;
10786                }
10787            }
10788            return true;
10789        }
10790
10791        @Override
10792        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
10793            return new PackageParser.ProviderIntentInfo[size];
10794        }
10795
10796        @Override
10797        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
10798            if (!sUserManager.exists(userId))
10799                return true;
10800            PackageParser.Package p = filter.provider.owner;
10801            if (p != null) {
10802                PackageSetting ps = (PackageSetting) p.mExtras;
10803                if (ps != null) {
10804                    // System apps are never considered stopped for purposes of
10805                    // filtering, because there may be no way for the user to
10806                    // actually re-launch them.
10807                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
10808                            && ps.getStopped(userId);
10809                }
10810            }
10811            return false;
10812        }
10813
10814        @Override
10815        protected boolean isPackageForFilter(String packageName,
10816                PackageParser.ProviderIntentInfo info) {
10817            return packageName.equals(info.provider.owner.packageName);
10818        }
10819
10820        @Override
10821        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
10822                int match, int userId) {
10823            if (!sUserManager.exists(userId))
10824                return null;
10825            final PackageParser.ProviderIntentInfo info = filter;
10826            if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) {
10827                return null;
10828            }
10829            final PackageParser.Provider provider = info.provider;
10830            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
10831            if (ps == null) {
10832                return null;
10833            }
10834            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
10835                    ps.readUserState(userId), userId);
10836            if (pi == null) {
10837                return null;
10838            }
10839            final ResolveInfo res = new ResolveInfo();
10840            res.providerInfo = pi;
10841            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
10842                res.filter = filter;
10843            }
10844            res.priority = info.getPriority();
10845            res.preferredOrder = provider.owner.mPreferredOrder;
10846            res.match = match;
10847            res.isDefault = info.hasDefault;
10848            res.labelRes = info.labelRes;
10849            res.nonLocalizedLabel = info.nonLocalizedLabel;
10850            res.icon = info.icon;
10851            res.system = res.providerInfo.applicationInfo.isSystemApp();
10852            return res;
10853        }
10854
10855        @Override
10856        protected void sortResults(List<ResolveInfo> results) {
10857            Collections.sort(results, mResolvePrioritySorter);
10858        }
10859
10860        @Override
10861        protected void dumpFilter(PrintWriter out, String prefix,
10862                PackageParser.ProviderIntentInfo filter) {
10863            out.print(prefix);
10864            out.print(
10865                    Integer.toHexString(System.identityHashCode(filter.provider)));
10866            out.print(' ');
10867            filter.provider.printComponentShortName(out);
10868            out.print(" filter ");
10869            out.println(Integer.toHexString(System.identityHashCode(filter)));
10870        }
10871
10872        @Override
10873        protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) {
10874            return filter.provider;
10875        }
10876
10877        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
10878            PackageParser.Provider provider = (PackageParser.Provider)label;
10879            out.print(prefix); out.print(
10880                    Integer.toHexString(System.identityHashCode(provider)));
10881                    out.print(' ');
10882                    provider.printComponentShortName(out);
10883            if (count > 1) {
10884                out.print(" ("); out.print(count); out.print(" filters)");
10885            }
10886            out.println();
10887        }
10888
10889        private final ArrayMap<ComponentName, PackageParser.Provider> mProviders
10890                = new ArrayMap<ComponentName, PackageParser.Provider>();
10891        private int mFlags;
10892    }
10893
10894    private static final class EphemeralIntentResolver
10895            extends IntentResolver<EphemeralResolveIntentInfo, EphemeralResolveInfo> {
10896        @Override
10897        protected EphemeralResolveIntentInfo[] newArray(int size) {
10898            return new EphemeralResolveIntentInfo[size];
10899        }
10900
10901        @Override
10902        protected boolean isPackageForFilter(String packageName, EphemeralResolveIntentInfo info) {
10903            return true;
10904        }
10905
10906        @Override
10907        protected EphemeralResolveInfo newResult(EphemeralResolveIntentInfo info, int match,
10908                int userId) {
10909            if (!sUserManager.exists(userId)) {
10910                return null;
10911            }
10912            return info.getEphemeralResolveInfo();
10913        }
10914    }
10915
10916    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
10917            new Comparator<ResolveInfo>() {
10918        public int compare(ResolveInfo r1, ResolveInfo r2) {
10919            int v1 = r1.priority;
10920            int v2 = r2.priority;
10921            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
10922            if (v1 != v2) {
10923                return (v1 > v2) ? -1 : 1;
10924            }
10925            v1 = r1.preferredOrder;
10926            v2 = r2.preferredOrder;
10927            if (v1 != v2) {
10928                return (v1 > v2) ? -1 : 1;
10929            }
10930            if (r1.isDefault != r2.isDefault) {
10931                return r1.isDefault ? -1 : 1;
10932            }
10933            v1 = r1.match;
10934            v2 = r2.match;
10935            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
10936            if (v1 != v2) {
10937                return (v1 > v2) ? -1 : 1;
10938            }
10939            if (r1.system != r2.system) {
10940                return r1.system ? -1 : 1;
10941            }
10942            if (r1.activityInfo != null) {
10943                return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName);
10944            }
10945            if (r1.serviceInfo != null) {
10946                return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName);
10947            }
10948            if (r1.providerInfo != null) {
10949                return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName);
10950            }
10951            return 0;
10952        }
10953    };
10954
10955    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
10956            new Comparator<ProviderInfo>() {
10957        public int compare(ProviderInfo p1, ProviderInfo p2) {
10958            final int v1 = p1.initOrder;
10959            final int v2 = p2.initOrder;
10960            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
10961        }
10962    };
10963
10964    final void sendPackageBroadcast(final String action, final String pkg, final Bundle extras,
10965            final int flags, final String targetPkg, final IIntentReceiver finishedReceiver,
10966            final int[] userIds) {
10967        mHandler.post(new Runnable() {
10968            @Override
10969            public void run() {
10970                try {
10971                    final IActivityManager am = ActivityManagerNative.getDefault();
10972                    if (am == null) return;
10973                    final int[] resolvedUserIds;
10974                    if (userIds == null) {
10975                        resolvedUserIds = am.getRunningUserIds();
10976                    } else {
10977                        resolvedUserIds = userIds;
10978                    }
10979                    for (int id : resolvedUserIds) {
10980                        final Intent intent = new Intent(action,
10981                                pkg != null ? Uri.fromParts("package", pkg, null) : null);
10982                        if (extras != null) {
10983                            intent.putExtras(extras);
10984                        }
10985                        if (targetPkg != null) {
10986                            intent.setPackage(targetPkg);
10987                        }
10988                        // Modify the UID when posting to other users
10989                        int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
10990                        if (uid > 0 && UserHandle.getUserId(uid) != id) {
10991                            uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
10992                            intent.putExtra(Intent.EXTRA_UID, uid);
10993                        }
10994                        intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
10995                        intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags);
10996                        if (DEBUG_BROADCASTS) {
10997                            RuntimeException here = new RuntimeException("here");
10998                            here.fillInStackTrace();
10999                            Slog.d(TAG, "Sending to user " + id + ": "
11000                                    + intent.toShortString(false, true, false, false)
11001                                    + " " + intent.getExtras(), here);
11002                        }
11003                        am.broadcastIntent(null, intent, null, finishedReceiver,
11004                                0, null, null, null, android.app.AppOpsManager.OP_NONE,
11005                                null, finishedReceiver != null, false, id);
11006                    }
11007                } catch (RemoteException ex) {
11008                }
11009            }
11010        });
11011    }
11012
11013    /**
11014     * Check if the external storage media is available. This is true if there
11015     * is a mounted external storage medium or if the external storage is
11016     * emulated.
11017     */
11018    private boolean isExternalMediaAvailable() {
11019        return mMediaMounted || Environment.isExternalStorageEmulated();
11020    }
11021
11022    @Override
11023    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
11024        // writer
11025        synchronized (mPackages) {
11026            if (!isExternalMediaAvailable()) {
11027                // If the external storage is no longer mounted at this point,
11028                // the caller may not have been able to delete all of this
11029                // packages files and can not delete any more.  Bail.
11030                return null;
11031            }
11032            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
11033            if (lastPackage != null) {
11034                pkgs.remove(lastPackage);
11035            }
11036            if (pkgs.size() > 0) {
11037                return pkgs.get(0);
11038            }
11039        }
11040        return null;
11041    }
11042
11043    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
11044        final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
11045                userId, andCode ? 1 : 0, packageName);
11046        if (mSystemReady) {
11047            msg.sendToTarget();
11048        } else {
11049            if (mPostSystemReadyMessages == null) {
11050                mPostSystemReadyMessages = new ArrayList<>();
11051            }
11052            mPostSystemReadyMessages.add(msg);
11053        }
11054    }
11055
11056    void startCleaningPackages() {
11057        // reader
11058        if (!isExternalMediaAvailable()) {
11059            return;
11060        }
11061        synchronized (mPackages) {
11062            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
11063                return;
11064            }
11065        }
11066        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
11067        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
11068        IActivityManager am = ActivityManagerNative.getDefault();
11069        if (am != null) {
11070            try {
11071                am.startService(null, intent, null, mContext.getOpPackageName(),
11072                        UserHandle.USER_SYSTEM);
11073            } catch (RemoteException e) {
11074            }
11075        }
11076    }
11077
11078    @Override
11079    public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer,
11080            int installFlags, String installerPackageName, int userId) {
11081        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
11082
11083        final int callingUid = Binder.getCallingUid();
11084        enforceCrossUserPermission(callingUid, userId,
11085                true /* requireFullPermission */, true /* checkShell */, "installPackageAsUser");
11086
11087        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
11088            try {
11089                if (observer != null) {
11090                    observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null);
11091                }
11092            } catch (RemoteException re) {
11093            }
11094            return;
11095        }
11096
11097        if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) {
11098            installFlags |= PackageManager.INSTALL_FROM_ADB;
11099
11100        } else {
11101            // Caller holds INSTALL_PACKAGES permission, so we're less strict
11102            // about installerPackageName.
11103
11104            installFlags &= ~PackageManager.INSTALL_FROM_ADB;
11105            installFlags &= ~PackageManager.INSTALL_ALL_USERS;
11106        }
11107
11108        UserHandle user;
11109        if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) {
11110            user = UserHandle.ALL;
11111        } else {
11112            user = new UserHandle(userId);
11113        }
11114
11115        // Only system components can circumvent runtime permissions when installing.
11116        if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0
11117                && mContext.checkCallingOrSelfPermission(Manifest.permission
11118                .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) {
11119            throw new SecurityException("You need the "
11120                    + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission "
11121                    + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag");
11122        }
11123
11124        final File originFile = new File(originPath);
11125        final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile);
11126
11127        final Message msg = mHandler.obtainMessage(INIT_COPY);
11128        final VerificationInfo verificationInfo = new VerificationInfo(
11129                null /*originatingUri*/, null /*referrer*/, -1 /*originatingUid*/, callingUid);
11130        final InstallParams params = new InstallParams(origin, null /*moveInfo*/, observer,
11131                installFlags, installerPackageName, null /*volumeUuid*/, verificationInfo, user,
11132                null /*packageAbiOverride*/, null /*grantedPermissions*/,
11133                null /*certificates*/);
11134        params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params));
11135        msg.obj = params;
11136
11137        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser",
11138                System.identityHashCode(msg.obj));
11139        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
11140                System.identityHashCode(msg.obj));
11141
11142        mHandler.sendMessage(msg);
11143    }
11144
11145    void installStage(String packageName, File stagedDir, String stagedCid,
11146            IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams,
11147            String installerPackageName, int installerUid, UserHandle user,
11148            Certificate[][] certificates) {
11149        if (DEBUG_EPHEMERAL) {
11150            if ((sessionParams.installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) {
11151                Slog.d(TAG, "Ephemeral install of " + packageName);
11152            }
11153        }
11154        final VerificationInfo verificationInfo = new VerificationInfo(
11155                sessionParams.originatingUri, sessionParams.referrerUri,
11156                sessionParams.originatingUid, installerUid);
11157
11158        final OriginInfo origin;
11159        if (stagedDir != null) {
11160            origin = OriginInfo.fromStagedFile(stagedDir);
11161        } else {
11162            origin = OriginInfo.fromStagedContainer(stagedCid);
11163        }
11164
11165        final Message msg = mHandler.obtainMessage(INIT_COPY);
11166        final InstallParams params = new InstallParams(origin, null, observer,
11167                sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid,
11168                verificationInfo, user, sessionParams.abiOverride,
11169                sessionParams.grantedRuntimePermissions, certificates);
11170        params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params));
11171        msg.obj = params;
11172
11173        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage",
11174                System.identityHashCode(msg.obj));
11175        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
11176                System.identityHashCode(msg.obj));
11177
11178        mHandler.sendMessage(msg);
11179    }
11180
11181    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting,
11182            int userId) {
11183        final boolean isSystem = isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
11184        sendPackageAddedForUser(packageName, isSystem, pkgSetting.appId, userId);
11185    }
11186
11187    private void sendPackageAddedForUser(String packageName, boolean isSystem,
11188            int appId, int userId) {
11189        Bundle extras = new Bundle(1);
11190        extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, appId));
11191
11192        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
11193                packageName, extras, 0, null, null, new int[] {userId});
11194        try {
11195            IActivityManager am = ActivityManagerNative.getDefault();
11196            if (isSystem && am.isUserRunning(userId, 0)) {
11197                // The just-installed/enabled app is bundled on the system, so presumed
11198                // to be able to run automatically without needing an explicit launch.
11199                // Send it a BOOT_COMPLETED if it would ordinarily have gotten one.
11200                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED)
11201                        .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES)
11202                        .setPackage(packageName);
11203                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null,
11204                        android.app.AppOpsManager.OP_NONE, null, false, false, userId);
11205            }
11206        } catch (RemoteException e) {
11207            // shouldn't happen
11208            Slog.w(TAG, "Unable to bootstrap installed package", e);
11209        }
11210    }
11211
11212    @Override
11213    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
11214            int userId) {
11215        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
11216        PackageSetting pkgSetting;
11217        final int uid = Binder.getCallingUid();
11218        enforceCrossUserPermission(uid, userId,
11219                true /* requireFullPermission */, true /* checkShell */,
11220                "setApplicationHiddenSetting for user " + userId);
11221
11222        if (hidden && isPackageDeviceAdmin(packageName, userId)) {
11223            Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
11224            return false;
11225        }
11226
11227        long callingId = Binder.clearCallingIdentity();
11228        try {
11229            boolean sendAdded = false;
11230            boolean sendRemoved = false;
11231            // writer
11232            synchronized (mPackages) {
11233                pkgSetting = mSettings.mPackages.get(packageName);
11234                if (pkgSetting == null) {
11235                    return false;
11236                }
11237                if (pkgSetting.getHidden(userId) != hidden) {
11238                    pkgSetting.setHidden(hidden, userId);
11239                    mSettings.writePackageRestrictionsLPr(userId);
11240                    if (hidden) {
11241                        sendRemoved = true;
11242                    } else {
11243                        sendAdded = true;
11244                    }
11245                }
11246            }
11247            if (sendAdded) {
11248                sendPackageAddedForUser(packageName, pkgSetting, userId);
11249                return true;
11250            }
11251            if (sendRemoved) {
11252                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
11253                        "hiding pkg");
11254                sendApplicationHiddenForUser(packageName, pkgSetting, userId);
11255                return true;
11256            }
11257        } finally {
11258            Binder.restoreCallingIdentity(callingId);
11259        }
11260        return false;
11261    }
11262
11263    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
11264            int userId) {
11265        final PackageRemovedInfo info = new PackageRemovedInfo();
11266        info.removedPackage = packageName;
11267        info.removedUsers = new int[] {userId};
11268        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
11269        info.sendPackageRemovedBroadcasts(true /*killApp*/);
11270    }
11271
11272    private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended) {
11273        if (pkgList.length > 0) {
11274            Bundle extras = new Bundle(1);
11275            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
11276
11277            sendPackageBroadcast(
11278                    suspended ? Intent.ACTION_PACKAGES_SUSPENDED
11279                            : Intent.ACTION_PACKAGES_UNSUSPENDED,
11280                    null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null,
11281                    new int[] {userId});
11282        }
11283    }
11284
11285    /**
11286     * Returns true if application is not found or there was an error. Otherwise it returns
11287     * the hidden state of the package for the given user.
11288     */
11289    @Override
11290    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
11291        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
11292        enforceCrossUserPermission(Binder.getCallingUid(), userId,
11293                true /* requireFullPermission */, false /* checkShell */,
11294                "getApplicationHidden for user " + userId);
11295        PackageSetting pkgSetting;
11296        long callingId = Binder.clearCallingIdentity();
11297        try {
11298            // writer
11299            synchronized (mPackages) {
11300                pkgSetting = mSettings.mPackages.get(packageName);
11301                if (pkgSetting == null) {
11302                    return true;
11303                }
11304                return pkgSetting.getHidden(userId);
11305            }
11306        } finally {
11307            Binder.restoreCallingIdentity(callingId);
11308        }
11309    }
11310
11311    /**
11312     * @hide
11313     */
11314    @Override
11315    public int installExistingPackageAsUser(String packageName, int userId) {
11316        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
11317                null);
11318        PackageSetting pkgSetting;
11319        final int uid = Binder.getCallingUid();
11320        enforceCrossUserPermission(uid, userId,
11321                true /* requireFullPermission */, true /* checkShell */,
11322                "installExistingPackage for user " + userId);
11323        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
11324            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
11325        }
11326
11327        long callingId = Binder.clearCallingIdentity();
11328        try {
11329            boolean installed = false;
11330
11331            // writer
11332            synchronized (mPackages) {
11333                pkgSetting = mSettings.mPackages.get(packageName);
11334                if (pkgSetting == null) {
11335                    return PackageManager.INSTALL_FAILED_INVALID_URI;
11336                }
11337                if (!pkgSetting.getInstalled(userId)) {
11338                    pkgSetting.setInstalled(true, userId);
11339                    pkgSetting.setHidden(false, userId);
11340                    mSettings.writePackageRestrictionsLPr(userId);
11341                    installed = true;
11342                }
11343            }
11344
11345            if (installed) {
11346                if (pkgSetting.pkg != null) {
11347                    synchronized (mInstallLock) {
11348                        // We don't need to freeze for a brand new install
11349                        prepareAppDataAfterInstallLIF(pkgSetting.pkg);
11350                    }
11351                }
11352                sendPackageAddedForUser(packageName, pkgSetting, userId);
11353            }
11354        } finally {
11355            Binder.restoreCallingIdentity(callingId);
11356        }
11357
11358        return PackageManager.INSTALL_SUCCEEDED;
11359    }
11360
11361    boolean isUserRestricted(int userId, String restrictionKey) {
11362        Bundle restrictions = sUserManager.getUserRestrictions(userId);
11363        if (restrictions.getBoolean(restrictionKey, false)) {
11364            Log.w(TAG, "User is restricted: " + restrictionKey);
11365            return true;
11366        }
11367        return false;
11368    }
11369
11370    @Override
11371    public String[] setPackagesSuspendedAsUser(String[] packageNames, boolean suspended,
11372            int userId) {
11373        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
11374        enforceCrossUserPermission(Binder.getCallingUid(), userId,
11375                true /* requireFullPermission */, true /* checkShell */,
11376                "setPackagesSuspended for user " + userId);
11377
11378        if (ArrayUtils.isEmpty(packageNames)) {
11379            return packageNames;
11380        }
11381
11382        // List of package names for whom the suspended state has changed.
11383        List<String> changedPackages = new ArrayList<>(packageNames.length);
11384        // List of package names for whom the suspended state is not set as requested in this
11385        // method.
11386        List<String> unactionedPackages = new ArrayList<>(packageNames.length);
11387        for (int i = 0; i < packageNames.length; i++) {
11388            String packageName = packageNames[i];
11389            long callingId = Binder.clearCallingIdentity();
11390            try {
11391                boolean changed = false;
11392                final int appId;
11393                synchronized (mPackages) {
11394                    final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
11395                    if (pkgSetting == null) {
11396                        Slog.w(TAG, "Could not find package setting for package \"" + packageName
11397                                + "\". Skipping suspending/un-suspending.");
11398                        unactionedPackages.add(packageName);
11399                        continue;
11400                    }
11401                    appId = pkgSetting.appId;
11402                    if (pkgSetting.getSuspended(userId) != suspended) {
11403                        if (!canSuspendPackageForUserLocked(packageName, userId)) {
11404                            unactionedPackages.add(packageName);
11405                            continue;
11406                        }
11407                        pkgSetting.setSuspended(suspended, userId);
11408                        mSettings.writePackageRestrictionsLPr(userId);
11409                        changed = true;
11410                        changedPackages.add(packageName);
11411                    }
11412                }
11413
11414                if (changed && suspended) {
11415                    killApplication(packageName, UserHandle.getUid(userId, appId),
11416                            "suspending package");
11417                }
11418            } finally {
11419                Binder.restoreCallingIdentity(callingId);
11420            }
11421        }
11422
11423        if (!changedPackages.isEmpty()) {
11424            sendPackagesSuspendedForUser(changedPackages.toArray(
11425                    new String[changedPackages.size()]), userId, suspended);
11426        }
11427
11428        return unactionedPackages.toArray(new String[unactionedPackages.size()]);
11429    }
11430
11431    @Override
11432    public boolean isPackageSuspendedForUser(String packageName, int userId) {
11433        enforceCrossUserPermission(Binder.getCallingUid(), userId,
11434                true /* requireFullPermission */, false /* checkShell */,
11435                "isPackageSuspendedForUser for user " + userId);
11436        synchronized (mPackages) {
11437            final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
11438            if (pkgSetting == null) {
11439                throw new IllegalArgumentException("Unknown target package: " + packageName);
11440            }
11441            return pkgSetting.getSuspended(userId);
11442        }
11443    }
11444
11445    /**
11446     * TODO: cache and disallow blocking the active dialer.
11447     *
11448     * @see also DefaultPermissionGrantPolicy#grantDefaultSystemHandlerPermissions
11449     */
11450    private boolean canSuspendPackageForUserLocked(String packageName, int userId) {
11451        if (isPackageDeviceAdmin(packageName, userId)) {
11452            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
11453                    + "\": has an active device admin");
11454            return false;
11455        }
11456
11457        String activeLauncherPackageName = getActiveLauncherPackageName(userId);
11458        if (packageName.equals(activeLauncherPackageName)) {
11459            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
11460                    + "\": contains the active launcher");
11461            return false;
11462        }
11463
11464        if (packageName.equals(mRequiredInstallerPackage)) {
11465            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
11466                    + "\": required for package installation");
11467            return false;
11468        }
11469
11470        if (packageName.equals(mRequiredVerifierPackage)) {
11471            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
11472                    + "\": required for package verification");
11473            return false;
11474        }
11475
11476        final PackageParser.Package pkg = mPackages.get(packageName);
11477        if (pkg != null && isPrivilegedApp(pkg)) {
11478            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
11479                    + "\": is a privileged app");
11480            return false;
11481        }
11482
11483        return true;
11484    }
11485
11486    private String getActiveLauncherPackageName(int userId) {
11487        Intent intent = new Intent(Intent.ACTION_MAIN);
11488        intent.addCategory(Intent.CATEGORY_HOME);
11489        ResolveInfo resolveInfo = resolveIntent(
11490                intent,
11491                intent.resolveTypeIfNeeded(mContext.getContentResolver()),
11492                PackageManager.MATCH_DEFAULT_ONLY,
11493                userId);
11494
11495        return resolveInfo == null ? null : resolveInfo.activityInfo.packageName;
11496    }
11497
11498    @Override
11499    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
11500        mContext.enforceCallingOrSelfPermission(
11501                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
11502                "Only package verification agents can verify applications");
11503
11504        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
11505        final PackageVerificationResponse response = new PackageVerificationResponse(
11506                verificationCode, Binder.getCallingUid());
11507        msg.arg1 = id;
11508        msg.obj = response;
11509        mHandler.sendMessage(msg);
11510    }
11511
11512    @Override
11513    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
11514            long millisecondsToDelay) {
11515        mContext.enforceCallingOrSelfPermission(
11516                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
11517                "Only package verification agents can extend verification timeouts");
11518
11519        final PackageVerificationState state = mPendingVerification.get(id);
11520        final PackageVerificationResponse response = new PackageVerificationResponse(
11521                verificationCodeAtTimeout, Binder.getCallingUid());
11522
11523        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
11524            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
11525        }
11526        if (millisecondsToDelay < 0) {
11527            millisecondsToDelay = 0;
11528        }
11529        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
11530                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
11531            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
11532        }
11533
11534        if ((state != null) && !state.timeoutExtended()) {
11535            state.extendTimeout();
11536
11537            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
11538            msg.arg1 = id;
11539            msg.obj = response;
11540            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
11541        }
11542    }
11543
11544    private void broadcastPackageVerified(int verificationId, Uri packageUri,
11545            int verificationCode, UserHandle user) {
11546        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
11547        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
11548        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
11549        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
11550        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
11551
11552        mContext.sendBroadcastAsUser(intent, user,
11553                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
11554    }
11555
11556    private ComponentName matchComponentForVerifier(String packageName,
11557            List<ResolveInfo> receivers) {
11558        ActivityInfo targetReceiver = null;
11559
11560        final int NR = receivers.size();
11561        for (int i = 0; i < NR; i++) {
11562            final ResolveInfo info = receivers.get(i);
11563            if (info.activityInfo == null) {
11564                continue;
11565            }
11566
11567            if (packageName.equals(info.activityInfo.packageName)) {
11568                targetReceiver = info.activityInfo;
11569                break;
11570            }
11571        }
11572
11573        if (targetReceiver == null) {
11574            return null;
11575        }
11576
11577        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
11578    }
11579
11580    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
11581            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
11582        if (pkgInfo.verifiers.length == 0) {
11583            return null;
11584        }
11585
11586        final int N = pkgInfo.verifiers.length;
11587        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
11588        for (int i = 0; i < N; i++) {
11589            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
11590
11591            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
11592                    receivers);
11593            if (comp == null) {
11594                continue;
11595            }
11596
11597            final int verifierUid = getUidForVerifier(verifierInfo);
11598            if (verifierUid == -1) {
11599                continue;
11600            }
11601
11602            if (DEBUG_VERIFY) {
11603                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
11604                        + " with the correct signature");
11605            }
11606            sufficientVerifiers.add(comp);
11607            verificationState.addSufficientVerifier(verifierUid);
11608        }
11609
11610        return sufficientVerifiers;
11611    }
11612
11613    private int getUidForVerifier(VerifierInfo verifierInfo) {
11614        synchronized (mPackages) {
11615            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
11616            if (pkg == null) {
11617                return -1;
11618            } else if (pkg.mSignatures.length != 1) {
11619                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
11620                        + " has more than one signature; ignoring");
11621                return -1;
11622            }
11623
11624            /*
11625             * If the public key of the package's signature does not match
11626             * our expected public key, then this is a different package and
11627             * we should skip.
11628             */
11629
11630            final byte[] expectedPublicKey;
11631            try {
11632                final Signature verifierSig = pkg.mSignatures[0];
11633                final PublicKey publicKey = verifierSig.getPublicKey();
11634                expectedPublicKey = publicKey.getEncoded();
11635            } catch (CertificateException e) {
11636                return -1;
11637            }
11638
11639            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
11640
11641            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
11642                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
11643                        + " does not have the expected public key; ignoring");
11644                return -1;
11645            }
11646
11647            return pkg.applicationInfo.uid;
11648        }
11649    }
11650
11651    @Override
11652    public void finishPackageInstall(int token) {
11653        enforceSystemOrRoot("Only the system is allowed to finish installs");
11654
11655        if (DEBUG_INSTALL) {
11656            Slog.v(TAG, "BM finishing package install for " + token);
11657        }
11658        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
11659
11660        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
11661        mHandler.sendMessage(msg);
11662    }
11663
11664    /**
11665     * Get the verification agent timeout.
11666     *
11667     * @return verification timeout in milliseconds
11668     */
11669    private long getVerificationTimeout() {
11670        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
11671                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
11672                DEFAULT_VERIFICATION_TIMEOUT);
11673    }
11674
11675    /**
11676     * Get the default verification agent response code.
11677     *
11678     * @return default verification response code
11679     */
11680    private int getDefaultVerificationResponse() {
11681        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
11682                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
11683                DEFAULT_VERIFICATION_RESPONSE);
11684    }
11685
11686    /**
11687     * Check whether or not package verification has been enabled.
11688     *
11689     * @return true if verification should be performed
11690     */
11691    private boolean isVerificationEnabled(int userId, int installFlags) {
11692        if (!DEFAULT_VERIFY_ENABLE) {
11693            return false;
11694        }
11695        // Ephemeral apps don't get the full verification treatment
11696        if ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) {
11697            if (DEBUG_EPHEMERAL) {
11698                Slog.d(TAG, "INSTALL_EPHEMERAL so skipping verification");
11699            }
11700            return false;
11701        }
11702
11703        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
11704
11705        // Check if installing from ADB
11706        if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
11707            // Do not run verification in a test harness environment
11708            if (ActivityManager.isRunningInTestHarness()) {
11709                return false;
11710            }
11711            if (ensureVerifyAppsEnabled) {
11712                return true;
11713            }
11714            // Check if the developer does not want package verification for ADB installs
11715            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
11716                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
11717                return false;
11718            }
11719        }
11720
11721        if (ensureVerifyAppsEnabled) {
11722            return true;
11723        }
11724
11725        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
11726                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
11727    }
11728
11729    @Override
11730    public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains)
11731            throws RemoteException {
11732        mContext.enforceCallingOrSelfPermission(
11733                Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
11734                "Only intentfilter verification agents can verify applications");
11735
11736        final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED);
11737        final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse(
11738                Binder.getCallingUid(), verificationCode, failedDomains);
11739        msg.arg1 = id;
11740        msg.obj = response;
11741        mHandler.sendMessage(msg);
11742    }
11743
11744    @Override
11745    public int getIntentVerificationStatus(String packageName, int userId) {
11746        synchronized (mPackages) {
11747            return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
11748        }
11749    }
11750
11751    @Override
11752    public boolean updateIntentVerificationStatus(String packageName, int status, int userId) {
11753        mContext.enforceCallingOrSelfPermission(
11754                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
11755
11756        boolean result = false;
11757        synchronized (mPackages) {
11758            result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId);
11759        }
11760        if (result) {
11761            scheduleWritePackageRestrictionsLocked(userId);
11762        }
11763        return result;
11764    }
11765
11766    @Override
11767    public @NonNull ParceledListSlice<IntentFilterVerificationInfo> getIntentFilterVerifications(
11768            String packageName) {
11769        synchronized (mPackages) {
11770            return new ParceledListSlice<>(mSettings.getIntentFilterVerificationsLPr(packageName));
11771        }
11772    }
11773
11774    @Override
11775    public @NonNull ParceledListSlice<IntentFilter> getAllIntentFilters(String packageName) {
11776        if (TextUtils.isEmpty(packageName)) {
11777            return ParceledListSlice.emptyList();
11778        }
11779        synchronized (mPackages) {
11780            PackageParser.Package pkg = mPackages.get(packageName);
11781            if (pkg == null || pkg.activities == null) {
11782                return ParceledListSlice.emptyList();
11783            }
11784            final int count = pkg.activities.size();
11785            ArrayList<IntentFilter> result = new ArrayList<>();
11786            for (int n=0; n<count; n++) {
11787                PackageParser.Activity activity = pkg.activities.get(n);
11788                if (activity.intents != null && activity.intents.size() > 0) {
11789                    result.addAll(activity.intents);
11790                }
11791            }
11792            return new ParceledListSlice<>(result);
11793        }
11794    }
11795
11796    @Override
11797    public boolean setDefaultBrowserPackageName(String packageName, int userId) {
11798        mContext.enforceCallingOrSelfPermission(
11799                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
11800
11801        synchronized (mPackages) {
11802            boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId);
11803            if (packageName != null) {
11804                result |= updateIntentVerificationStatus(packageName,
11805                        PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS,
11806                        userId);
11807                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr(
11808                        packageName, userId);
11809            }
11810            return result;
11811        }
11812    }
11813
11814    @Override
11815    public String getDefaultBrowserPackageName(int userId) {
11816        synchronized (mPackages) {
11817            return mSettings.getDefaultBrowserPackageNameLPw(userId);
11818        }
11819    }
11820
11821    /**
11822     * Get the "allow unknown sources" setting.
11823     *
11824     * @return the current "allow unknown sources" setting
11825     */
11826    private int getUnknownSourcesSettings() {
11827        return android.provider.Settings.Secure.getInt(mContext.getContentResolver(),
11828                android.provider.Settings.Secure.INSTALL_NON_MARKET_APPS,
11829                -1);
11830    }
11831
11832    @Override
11833    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
11834        final int uid = Binder.getCallingUid();
11835        // writer
11836        synchronized (mPackages) {
11837            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
11838            if (targetPackageSetting == null) {
11839                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
11840            }
11841
11842            PackageSetting installerPackageSetting;
11843            if (installerPackageName != null) {
11844                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
11845                if (installerPackageSetting == null) {
11846                    throw new IllegalArgumentException("Unknown installer package: "
11847                            + installerPackageName);
11848                }
11849            } else {
11850                installerPackageSetting = null;
11851            }
11852
11853            Signature[] callerSignature;
11854            Object obj = mSettings.getUserIdLPr(uid);
11855            if (obj != null) {
11856                if (obj instanceof SharedUserSetting) {
11857                    callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
11858                } else if (obj instanceof PackageSetting) {
11859                    callerSignature = ((PackageSetting)obj).signatures.mSignatures;
11860                } else {
11861                    throw new SecurityException("Bad object " + obj + " for uid " + uid);
11862                }
11863            } else {
11864                throw new SecurityException("Unknown calling UID: " + uid);
11865            }
11866
11867            // Verify: can't set installerPackageName to a package that is
11868            // not signed with the same cert as the caller.
11869            if (installerPackageSetting != null) {
11870                if (compareSignatures(callerSignature,
11871                        installerPackageSetting.signatures.mSignatures)
11872                        != PackageManager.SIGNATURE_MATCH) {
11873                    throw new SecurityException(
11874                            "Caller does not have same cert as new installer package "
11875                            + installerPackageName);
11876                }
11877            }
11878
11879            // Verify: if target already has an installer package, it must
11880            // be signed with the same cert as the caller.
11881            if (targetPackageSetting.installerPackageName != null) {
11882                PackageSetting setting = mSettings.mPackages.get(
11883                        targetPackageSetting.installerPackageName);
11884                // If the currently set package isn't valid, then it's always
11885                // okay to change it.
11886                if (setting != null) {
11887                    if (compareSignatures(callerSignature,
11888                            setting.signatures.mSignatures)
11889                            != PackageManager.SIGNATURE_MATCH) {
11890                        throw new SecurityException(
11891                                "Caller does not have same cert as old installer package "
11892                                + targetPackageSetting.installerPackageName);
11893                    }
11894                }
11895            }
11896
11897            // Okay!
11898            targetPackageSetting.installerPackageName = installerPackageName;
11899            if (installerPackageName != null) {
11900                mSettings.mInstallerPackages.add(installerPackageName);
11901            }
11902            scheduleWriteSettingsLocked();
11903        }
11904    }
11905
11906    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
11907        // Queue up an async operation since the package installation may take a little while.
11908        mHandler.post(new Runnable() {
11909            public void run() {
11910                mHandler.removeCallbacks(this);
11911                 // Result object to be returned
11912                PackageInstalledInfo res = new PackageInstalledInfo();
11913                res.setReturnCode(currentStatus);
11914                res.uid = -1;
11915                res.pkg = null;
11916                res.removedInfo = null;
11917                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
11918                    args.doPreInstall(res.returnCode);
11919                    synchronized (mInstallLock) {
11920                        installPackageTracedLI(args, res);
11921                    }
11922                    args.doPostInstall(res.returnCode, res.uid);
11923                }
11924
11925                // A restore should be performed at this point if (a) the install
11926                // succeeded, (b) the operation is not an update, and (c) the new
11927                // package has not opted out of backup participation.
11928                final boolean update = res.removedInfo != null
11929                        && res.removedInfo.removedPackage != null;
11930                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
11931                boolean doRestore = !update
11932                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
11933
11934                // Set up the post-install work request bookkeeping.  This will be used
11935                // and cleaned up by the post-install event handling regardless of whether
11936                // there's a restore pass performed.  Token values are >= 1.
11937                int token;
11938                if (mNextInstallToken < 0) mNextInstallToken = 1;
11939                token = mNextInstallToken++;
11940
11941                PostInstallData data = new PostInstallData(args, res);
11942                mRunningInstalls.put(token, data);
11943                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
11944
11945                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
11946                    // Pass responsibility to the Backup Manager.  It will perform a
11947                    // restore if appropriate, then pass responsibility back to the
11948                    // Package Manager to run the post-install observer callbacks
11949                    // and broadcasts.
11950                    IBackupManager bm = IBackupManager.Stub.asInterface(
11951                            ServiceManager.getService(Context.BACKUP_SERVICE));
11952                    if (bm != null) {
11953                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
11954                                + " to BM for possible restore");
11955                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
11956                        try {
11957                            // TODO: http://b/22388012
11958                            if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) {
11959                                bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
11960                            } else {
11961                                doRestore = false;
11962                            }
11963                        } catch (RemoteException e) {
11964                            // can't happen; the backup manager is local
11965                        } catch (Exception e) {
11966                            Slog.e(TAG, "Exception trying to enqueue restore", e);
11967                            doRestore = false;
11968                        }
11969                    } else {
11970                        Slog.e(TAG, "Backup Manager not found!");
11971                        doRestore = false;
11972                    }
11973                }
11974
11975                if (!doRestore) {
11976                    // No restore possible, or the Backup Manager was mysteriously not
11977                    // available -- just fire the post-install work request directly.
11978                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
11979
11980                    Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token);
11981
11982                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
11983                    mHandler.sendMessage(msg);
11984                }
11985            }
11986        });
11987    }
11988
11989    private abstract class HandlerParams {
11990        private static final int MAX_RETRIES = 4;
11991
11992        /**
11993         * Number of times startCopy() has been attempted and had a non-fatal
11994         * error.
11995         */
11996        private int mRetries = 0;
11997
11998        /** User handle for the user requesting the information or installation. */
11999        private final UserHandle mUser;
12000        String traceMethod;
12001        int traceCookie;
12002
12003        HandlerParams(UserHandle user) {
12004            mUser = user;
12005        }
12006
12007        UserHandle getUser() {
12008            return mUser;
12009        }
12010
12011        HandlerParams setTraceMethod(String traceMethod) {
12012            this.traceMethod = traceMethod;
12013            return this;
12014        }
12015
12016        HandlerParams setTraceCookie(int traceCookie) {
12017            this.traceCookie = traceCookie;
12018            return this;
12019        }
12020
12021        final boolean startCopy() {
12022            boolean res;
12023            try {
12024                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
12025
12026                if (++mRetries > MAX_RETRIES) {
12027                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
12028                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
12029                    handleServiceError();
12030                    return false;
12031                } else {
12032                    handleStartCopy();
12033                    res = true;
12034                }
12035            } catch (RemoteException e) {
12036                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
12037                mHandler.sendEmptyMessage(MCS_RECONNECT);
12038                res = false;
12039            }
12040            handleReturnCode();
12041            return res;
12042        }
12043
12044        final void serviceError() {
12045            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
12046            handleServiceError();
12047            handleReturnCode();
12048        }
12049
12050        abstract void handleStartCopy() throws RemoteException;
12051        abstract void handleServiceError();
12052        abstract void handleReturnCode();
12053    }
12054
12055    class MeasureParams extends HandlerParams {
12056        private final PackageStats mStats;
12057        private boolean mSuccess;
12058
12059        private final IPackageStatsObserver mObserver;
12060
12061        public MeasureParams(PackageStats stats, IPackageStatsObserver observer) {
12062            super(new UserHandle(stats.userHandle));
12063            mObserver = observer;
12064            mStats = stats;
12065        }
12066
12067        @Override
12068        public String toString() {
12069            return "MeasureParams{"
12070                + Integer.toHexString(System.identityHashCode(this))
12071                + " " + mStats.packageName + "}";
12072        }
12073
12074        @Override
12075        void handleStartCopy() throws RemoteException {
12076            synchronized (mInstallLock) {
12077                mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats);
12078            }
12079
12080            if (mSuccess) {
12081                final boolean mounted;
12082                if (Environment.isExternalStorageEmulated()) {
12083                    mounted = true;
12084                } else {
12085                    final String status = Environment.getExternalStorageState();
12086                    mounted = (Environment.MEDIA_MOUNTED.equals(status)
12087                            || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status));
12088                }
12089
12090                if (mounted) {
12091                    final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle);
12092
12093                    mStats.externalCacheSize = calculateDirectorySize(mContainerService,
12094                            userEnv.buildExternalStorageAppCacheDirs(mStats.packageName));
12095
12096                    mStats.externalDataSize = calculateDirectorySize(mContainerService,
12097                            userEnv.buildExternalStorageAppDataDirs(mStats.packageName));
12098
12099                    // Always subtract cache size, since it's a subdirectory
12100                    mStats.externalDataSize -= mStats.externalCacheSize;
12101
12102                    mStats.externalMediaSize = calculateDirectorySize(mContainerService,
12103                            userEnv.buildExternalStorageAppMediaDirs(mStats.packageName));
12104
12105                    mStats.externalObbSize = calculateDirectorySize(mContainerService,
12106                            userEnv.buildExternalStorageAppObbDirs(mStats.packageName));
12107                }
12108            }
12109        }
12110
12111        @Override
12112        void handleReturnCode() {
12113            if (mObserver != null) {
12114                try {
12115                    mObserver.onGetStatsCompleted(mStats, mSuccess);
12116                } catch (RemoteException e) {
12117                    Slog.i(TAG, "Observer no longer exists.");
12118                }
12119            }
12120        }
12121
12122        @Override
12123        void handleServiceError() {
12124            Slog.e(TAG, "Could not measure application " + mStats.packageName
12125                            + " external storage");
12126        }
12127    }
12128
12129    private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths)
12130            throws RemoteException {
12131        long result = 0;
12132        for (File path : paths) {
12133            result += mcs.calculateDirectorySize(path.getAbsolutePath());
12134        }
12135        return result;
12136    }
12137
12138    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
12139        for (File path : paths) {
12140            try {
12141                mcs.clearDirectory(path.getAbsolutePath());
12142            } catch (RemoteException e) {
12143            }
12144        }
12145    }
12146
12147    static class OriginInfo {
12148        /**
12149         * Location where install is coming from, before it has been
12150         * copied/renamed into place. This could be a single monolithic APK
12151         * file, or a cluster directory. This location may be untrusted.
12152         */
12153        final File file;
12154        final String cid;
12155
12156        /**
12157         * Flag indicating that {@link #file} or {@link #cid} has already been
12158         * staged, meaning downstream users don't need to defensively copy the
12159         * contents.
12160         */
12161        final boolean staged;
12162
12163        /**
12164         * Flag indicating that {@link #file} or {@link #cid} is an already
12165         * installed app that is being moved.
12166         */
12167        final boolean existing;
12168
12169        final String resolvedPath;
12170        final File resolvedFile;
12171
12172        static OriginInfo fromNothing() {
12173            return new OriginInfo(null, null, false, false);
12174        }
12175
12176        static OriginInfo fromUntrustedFile(File file) {
12177            return new OriginInfo(file, null, false, false);
12178        }
12179
12180        static OriginInfo fromExistingFile(File file) {
12181            return new OriginInfo(file, null, false, true);
12182        }
12183
12184        static OriginInfo fromStagedFile(File file) {
12185            return new OriginInfo(file, null, true, false);
12186        }
12187
12188        static OriginInfo fromStagedContainer(String cid) {
12189            return new OriginInfo(null, cid, true, false);
12190        }
12191
12192        private OriginInfo(File file, String cid, boolean staged, boolean existing) {
12193            this.file = file;
12194            this.cid = cid;
12195            this.staged = staged;
12196            this.existing = existing;
12197
12198            if (cid != null) {
12199                resolvedPath = PackageHelper.getSdDir(cid);
12200                resolvedFile = new File(resolvedPath);
12201            } else if (file != null) {
12202                resolvedPath = file.getAbsolutePath();
12203                resolvedFile = file;
12204            } else {
12205                resolvedPath = null;
12206                resolvedFile = null;
12207            }
12208        }
12209    }
12210
12211    static class MoveInfo {
12212        final int moveId;
12213        final String fromUuid;
12214        final String toUuid;
12215        final String packageName;
12216        final String dataAppName;
12217        final int appId;
12218        final String seinfo;
12219        final int targetSdkVersion;
12220
12221        public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName,
12222                String dataAppName, int appId, String seinfo, int targetSdkVersion) {
12223            this.moveId = moveId;
12224            this.fromUuid = fromUuid;
12225            this.toUuid = toUuid;
12226            this.packageName = packageName;
12227            this.dataAppName = dataAppName;
12228            this.appId = appId;
12229            this.seinfo = seinfo;
12230            this.targetSdkVersion = targetSdkVersion;
12231        }
12232    }
12233
12234    static class VerificationInfo {
12235        /** A constant used to indicate that a uid value is not present. */
12236        public static final int NO_UID = -1;
12237
12238        /** URI referencing where the package was downloaded from. */
12239        final Uri originatingUri;
12240
12241        /** HTTP referrer URI associated with the originatingURI. */
12242        final Uri referrer;
12243
12244        /** UID of the application that the install request originated from. */
12245        final int originatingUid;
12246
12247        /** UID of application requesting the install */
12248        final int installerUid;
12249
12250        VerificationInfo(Uri originatingUri, Uri referrer, int originatingUid, int installerUid) {
12251            this.originatingUri = originatingUri;
12252            this.referrer = referrer;
12253            this.originatingUid = originatingUid;
12254            this.installerUid = installerUid;
12255        }
12256    }
12257
12258    class InstallParams extends HandlerParams {
12259        final OriginInfo origin;
12260        final MoveInfo move;
12261        final IPackageInstallObserver2 observer;
12262        int installFlags;
12263        final String installerPackageName;
12264        final String volumeUuid;
12265        private InstallArgs mArgs;
12266        private int mRet;
12267        final String packageAbiOverride;
12268        final String[] grantedRuntimePermissions;
12269        final VerificationInfo verificationInfo;
12270        final Certificate[][] certificates;
12271
12272        InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
12273                int installFlags, String installerPackageName, String volumeUuid,
12274                VerificationInfo verificationInfo, UserHandle user, String packageAbiOverride,
12275                String[] grantedPermissions, Certificate[][] certificates) {
12276            super(user);
12277            this.origin = origin;
12278            this.move = move;
12279            this.observer = observer;
12280            this.installFlags = installFlags;
12281            this.installerPackageName = installerPackageName;
12282            this.volumeUuid = volumeUuid;
12283            this.verificationInfo = verificationInfo;
12284            this.packageAbiOverride = packageAbiOverride;
12285            this.grantedRuntimePermissions = grantedPermissions;
12286            this.certificates = certificates;
12287        }
12288
12289        @Override
12290        public String toString() {
12291            return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
12292                    + " file=" + origin.file + " cid=" + origin.cid + "}";
12293        }
12294
12295        private int installLocationPolicy(PackageInfoLite pkgLite) {
12296            String packageName = pkgLite.packageName;
12297            int installLocation = pkgLite.installLocation;
12298            boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
12299            // reader
12300            synchronized (mPackages) {
12301                // Currently installed package which the new package is attempting to replace or
12302                // null if no such package is installed.
12303                PackageParser.Package installedPkg = mPackages.get(packageName);
12304                // Package which currently owns the data which the new package will own if installed.
12305                // If an app is unstalled while keeping data (e.g., adb uninstall -k), installedPkg
12306                // will be null whereas dataOwnerPkg will contain information about the package
12307                // which was uninstalled while keeping its data.
12308                PackageParser.Package dataOwnerPkg = installedPkg;
12309                if (dataOwnerPkg  == null) {
12310                    PackageSetting ps = mSettings.mPackages.get(packageName);
12311                    if (ps != null) {
12312                        dataOwnerPkg = ps.pkg;
12313                    }
12314                }
12315
12316                if (dataOwnerPkg != null) {
12317                    // If installed, the package will get access to data left on the device by its
12318                    // predecessor. As a security measure, this is permited only if this is not a
12319                    // version downgrade or if the predecessor package is marked as debuggable and
12320                    // a downgrade is explicitly requested.
12321                    //
12322                    // On debuggable platform builds, downgrades are permitted even for
12323                    // non-debuggable packages to make testing easier. Debuggable platform builds do
12324                    // not offer security guarantees and thus it's OK to disable some security
12325                    // mechanisms to make debugging/testing easier on those builds. However, even on
12326                    // debuggable builds downgrades of packages are permitted only if requested via
12327                    // installFlags. This is because we aim to keep the behavior of debuggable
12328                    // platform builds as close as possible to the behavior of non-debuggable
12329                    // platform builds.
12330                    final boolean downgradeRequested =
12331                            (installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) != 0;
12332                    final boolean packageDebuggable =
12333                                (dataOwnerPkg.applicationInfo.flags
12334                                        & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
12335                    final boolean downgradePermitted =
12336                            (downgradeRequested) && ((Build.IS_DEBUGGABLE) || (packageDebuggable));
12337                    if (!downgradePermitted) {
12338                        try {
12339                            checkDowngrade(dataOwnerPkg, pkgLite);
12340                        } catch (PackageManagerException e) {
12341                            Slog.w(TAG, "Downgrade detected: " + e.getMessage());
12342                            return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
12343                        }
12344                    }
12345                }
12346
12347                if (installedPkg != null) {
12348                    if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
12349                        // Check for updated system application.
12350                        if ((installedPkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
12351                            if (onSd) {
12352                                Slog.w(TAG, "Cannot install update to system app on sdcard");
12353                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
12354                            }
12355                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
12356                        } else {
12357                            if (onSd) {
12358                                // Install flag overrides everything.
12359                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
12360                            }
12361                            // If current upgrade specifies particular preference
12362                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
12363                                // Application explicitly specified internal.
12364                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
12365                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
12366                                // App explictly prefers external. Let policy decide
12367                            } else {
12368                                // Prefer previous location
12369                                if (isExternal(installedPkg)) {
12370                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
12371                                }
12372                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
12373                            }
12374                        }
12375                    } else {
12376                        // Invalid install. Return error code
12377                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
12378                    }
12379                }
12380            }
12381            // All the special cases have been taken care of.
12382            // Return result based on recommended install location.
12383            if (onSd) {
12384                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
12385            }
12386            return pkgLite.recommendedInstallLocation;
12387        }
12388
12389        /*
12390         * Invoke remote method to get package information and install
12391         * location values. Override install location based on default
12392         * policy if needed and then create install arguments based
12393         * on the install location.
12394         */
12395        public void handleStartCopy() throws RemoteException {
12396            int ret = PackageManager.INSTALL_SUCCEEDED;
12397
12398            // If we're already staged, we've firmly committed to an install location
12399            if (origin.staged) {
12400                if (origin.file != null) {
12401                    installFlags |= PackageManager.INSTALL_INTERNAL;
12402                    installFlags &= ~PackageManager.INSTALL_EXTERNAL;
12403                } else if (origin.cid != null) {
12404                    installFlags |= PackageManager.INSTALL_EXTERNAL;
12405                    installFlags &= ~PackageManager.INSTALL_INTERNAL;
12406                } else {
12407                    throw new IllegalStateException("Invalid stage location");
12408                }
12409            }
12410
12411            final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
12412            final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
12413            final boolean ephemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0;
12414            PackageInfoLite pkgLite = null;
12415
12416            if (onInt && onSd) {
12417                // Check if both bits are set.
12418                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
12419                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
12420            } else if (onSd && ephemeral) {
12421                Slog.w(TAG,  "Conflicting flags specified for installing ephemeral on external");
12422                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
12423            } else {
12424                pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
12425                        packageAbiOverride);
12426
12427                if (DEBUG_EPHEMERAL && ephemeral) {
12428                    Slog.v(TAG, "pkgLite for install: " + pkgLite);
12429                }
12430
12431                /*
12432                 * If we have too little free space, try to free cache
12433                 * before giving up.
12434                 */
12435                if (!origin.staged && pkgLite.recommendedInstallLocation
12436                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
12437                    // TODO: focus freeing disk space on the target device
12438                    final StorageManager storage = StorageManager.from(mContext);
12439                    final long lowThreshold = storage.getStorageLowBytes(
12440                            Environment.getDataDirectory());
12441
12442                    final long sizeBytes = mContainerService.calculateInstalledSize(
12443                            origin.resolvedPath, isForwardLocked(), packageAbiOverride);
12444
12445                    try {
12446                        mInstaller.freeCache(null, sizeBytes + lowThreshold);
12447                        pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
12448                                installFlags, packageAbiOverride);
12449                    } catch (InstallerException e) {
12450                        Slog.w(TAG, "Failed to free cache", e);
12451                    }
12452
12453                    /*
12454                     * The cache free must have deleted the file we
12455                     * downloaded to install.
12456                     *
12457                     * TODO: fix the "freeCache" call to not delete
12458                     *       the file we care about.
12459                     */
12460                    if (pkgLite.recommendedInstallLocation
12461                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
12462                        pkgLite.recommendedInstallLocation
12463                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
12464                    }
12465                }
12466            }
12467
12468            if (ret == PackageManager.INSTALL_SUCCEEDED) {
12469                int loc = pkgLite.recommendedInstallLocation;
12470                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
12471                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
12472                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
12473                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
12474                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
12475                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
12476                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
12477                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
12478                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
12479                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
12480                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
12481                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
12482                } else {
12483                    // Override with defaults if needed.
12484                    loc = installLocationPolicy(pkgLite);
12485                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
12486                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
12487                    } else if (!onSd && !onInt) {
12488                        // Override install location with flags
12489                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
12490                            // Set the flag to install on external media.
12491                            installFlags |= PackageManager.INSTALL_EXTERNAL;
12492                            installFlags &= ~PackageManager.INSTALL_INTERNAL;
12493                        } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) {
12494                            if (DEBUG_EPHEMERAL) {
12495                                Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag");
12496                            }
12497                            installFlags |= PackageManager.INSTALL_EPHEMERAL;
12498                            installFlags &= ~(PackageManager.INSTALL_EXTERNAL
12499                                    |PackageManager.INSTALL_INTERNAL);
12500                        } else {
12501                            // Make sure the flag for installing on external
12502                            // media is unset
12503                            installFlags |= PackageManager.INSTALL_INTERNAL;
12504                            installFlags &= ~PackageManager.INSTALL_EXTERNAL;
12505                        }
12506                    }
12507                }
12508            }
12509
12510            final InstallArgs args = createInstallArgs(this);
12511            mArgs = args;
12512
12513            if (ret == PackageManager.INSTALL_SUCCEEDED) {
12514                // TODO: http://b/22976637
12515                // Apps installed for "all" users use the device owner to verify the app
12516                UserHandle verifierUser = getUser();
12517                if (verifierUser == UserHandle.ALL) {
12518                    verifierUser = UserHandle.SYSTEM;
12519                }
12520
12521                /*
12522                 * Determine if we have any installed package verifiers. If we
12523                 * do, then we'll defer to them to verify the packages.
12524                 */
12525                final int requiredUid = mRequiredVerifierPackage == null ? -1
12526                        : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
12527                                verifierUser.getIdentifier());
12528                if (!origin.existing && requiredUid != -1
12529                        && isVerificationEnabled(verifierUser.getIdentifier(), installFlags)) {
12530                    final Intent verification = new Intent(
12531                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
12532                    verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
12533                    verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
12534                            PACKAGE_MIME_TYPE);
12535                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
12536
12537                    // Query all live verifiers based on current user state
12538                    final List<ResolveInfo> receivers = queryIntentReceiversInternal(verification,
12539                            PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier());
12540
12541                    if (DEBUG_VERIFY) {
12542                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
12543                                + verification.toString() + " with " + pkgLite.verifiers.length
12544                                + " optional verifiers");
12545                    }
12546
12547                    final int verificationId = mPendingVerificationToken++;
12548
12549                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
12550
12551                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
12552                            installerPackageName);
12553
12554                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
12555                            installFlags);
12556
12557                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
12558                            pkgLite.packageName);
12559
12560                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
12561                            pkgLite.versionCode);
12562
12563                    if (verificationInfo != null) {
12564                        if (verificationInfo.originatingUri != null) {
12565                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
12566                                    verificationInfo.originatingUri);
12567                        }
12568                        if (verificationInfo.referrer != null) {
12569                            verification.putExtra(Intent.EXTRA_REFERRER,
12570                                    verificationInfo.referrer);
12571                        }
12572                        if (verificationInfo.originatingUid >= 0) {
12573                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
12574                                    verificationInfo.originatingUid);
12575                        }
12576                        if (verificationInfo.installerUid >= 0) {
12577                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
12578                                    verificationInfo.installerUid);
12579                        }
12580                    }
12581
12582                    final PackageVerificationState verificationState = new PackageVerificationState(
12583                            requiredUid, args);
12584
12585                    mPendingVerification.append(verificationId, verificationState);
12586
12587                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
12588                            receivers, verificationState);
12589
12590                    /*
12591                     * If any sufficient verifiers were listed in the package
12592                     * manifest, attempt to ask them.
12593                     */
12594                    if (sufficientVerifiers != null) {
12595                        final int N = sufficientVerifiers.size();
12596                        if (N == 0) {
12597                            Slog.i(TAG, "Additional verifiers required, but none installed.");
12598                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
12599                        } else {
12600                            for (int i = 0; i < N; i++) {
12601                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
12602
12603                                final Intent sufficientIntent = new Intent(verification);
12604                                sufficientIntent.setComponent(verifierComponent);
12605                                mContext.sendBroadcastAsUser(sufficientIntent, verifierUser);
12606                            }
12607                        }
12608                    }
12609
12610                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
12611                            mRequiredVerifierPackage, receivers);
12612                    if (ret == PackageManager.INSTALL_SUCCEEDED
12613                            && mRequiredVerifierPackage != null) {
12614                        Trace.asyncTraceBegin(
12615                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
12616                        /*
12617                         * Send the intent to the required verification agent,
12618                         * but only start the verification timeout after the
12619                         * target BroadcastReceivers have run.
12620                         */
12621                        verification.setComponent(requiredVerifierComponent);
12622                        mContext.sendOrderedBroadcastAsUser(verification, verifierUser,
12623                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
12624                                new BroadcastReceiver() {
12625                                    @Override
12626                                    public void onReceive(Context context, Intent intent) {
12627                                        final Message msg = mHandler
12628                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
12629                                        msg.arg1 = verificationId;
12630                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
12631                                    }
12632                                }, null, 0, null, null);
12633
12634                        /*
12635                         * We don't want the copy to proceed until verification
12636                         * succeeds, so null out this field.
12637                         */
12638                        mArgs = null;
12639                    }
12640                } else {
12641                    /*
12642                     * No package verification is enabled, so immediately start
12643                     * the remote call to initiate copy using temporary file.
12644                     */
12645                    ret = args.copyApk(mContainerService, true);
12646                }
12647            }
12648
12649            mRet = ret;
12650        }
12651
12652        @Override
12653        void handleReturnCode() {
12654            // If mArgs is null, then MCS couldn't be reached. When it
12655            // reconnects, it will try again to install. At that point, this
12656            // will succeed.
12657            if (mArgs != null) {
12658                processPendingInstall(mArgs, mRet);
12659            }
12660        }
12661
12662        @Override
12663        void handleServiceError() {
12664            mArgs = createInstallArgs(this);
12665            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
12666        }
12667
12668        public boolean isForwardLocked() {
12669            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
12670        }
12671    }
12672
12673    /**
12674     * Used during creation of InstallArgs
12675     *
12676     * @param installFlags package installation flags
12677     * @return true if should be installed on external storage
12678     */
12679    private static boolean installOnExternalAsec(int installFlags) {
12680        if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) {
12681            return false;
12682        }
12683        if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
12684            return true;
12685        }
12686        return false;
12687    }
12688
12689    /**
12690     * Used during creation of InstallArgs
12691     *
12692     * @param installFlags package installation flags
12693     * @return true if should be installed as forward locked
12694     */
12695    private static boolean installForwardLocked(int installFlags) {
12696        return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
12697    }
12698
12699    private InstallArgs createInstallArgs(InstallParams params) {
12700        if (params.move != null) {
12701            return new MoveInstallArgs(params);
12702        } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) {
12703            return new AsecInstallArgs(params);
12704        } else {
12705            return new FileInstallArgs(params);
12706        }
12707    }
12708
12709    /**
12710     * Create args that describe an existing installed package. Typically used
12711     * when cleaning up old installs, or used as a move source.
12712     */
12713    private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
12714            String resourcePath, String[] instructionSets) {
12715        final boolean isInAsec;
12716        if (installOnExternalAsec(installFlags)) {
12717            /* Apps on SD card are always in ASEC containers. */
12718            isInAsec = true;
12719        } else if (installForwardLocked(installFlags)
12720                && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) {
12721            /*
12722             * Forward-locked apps are only in ASEC containers if they're the
12723             * new style
12724             */
12725            isInAsec = true;
12726        } else {
12727            isInAsec = false;
12728        }
12729
12730        if (isInAsec) {
12731            return new AsecInstallArgs(codePath, instructionSets,
12732                    installOnExternalAsec(installFlags), installForwardLocked(installFlags));
12733        } else {
12734            return new FileInstallArgs(codePath, resourcePath, instructionSets);
12735        }
12736    }
12737
12738    static abstract class InstallArgs {
12739        /** @see InstallParams#origin */
12740        final OriginInfo origin;
12741        /** @see InstallParams#move */
12742        final MoveInfo move;
12743
12744        final IPackageInstallObserver2 observer;
12745        // Always refers to PackageManager flags only
12746        final int installFlags;
12747        final String installerPackageName;
12748        final String volumeUuid;
12749        final UserHandle user;
12750        final String abiOverride;
12751        final String[] installGrantPermissions;
12752        /** If non-null, drop an async trace when the install completes */
12753        final String traceMethod;
12754        final int traceCookie;
12755        final Certificate[][] certificates;
12756
12757        // The list of instruction sets supported by this app. This is currently
12758        // only used during the rmdex() phase to clean up resources. We can get rid of this
12759        // if we move dex files under the common app path.
12760        /* nullable */ String[] instructionSets;
12761
12762        InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
12763                int installFlags, String installerPackageName, String volumeUuid,
12764                UserHandle user, String[] instructionSets,
12765                String abiOverride, String[] installGrantPermissions,
12766                String traceMethod, int traceCookie, Certificate[][] certificates) {
12767            this.origin = origin;
12768            this.move = move;
12769            this.installFlags = installFlags;
12770            this.observer = observer;
12771            this.installerPackageName = installerPackageName;
12772            this.volumeUuid = volumeUuid;
12773            this.user = user;
12774            this.instructionSets = instructionSets;
12775            this.abiOverride = abiOverride;
12776            this.installGrantPermissions = installGrantPermissions;
12777            this.traceMethod = traceMethod;
12778            this.traceCookie = traceCookie;
12779            this.certificates = certificates;
12780        }
12781
12782        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
12783        abstract int doPreInstall(int status);
12784
12785        /**
12786         * Rename package into final resting place. All paths on the given
12787         * scanned package should be updated to reflect the rename.
12788         */
12789        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
12790        abstract int doPostInstall(int status, int uid);
12791
12792        /** @see PackageSettingBase#codePathString */
12793        abstract String getCodePath();
12794        /** @see PackageSettingBase#resourcePathString */
12795        abstract String getResourcePath();
12796
12797        // Need installer lock especially for dex file removal.
12798        abstract void cleanUpResourcesLI();
12799        abstract boolean doPostDeleteLI(boolean delete);
12800
12801        /**
12802         * Called before the source arguments are copied. This is used mostly
12803         * for MoveParams when it needs to read the source file to put it in the
12804         * destination.
12805         */
12806        int doPreCopy() {
12807            return PackageManager.INSTALL_SUCCEEDED;
12808        }
12809
12810        /**
12811         * Called after the source arguments are copied. This is used mostly for
12812         * MoveParams when it needs to read the source file to put it in the
12813         * destination.
12814         */
12815        int doPostCopy(int uid) {
12816            return PackageManager.INSTALL_SUCCEEDED;
12817        }
12818
12819        protected boolean isFwdLocked() {
12820            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
12821        }
12822
12823        protected boolean isExternalAsec() {
12824            return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
12825        }
12826
12827        protected boolean isEphemeral() {
12828            return (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0;
12829        }
12830
12831        UserHandle getUser() {
12832            return user;
12833        }
12834    }
12835
12836    private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) {
12837        if (!allCodePaths.isEmpty()) {
12838            if (instructionSets == null) {
12839                throw new IllegalStateException("instructionSet == null");
12840            }
12841            String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
12842            for (String codePath : allCodePaths) {
12843                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
12844                    try {
12845                        mInstaller.rmdex(codePath, dexCodeInstructionSet);
12846                    } catch (InstallerException ignored) {
12847                    }
12848                }
12849            }
12850        }
12851    }
12852
12853    /**
12854     * Logic to handle installation of non-ASEC applications, including copying
12855     * and renaming logic.
12856     */
12857    class FileInstallArgs extends InstallArgs {
12858        private File codeFile;
12859        private File resourceFile;
12860
12861        // Example topology:
12862        // /data/app/com.example/base.apk
12863        // /data/app/com.example/split_foo.apk
12864        // /data/app/com.example/lib/arm/libfoo.so
12865        // /data/app/com.example/lib/arm64/libfoo.so
12866        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
12867
12868        /** New install */
12869        FileInstallArgs(InstallParams params) {
12870            super(params.origin, params.move, params.observer, params.installFlags,
12871                    params.installerPackageName, params.volumeUuid,
12872                    params.getUser(), null /*instructionSets*/, params.packageAbiOverride,
12873                    params.grantedRuntimePermissions,
12874                    params.traceMethod, params.traceCookie, params.certificates);
12875            if (isFwdLocked()) {
12876                throw new IllegalArgumentException("Forward locking only supported in ASEC");
12877            }
12878        }
12879
12880        /** Existing install */
12881        FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) {
12882            super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets,
12883                    null, null, null, 0, null /*certificates*/);
12884            this.codeFile = (codePath != null) ? new File(codePath) : null;
12885            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
12886        }
12887
12888        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
12889            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk");
12890            try {
12891                return doCopyApk(imcs, temp);
12892            } finally {
12893                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12894            }
12895        }
12896
12897        private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
12898            if (origin.staged) {
12899                if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy");
12900                codeFile = origin.file;
12901                resourceFile = origin.file;
12902                return PackageManager.INSTALL_SUCCEEDED;
12903            }
12904
12905            try {
12906                final boolean isEphemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0;
12907                final File tempDir =
12908                        mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral);
12909                codeFile = tempDir;
12910                resourceFile = tempDir;
12911            } catch (IOException e) {
12912                Slog.w(TAG, "Failed to create copy file: " + e);
12913                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
12914            }
12915
12916            final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
12917                @Override
12918                public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
12919                    if (!FileUtils.isValidExtFilename(name)) {
12920                        throw new IllegalArgumentException("Invalid filename: " + name);
12921                    }
12922                    try {
12923                        final File file = new File(codeFile, name);
12924                        final FileDescriptor fd = Os.open(file.getAbsolutePath(),
12925                                O_RDWR | O_CREAT, 0644);
12926                        Os.chmod(file.getAbsolutePath(), 0644);
12927                        return new ParcelFileDescriptor(fd);
12928                    } catch (ErrnoException e) {
12929                        throw new RemoteException("Failed to open: " + e.getMessage());
12930                    }
12931                }
12932            };
12933
12934            int ret = PackageManager.INSTALL_SUCCEEDED;
12935            ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
12936            if (ret != PackageManager.INSTALL_SUCCEEDED) {
12937                Slog.e(TAG, "Failed to copy package");
12938                return ret;
12939            }
12940
12941            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
12942            NativeLibraryHelper.Handle handle = null;
12943            try {
12944                handle = NativeLibraryHelper.Handle.create(codeFile);
12945                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
12946                        abiOverride);
12947            } catch (IOException e) {
12948                Slog.e(TAG, "Copying native libraries failed", e);
12949                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
12950            } finally {
12951                IoUtils.closeQuietly(handle);
12952            }
12953
12954            return ret;
12955        }
12956
12957        int doPreInstall(int status) {
12958            if (status != PackageManager.INSTALL_SUCCEEDED) {
12959                cleanUp();
12960            }
12961            return status;
12962        }
12963
12964        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
12965            if (status != PackageManager.INSTALL_SUCCEEDED) {
12966                cleanUp();
12967                return false;
12968            }
12969
12970            final File targetDir = codeFile.getParentFile();
12971            final File beforeCodeFile = codeFile;
12972            final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName);
12973
12974            if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
12975            try {
12976                Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
12977            } catch (ErrnoException e) {
12978                Slog.w(TAG, "Failed to rename", e);
12979                return false;
12980            }
12981
12982            if (!SELinux.restoreconRecursive(afterCodeFile)) {
12983                Slog.w(TAG, "Failed to restorecon");
12984                return false;
12985            }
12986
12987            // Reflect the rename internally
12988            codeFile = afterCodeFile;
12989            resourceFile = afterCodeFile;
12990
12991            // Reflect the rename in scanned details
12992            pkg.setCodePath(afterCodeFile.getAbsolutePath());
12993            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
12994                    afterCodeFile, pkg.baseCodePath));
12995            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
12996                    afterCodeFile, pkg.splitCodePaths));
12997
12998            // Reflect the rename in app info
12999            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
13000            pkg.setApplicationInfoCodePath(pkg.codePath);
13001            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
13002            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
13003            pkg.setApplicationInfoResourcePath(pkg.codePath);
13004            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
13005            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
13006
13007            return true;
13008        }
13009
13010        int doPostInstall(int status, int uid) {
13011            if (status != PackageManager.INSTALL_SUCCEEDED) {
13012                cleanUp();
13013            }
13014            return status;
13015        }
13016
13017        @Override
13018        String getCodePath() {
13019            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
13020        }
13021
13022        @Override
13023        String getResourcePath() {
13024            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
13025        }
13026
13027        private boolean cleanUp() {
13028            if (codeFile == null || !codeFile.exists()) {
13029                return false;
13030            }
13031
13032            removeCodePathLI(codeFile);
13033
13034            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
13035                resourceFile.delete();
13036            }
13037
13038            return true;
13039        }
13040
13041        void cleanUpResourcesLI() {
13042            // Try enumerating all code paths before deleting
13043            List<String> allCodePaths = Collections.EMPTY_LIST;
13044            if (codeFile != null && codeFile.exists()) {
13045                try {
13046                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
13047                    allCodePaths = pkg.getAllCodePaths();
13048                } catch (PackageParserException e) {
13049                    // Ignored; we tried our best
13050                }
13051            }
13052
13053            cleanUp();
13054            removeDexFiles(allCodePaths, instructionSets);
13055        }
13056
13057        boolean doPostDeleteLI(boolean delete) {
13058            // XXX err, shouldn't we respect the delete flag?
13059            cleanUpResourcesLI();
13060            return true;
13061        }
13062    }
13063
13064    private boolean isAsecExternal(String cid) {
13065        final String asecPath = PackageHelper.getSdFilesystem(cid);
13066        return !asecPath.startsWith(mAsecInternalPath);
13067    }
13068
13069    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
13070            PackageManagerException {
13071        if (copyRet < 0) {
13072            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
13073                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
13074                throw new PackageManagerException(copyRet, message);
13075            }
13076        }
13077    }
13078
13079    /**
13080     * Extract the MountService "container ID" from the full code path of an
13081     * .apk.
13082     */
13083    static String cidFromCodePath(String fullCodePath) {
13084        int eidx = fullCodePath.lastIndexOf("/");
13085        String subStr1 = fullCodePath.substring(0, eidx);
13086        int sidx = subStr1.lastIndexOf("/");
13087        return subStr1.substring(sidx+1, eidx);
13088    }
13089
13090    /**
13091     * Logic to handle installation of ASEC applications, including copying and
13092     * renaming logic.
13093     */
13094    class AsecInstallArgs extends InstallArgs {
13095        static final String RES_FILE_NAME = "pkg.apk";
13096        static final String PUBLIC_RES_FILE_NAME = "res.zip";
13097
13098        String cid;
13099        String packagePath;
13100        String resourcePath;
13101
13102        /** New install */
13103        AsecInstallArgs(InstallParams params) {
13104            super(params.origin, params.move, params.observer, params.installFlags,
13105                    params.installerPackageName, params.volumeUuid,
13106                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
13107                    params.grantedRuntimePermissions,
13108                    params.traceMethod, params.traceCookie, params.certificates);
13109        }
13110
13111        /** Existing install */
13112        AsecInstallArgs(String fullCodePath, String[] instructionSets,
13113                        boolean isExternal, boolean isForwardLocked) {
13114            super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0)
13115              | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
13116                    instructionSets, null, null, null, 0, null /*certificates*/);
13117            // Hackily pretend we're still looking at a full code path
13118            if (!fullCodePath.endsWith(RES_FILE_NAME)) {
13119                fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath();
13120            }
13121
13122            // Extract cid from fullCodePath
13123            int eidx = fullCodePath.lastIndexOf("/");
13124            String subStr1 = fullCodePath.substring(0, eidx);
13125            int sidx = subStr1.lastIndexOf("/");
13126            cid = subStr1.substring(sidx+1, eidx);
13127            setMountPath(subStr1);
13128        }
13129
13130        AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) {
13131            super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0)
13132              | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
13133                    instructionSets, null, null, null, 0, null /*certificates*/);
13134            this.cid = cid;
13135            setMountPath(PackageHelper.getSdDir(cid));
13136        }
13137
13138        void createCopyFile() {
13139            cid = mInstallerService.allocateExternalStageCidLegacy();
13140        }
13141
13142        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
13143            if (origin.staged && origin.cid != null) {
13144                if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy");
13145                cid = origin.cid;
13146                setMountPath(PackageHelper.getSdDir(cid));
13147                return PackageManager.INSTALL_SUCCEEDED;
13148            }
13149
13150            if (temp) {
13151                createCopyFile();
13152            } else {
13153                /*
13154                 * Pre-emptively destroy the container since it's destroyed if
13155                 * copying fails due to it existing anyway.
13156                 */
13157                PackageHelper.destroySdDir(cid);
13158            }
13159
13160            final String newMountPath = imcs.copyPackageToContainer(
13161                    origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(),
13162                    isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */));
13163
13164            if (newMountPath != null) {
13165                setMountPath(newMountPath);
13166                return PackageManager.INSTALL_SUCCEEDED;
13167            } else {
13168                return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
13169            }
13170        }
13171
13172        @Override
13173        String getCodePath() {
13174            return packagePath;
13175        }
13176
13177        @Override
13178        String getResourcePath() {
13179            return resourcePath;
13180        }
13181
13182        int doPreInstall(int status) {
13183            if (status != PackageManager.INSTALL_SUCCEEDED) {
13184                // Destroy container
13185                PackageHelper.destroySdDir(cid);
13186            } else {
13187                boolean mounted = PackageHelper.isContainerMounted(cid);
13188                if (!mounted) {
13189                    String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(),
13190                            Process.SYSTEM_UID);
13191                    if (newMountPath != null) {
13192                        setMountPath(newMountPath);
13193                    } else {
13194                        return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
13195                    }
13196                }
13197            }
13198            return status;
13199        }
13200
13201        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
13202            String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME);
13203            String newMountPath = null;
13204            if (PackageHelper.isContainerMounted(cid)) {
13205                // Unmount the container
13206                if (!PackageHelper.unMountSdDir(cid)) {
13207                    Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
13208                    return false;
13209                }
13210            }
13211            if (!PackageHelper.renameSdDir(cid, newCacheId)) {
13212                Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
13213                        " which might be stale. Will try to clean up.");
13214                // Clean up the stale container and proceed to recreate.
13215                if (!PackageHelper.destroySdDir(newCacheId)) {
13216                    Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
13217                    return false;
13218                }
13219                // Successfully cleaned up stale container. Try to rename again.
13220                if (!PackageHelper.renameSdDir(cid, newCacheId)) {
13221                    Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
13222                            + " inspite of cleaning it up.");
13223                    return false;
13224                }
13225            }
13226            if (!PackageHelper.isContainerMounted(newCacheId)) {
13227                Slog.w(TAG, "Mounting container " + newCacheId);
13228                newMountPath = PackageHelper.mountSdDir(newCacheId,
13229                        getEncryptKey(), Process.SYSTEM_UID);
13230            } else {
13231                newMountPath = PackageHelper.getSdDir(newCacheId);
13232            }
13233            if (newMountPath == null) {
13234                Slog.w(TAG, "Failed to get cache path for  " + newCacheId);
13235                return false;
13236            }
13237            Log.i(TAG, "Succesfully renamed " + cid +
13238                    " to " + newCacheId +
13239                    " at new path: " + newMountPath);
13240            cid = newCacheId;
13241
13242            final File beforeCodeFile = new File(packagePath);
13243            setMountPath(newMountPath);
13244            final File afterCodeFile = new File(packagePath);
13245
13246            // Reflect the rename in scanned details
13247            pkg.setCodePath(afterCodeFile.getAbsolutePath());
13248            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
13249                    afterCodeFile, pkg.baseCodePath));
13250            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
13251                    afterCodeFile, pkg.splitCodePaths));
13252
13253            // Reflect the rename in app info
13254            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
13255            pkg.setApplicationInfoCodePath(pkg.codePath);
13256            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
13257            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
13258            pkg.setApplicationInfoResourcePath(pkg.codePath);
13259            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
13260            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
13261
13262            return true;
13263        }
13264
13265        private void setMountPath(String mountPath) {
13266            final File mountFile = new File(mountPath);
13267
13268            final File monolithicFile = new File(mountFile, RES_FILE_NAME);
13269            if (monolithicFile.exists()) {
13270                packagePath = monolithicFile.getAbsolutePath();
13271                if (isFwdLocked()) {
13272                    resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath();
13273                } else {
13274                    resourcePath = packagePath;
13275                }
13276            } else {
13277                packagePath = mountFile.getAbsolutePath();
13278                resourcePath = packagePath;
13279            }
13280        }
13281
13282        int doPostInstall(int status, int uid) {
13283            if (status != PackageManager.INSTALL_SUCCEEDED) {
13284                cleanUp();
13285            } else {
13286                final int groupOwner;
13287                final String protectedFile;
13288                if (isFwdLocked()) {
13289                    groupOwner = UserHandle.getSharedAppGid(uid);
13290                    protectedFile = RES_FILE_NAME;
13291                } else {
13292                    groupOwner = -1;
13293                    protectedFile = null;
13294                }
13295
13296                if (uid < Process.FIRST_APPLICATION_UID
13297                        || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) {
13298                    Slog.e(TAG, "Failed to finalize " + cid);
13299                    PackageHelper.destroySdDir(cid);
13300                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
13301                }
13302
13303                boolean mounted = PackageHelper.isContainerMounted(cid);
13304                if (!mounted) {
13305                    PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid());
13306                }
13307            }
13308            return status;
13309        }
13310
13311        private void cleanUp() {
13312            if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp");
13313
13314            // Destroy secure container
13315            PackageHelper.destroySdDir(cid);
13316        }
13317
13318        private List<String> getAllCodePaths() {
13319            final File codeFile = new File(getCodePath());
13320            if (codeFile != null && codeFile.exists()) {
13321                try {
13322                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
13323                    return pkg.getAllCodePaths();
13324                } catch (PackageParserException e) {
13325                    // Ignored; we tried our best
13326                }
13327            }
13328            return Collections.EMPTY_LIST;
13329        }
13330
13331        void cleanUpResourcesLI() {
13332            // Enumerate all code paths before deleting
13333            cleanUpResourcesLI(getAllCodePaths());
13334        }
13335
13336        private void cleanUpResourcesLI(List<String> allCodePaths) {
13337            cleanUp();
13338            removeDexFiles(allCodePaths, instructionSets);
13339        }
13340
13341        String getPackageName() {
13342            return getAsecPackageName(cid);
13343        }
13344
13345        boolean doPostDeleteLI(boolean delete) {
13346            if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete);
13347            final List<String> allCodePaths = getAllCodePaths();
13348            boolean mounted = PackageHelper.isContainerMounted(cid);
13349            if (mounted) {
13350                // Unmount first
13351                if (PackageHelper.unMountSdDir(cid)) {
13352                    mounted = false;
13353                }
13354            }
13355            if (!mounted && delete) {
13356                cleanUpResourcesLI(allCodePaths);
13357            }
13358            return !mounted;
13359        }
13360
13361        @Override
13362        int doPreCopy() {
13363            if (isFwdLocked()) {
13364                if (!PackageHelper.fixSdPermissions(cid, getPackageUid(DEFAULT_CONTAINER_PACKAGE,
13365                        MATCH_SYSTEM_ONLY, UserHandle.USER_SYSTEM), RES_FILE_NAME)) {
13366                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
13367                }
13368            }
13369
13370            return PackageManager.INSTALL_SUCCEEDED;
13371        }
13372
13373        @Override
13374        int doPostCopy(int uid) {
13375            if (isFwdLocked()) {
13376                if (uid < Process.FIRST_APPLICATION_UID
13377                        || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid),
13378                                RES_FILE_NAME)) {
13379                    Slog.e(TAG, "Failed to finalize " + cid);
13380                    PackageHelper.destroySdDir(cid);
13381                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
13382                }
13383            }
13384
13385            return PackageManager.INSTALL_SUCCEEDED;
13386        }
13387    }
13388
13389    /**
13390     * Logic to handle movement of existing installed applications.
13391     */
13392    class MoveInstallArgs extends InstallArgs {
13393        private File codeFile;
13394        private File resourceFile;
13395
13396        /** New install */
13397        MoveInstallArgs(InstallParams params) {
13398            super(params.origin, params.move, params.observer, params.installFlags,
13399                    params.installerPackageName, params.volumeUuid,
13400                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
13401                    params.grantedRuntimePermissions,
13402                    params.traceMethod, params.traceCookie, params.certificates);
13403        }
13404
13405        int copyApk(IMediaContainerService imcs, boolean temp) {
13406            if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from "
13407                    + move.fromUuid + " to " + move.toUuid);
13408            synchronized (mInstaller) {
13409                try {
13410                    mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName,
13411                            move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion);
13412                } catch (InstallerException e) {
13413                    Slog.w(TAG, "Failed to move app", e);
13414                    return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
13415                }
13416            }
13417
13418            codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName);
13419            resourceFile = codeFile;
13420            if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile);
13421
13422            return PackageManager.INSTALL_SUCCEEDED;
13423        }
13424
13425        int doPreInstall(int status) {
13426            if (status != PackageManager.INSTALL_SUCCEEDED) {
13427                cleanUp(move.toUuid);
13428            }
13429            return status;
13430        }
13431
13432        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
13433            if (status != PackageManager.INSTALL_SUCCEEDED) {
13434                cleanUp(move.toUuid);
13435                return false;
13436            }
13437
13438            // Reflect the move in app info
13439            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
13440            pkg.setApplicationInfoCodePath(pkg.codePath);
13441            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
13442            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
13443            pkg.setApplicationInfoResourcePath(pkg.codePath);
13444            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
13445            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
13446
13447            return true;
13448        }
13449
13450        int doPostInstall(int status, int uid) {
13451            if (status == PackageManager.INSTALL_SUCCEEDED) {
13452                cleanUp(move.fromUuid);
13453            } else {
13454                cleanUp(move.toUuid);
13455            }
13456            return status;
13457        }
13458
13459        @Override
13460        String getCodePath() {
13461            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
13462        }
13463
13464        @Override
13465        String getResourcePath() {
13466            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
13467        }
13468
13469        private boolean cleanUp(String volumeUuid) {
13470            final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid),
13471                    move.dataAppName);
13472            Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid);
13473            final int[] userIds = sUserManager.getUserIds();
13474            synchronized (mInstallLock) {
13475                // Clean up both app data and code
13476                // All package moves are frozen until finished
13477                for (int userId : userIds) {
13478                    try {
13479                        mInstaller.destroyAppData(volumeUuid, move.packageName, userId,
13480                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 0);
13481                    } catch (InstallerException e) {
13482                        Slog.w(TAG, String.valueOf(e));
13483                    }
13484                }
13485                removeCodePathLI(codeFile);
13486            }
13487            return true;
13488        }
13489
13490        void cleanUpResourcesLI() {
13491            throw new UnsupportedOperationException();
13492        }
13493
13494        boolean doPostDeleteLI(boolean delete) {
13495            throw new UnsupportedOperationException();
13496        }
13497    }
13498
13499    static String getAsecPackageName(String packageCid) {
13500        int idx = packageCid.lastIndexOf("-");
13501        if (idx == -1) {
13502            return packageCid;
13503        }
13504        return packageCid.substring(0, idx);
13505    }
13506
13507    // Utility method used to create code paths based on package name and available index.
13508    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
13509        String idxStr = "";
13510        int idx = 1;
13511        // Fall back to default value of idx=1 if prefix is not
13512        // part of oldCodePath
13513        if (oldCodePath != null) {
13514            String subStr = oldCodePath;
13515            // Drop the suffix right away
13516            if (suffix != null && subStr.endsWith(suffix)) {
13517                subStr = subStr.substring(0, subStr.length() - suffix.length());
13518            }
13519            // If oldCodePath already contains prefix find out the
13520            // ending index to either increment or decrement.
13521            int sidx = subStr.lastIndexOf(prefix);
13522            if (sidx != -1) {
13523                subStr = subStr.substring(sidx + prefix.length());
13524                if (subStr != null) {
13525                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
13526                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
13527                    }
13528                    try {
13529                        idx = Integer.parseInt(subStr);
13530                        if (idx <= 1) {
13531                            idx++;
13532                        } else {
13533                            idx--;
13534                        }
13535                    } catch(NumberFormatException e) {
13536                    }
13537                }
13538            }
13539        }
13540        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
13541        return prefix + idxStr;
13542    }
13543
13544    private File getNextCodePath(File targetDir, String packageName) {
13545        int suffix = 1;
13546        File result;
13547        do {
13548            result = new File(targetDir, packageName + "-" + suffix);
13549            suffix++;
13550        } while (result.exists());
13551        return result;
13552    }
13553
13554    // Utility method that returns the relative package path with respect
13555    // to the installation directory. Like say for /data/data/com.test-1.apk
13556    // string com.test-1 is returned.
13557    static String deriveCodePathName(String codePath) {
13558        if (codePath == null) {
13559            return null;
13560        }
13561        final File codeFile = new File(codePath);
13562        final String name = codeFile.getName();
13563        if (codeFile.isDirectory()) {
13564            return name;
13565        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
13566            final int lastDot = name.lastIndexOf('.');
13567            return name.substring(0, lastDot);
13568        } else {
13569            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
13570            return null;
13571        }
13572    }
13573
13574    static class PackageInstalledInfo {
13575        String name;
13576        int uid;
13577        // The set of users that originally had this package installed.
13578        int[] origUsers;
13579        // The set of users that now have this package installed.
13580        int[] newUsers;
13581        PackageParser.Package pkg;
13582        int returnCode;
13583        String returnMsg;
13584        PackageRemovedInfo removedInfo;
13585        ArrayMap<String, PackageInstalledInfo> addedChildPackages;
13586
13587        public void setError(int code, String msg) {
13588            setReturnCode(code);
13589            setReturnMessage(msg);
13590            Slog.w(TAG, msg);
13591        }
13592
13593        public void setError(String msg, PackageParserException e) {
13594            setReturnCode(e.error);
13595            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
13596            Slog.w(TAG, msg, e);
13597        }
13598
13599        public void setError(String msg, PackageManagerException e) {
13600            returnCode = e.error;
13601            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
13602            Slog.w(TAG, msg, e);
13603        }
13604
13605        public void setReturnCode(int returnCode) {
13606            this.returnCode = returnCode;
13607            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
13608            for (int i = 0; i < childCount; i++) {
13609                addedChildPackages.valueAt(i).returnCode = returnCode;
13610            }
13611        }
13612
13613        private void setReturnMessage(String returnMsg) {
13614            this.returnMsg = returnMsg;
13615            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
13616            for (int i = 0; i < childCount; i++) {
13617                addedChildPackages.valueAt(i).returnMsg = returnMsg;
13618            }
13619        }
13620
13621        // In some error cases we want to convey more info back to the observer
13622        String origPackage;
13623        String origPermission;
13624    }
13625
13626    /*
13627     * Install a non-existing package.
13628     */
13629    private void installNewPackageLIF(PackageParser.Package pkg, final int policyFlags,
13630            int scanFlags, UserHandle user, String installerPackageName, String volumeUuid,
13631            PackageInstalledInfo res) {
13632        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage");
13633
13634        // Remember this for later, in case we need to rollback this install
13635        String pkgName = pkg.packageName;
13636
13637        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
13638
13639        synchronized(mPackages) {
13640            if (mSettings.mRenamedPackages.containsKey(pkgName)) {
13641                // A package with the same name is already installed, though
13642                // it has been renamed to an older name.  The package we
13643                // are trying to install should be installed as an update to
13644                // the existing one, but that has not been requested, so bail.
13645                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
13646                        + " without first uninstalling package running as "
13647                        + mSettings.mRenamedPackages.get(pkgName));
13648                return;
13649            }
13650            if (mPackages.containsKey(pkgName)) {
13651                // Don't allow installation over an existing package with the same name.
13652                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
13653                        + " without first uninstalling.");
13654                return;
13655            }
13656        }
13657
13658        try {
13659            PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags,
13660                    System.currentTimeMillis(), user);
13661
13662            updateSettingsLI(newPackage, installerPackageName, null, res, user);
13663
13664            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
13665                prepareAppDataAfterInstallLIF(newPackage);
13666
13667            } else {
13668                // Remove package from internal structures, but keep around any
13669                // data that might have already existed
13670                deletePackageLIF(pkgName, UserHandle.ALL, false, null,
13671                        PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null);
13672            }
13673        } catch (PackageManagerException e) {
13674            res.setError("Package couldn't be installed in " + pkg.codePath, e);
13675        }
13676
13677        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
13678    }
13679
13680    private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) {
13681        // Can't rotate keys during boot or if sharedUser.
13682        if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null
13683                || !oldPs.keySetData.isUsingUpgradeKeySets()) {
13684            return false;
13685        }
13686        // app is using upgradeKeySets; make sure all are valid
13687        KeySetManagerService ksms = mSettings.mKeySetManagerService;
13688        long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets();
13689        for (int i = 0; i < upgradeKeySets.length; i++) {
13690            if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) {
13691                Slog.wtf(TAG, "Package "
13692                         + (oldPs.name != null ? oldPs.name : "<null>")
13693                         + " contains upgrade-key-set reference to unknown key-set: "
13694                         + upgradeKeySets[i]
13695                         + " reverting to signatures check.");
13696                return false;
13697            }
13698        }
13699        return true;
13700    }
13701
13702    private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) {
13703        // Upgrade keysets are being used.  Determine if new package has a superset of the
13704        // required keys.
13705        long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets();
13706        KeySetManagerService ksms = mSettings.mKeySetManagerService;
13707        for (int i = 0; i < upgradeKeySets.length; i++) {
13708            Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]);
13709            if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) {
13710                return true;
13711            }
13712        }
13713        return false;
13714    }
13715
13716    private void replacePackageLIF(PackageParser.Package pkg, final int policyFlags, int scanFlags,
13717            UserHandle user, String installerPackageName, PackageInstalledInfo res) {
13718        final boolean isEphemeral = (policyFlags & PackageParser.PARSE_IS_EPHEMERAL) != 0;
13719
13720        final PackageParser.Package oldPackage;
13721        final String pkgName = pkg.packageName;
13722        final int[] allUsers;
13723
13724        // First find the old package info and check signatures
13725        synchronized(mPackages) {
13726            oldPackage = mPackages.get(pkgName);
13727            final boolean oldIsEphemeral = oldPackage.applicationInfo.isEphemeralApp();
13728            if (isEphemeral && !oldIsEphemeral) {
13729                // can't downgrade from full to ephemeral
13730                Slog.w(TAG, "Can't replace app with ephemeral: " + pkgName);
13731                res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID);
13732                return;
13733            }
13734            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
13735            final PackageSetting ps = mSettings.mPackages.get(pkgName);
13736            if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
13737                if (!checkUpgradeKeySetLP(ps, pkg)) {
13738                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
13739                            "New package not signed by keys specified by upgrade-keysets: "
13740                                    + pkgName);
13741                    return;
13742                }
13743            } else {
13744                // default to original signature matching
13745                if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
13746                        != PackageManager.SIGNATURE_MATCH) {
13747                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
13748                            "New package has a different signature: " + pkgName);
13749                    return;
13750                }
13751            }
13752
13753            // Check for shared user id changes
13754            String invalidPackageName =
13755                    getParentOrChildPackageChangedSharedUser(oldPackage, pkg);
13756            if (invalidPackageName != null) {
13757                res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
13758                        "Package " + invalidPackageName + " tried to change user "
13759                                + oldPackage.mSharedUserId);
13760                return;
13761            }
13762
13763            // In case of rollback, remember per-user/profile install state
13764            allUsers = sUserManager.getUserIds();
13765        }
13766
13767        // Update what is removed
13768        res.removedInfo = new PackageRemovedInfo();
13769        res.removedInfo.uid = oldPackage.applicationInfo.uid;
13770        res.removedInfo.removedPackage = oldPackage.packageName;
13771        res.removedInfo.isUpdate = true;
13772        final int childCount = (oldPackage.childPackages != null)
13773                ? oldPackage.childPackages.size() : 0;
13774        for (int i = 0; i < childCount; i++) {
13775            boolean childPackageUpdated = false;
13776            PackageParser.Package childPkg = oldPackage.childPackages.get(i);
13777            if (res.addedChildPackages != null) {
13778                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
13779                if (childRes != null) {
13780                    childRes.removedInfo.uid = childPkg.applicationInfo.uid;
13781                    childRes.removedInfo.removedPackage = childPkg.packageName;
13782                    childRes.removedInfo.isUpdate = true;
13783                    childPackageUpdated = true;
13784                }
13785            }
13786            if (!childPackageUpdated) {
13787                PackageRemovedInfo childRemovedRes = new PackageRemovedInfo();
13788                childRemovedRes.removedPackage = childPkg.packageName;
13789                childRemovedRes.isUpdate = false;
13790                childRemovedRes.dataRemoved = true;
13791                synchronized (mPackages) {
13792                    PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName);
13793                    if (childPs != null) {
13794                        childRemovedRes.origUsers = childPs.queryInstalledUsers(allUsers, true);
13795                    }
13796                }
13797                if (res.removedInfo.removedChildPackages == null) {
13798                    res.removedInfo.removedChildPackages = new ArrayMap<>();
13799                }
13800                res.removedInfo.removedChildPackages.put(childPkg.packageName, childRemovedRes);
13801            }
13802        }
13803
13804        boolean sysPkg = (isSystemApp(oldPackage));
13805        if (sysPkg) {
13806            // Set the system/privileged flags as needed
13807            final boolean privileged =
13808                    (oldPackage.applicationInfo.privateFlags
13809                            & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
13810            final int systemPolicyFlags = policyFlags
13811                    | PackageParser.PARSE_IS_SYSTEM
13812                    | (privileged ? PackageParser.PARSE_IS_PRIVILEGED : 0);
13813
13814            replaceSystemPackageLIF(oldPackage, pkg, systemPolicyFlags, scanFlags,
13815                    user, allUsers, installerPackageName, res);
13816        } else {
13817            replaceNonSystemPackageLIF(oldPackage, pkg, policyFlags, scanFlags,
13818                    user, allUsers, installerPackageName, res);
13819        }
13820    }
13821
13822    public List<String> getPreviousCodePaths(String packageName) {
13823        final PackageSetting ps = mSettings.mPackages.get(packageName);
13824        final List<String> result = new ArrayList<String>();
13825        if (ps != null && ps.oldCodePaths != null) {
13826            result.addAll(ps.oldCodePaths);
13827        }
13828        return result;
13829    }
13830
13831    private void replaceNonSystemPackageLIF(PackageParser.Package deletedPackage,
13832            PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user,
13833            int[] allUsers, String installerPackageName, PackageInstalledInfo res) {
13834        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
13835                + deletedPackage);
13836
13837        String pkgName = deletedPackage.packageName;
13838        boolean deletedPkg = true;
13839        boolean addedPkg = false;
13840        boolean updatedSettings = false;
13841        final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0;
13842        final int deleteFlags = PackageManager.DELETE_KEEP_DATA
13843                | (killApp ? 0 : PackageManager.DELETE_DONT_KILL_APP);
13844
13845        final long origUpdateTime = (pkg.mExtras != null)
13846                ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0;
13847
13848        // First delete the existing package while retaining the data directory
13849        if (!deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
13850                res.removedInfo, true, pkg)) {
13851            // If the existing package wasn't successfully deleted
13852            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
13853            deletedPkg = false;
13854        } else {
13855            // Successfully deleted the old package; proceed with replace.
13856
13857            // If deleted package lived in a container, give users a chance to
13858            // relinquish resources before killing.
13859            if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) {
13860                if (DEBUG_INSTALL) {
13861                    Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
13862                }
13863                final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
13864                final ArrayList<String> pkgList = new ArrayList<String>(1);
13865                pkgList.add(deletedPackage.applicationInfo.packageName);
13866                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
13867            }
13868
13869            clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
13870                    | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
13871            clearAppProfilesLIF(pkg);
13872
13873            try {
13874                final PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags,
13875                        scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
13876                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user);
13877
13878                // Update the in-memory copy of the previous code paths.
13879                PackageSetting ps = mSettings.mPackages.get(pkgName);
13880                if (!killApp) {
13881                    if (ps.oldCodePaths == null) {
13882                        ps.oldCodePaths = new ArraySet<>();
13883                    }
13884                    Collections.addAll(ps.oldCodePaths, deletedPackage.baseCodePath);
13885                    if (deletedPackage.splitCodePaths != null) {
13886                        Collections.addAll(ps.oldCodePaths, deletedPackage.splitCodePaths);
13887                    }
13888                } else {
13889                    ps.oldCodePaths = null;
13890                }
13891                if (ps.childPackageNames != null) {
13892                    for (int i = ps.childPackageNames.size() - 1; i >= 0; --i) {
13893                        final String childPkgName = ps.childPackageNames.get(i);
13894                        final PackageSetting childPs = mSettings.mPackages.get(childPkgName);
13895                        childPs.oldCodePaths = ps.oldCodePaths;
13896                    }
13897                }
13898                prepareAppDataAfterInstallLIF(newPackage);
13899                addedPkg = true;
13900            } catch (PackageManagerException e) {
13901                res.setError("Package couldn't be installed in " + pkg.codePath, e);
13902            }
13903        }
13904
13905        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
13906            if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
13907
13908            // Revert all internal state mutations and added folders for the failed install
13909            if (addedPkg) {
13910                deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
13911                        res.removedInfo, true, null);
13912            }
13913
13914            // Restore the old package
13915            if (deletedPkg) {
13916                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
13917                File restoreFile = new File(deletedPackage.codePath);
13918                // Parse old package
13919                boolean oldExternal = isExternal(deletedPackage);
13920                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
13921                        (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) |
13922                        (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
13923                int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
13924                try {
13925                    scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime,
13926                            null);
13927                } catch (PackageManagerException e) {
13928                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
13929                            + e.getMessage());
13930                    return;
13931                }
13932
13933                synchronized (mPackages) {
13934                    // Ensure the installer package name up to date
13935                    setInstallerPackageNameLPw(deletedPackage, installerPackageName);
13936
13937                    // Update permissions for restored package
13938                    updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
13939
13940                    mSettings.writeLPr();
13941                }
13942
13943                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
13944            }
13945        } else {
13946            synchronized (mPackages) {
13947                PackageSetting ps = mSettings.peekPackageLPr(pkg.packageName);
13948                if (ps != null) {
13949                    res.removedInfo.removedForAllUsers = mPackages.get(ps.name) == null;
13950                    if (res.removedInfo.removedChildPackages != null) {
13951                        final int childCount = res.removedInfo.removedChildPackages.size();
13952                        // Iterate in reverse as we may modify the collection
13953                        for (int i = childCount - 1; i >= 0; i--) {
13954                            String childPackageName = res.removedInfo.removedChildPackages.keyAt(i);
13955                            if (res.addedChildPackages.containsKey(childPackageName)) {
13956                                res.removedInfo.removedChildPackages.removeAt(i);
13957                            } else {
13958                                PackageRemovedInfo childInfo = res.removedInfo
13959                                        .removedChildPackages.valueAt(i);
13960                                childInfo.removedForAllUsers = mPackages.get(
13961                                        childInfo.removedPackage) == null;
13962                            }
13963                        }
13964                    }
13965                }
13966            }
13967        }
13968    }
13969
13970    private void replaceSystemPackageLIF(PackageParser.Package deletedPackage,
13971            PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user,
13972            int[] allUsers, String installerPackageName, PackageInstalledInfo res) {
13973        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
13974                + ", old=" + deletedPackage);
13975
13976        final boolean disabledSystem;
13977
13978        // Remove existing system package
13979        removePackageLI(deletedPackage, true);
13980
13981        disabledSystem = disableSystemPackageLPw(deletedPackage, pkg);
13982        if (!disabledSystem) {
13983            // We didn't need to disable the .apk as a current system package,
13984            // which means we are replacing another update that is already
13985            // installed.  We need to make sure to delete the older one's .apk.
13986            res.removedInfo.args = createInstallArgsForExisting(0,
13987                    deletedPackage.applicationInfo.getCodePath(),
13988                    deletedPackage.applicationInfo.getResourcePath(),
13989                    getAppDexInstructionSets(deletedPackage.applicationInfo));
13990        } else {
13991            res.removedInfo.args = null;
13992        }
13993
13994        // Successfully disabled the old package. Now proceed with re-installation
13995        clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
13996                | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
13997        clearAppProfilesLIF(pkg);
13998
13999        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
14000        pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP,
14001                ApplicationInfo.FLAG_UPDATED_SYSTEM_APP);
14002
14003        PackageParser.Package newPackage = null;
14004        try {
14005            // Add the package to the internal data structures
14006            newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags, 0, user);
14007
14008            // Set the update and install times
14009            PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras;
14010            setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime,
14011                    System.currentTimeMillis());
14012
14013            // Update the package dynamic state if succeeded
14014            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
14015                // Now that the install succeeded make sure we remove data
14016                // directories for any child package the update removed.
14017                final int deletedChildCount = (deletedPackage.childPackages != null)
14018                        ? deletedPackage.childPackages.size() : 0;
14019                final int newChildCount = (newPackage.childPackages != null)
14020                        ? newPackage.childPackages.size() : 0;
14021                for (int i = 0; i < deletedChildCount; i++) {
14022                    PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i);
14023                    boolean childPackageDeleted = true;
14024                    for (int j = 0; j < newChildCount; j++) {
14025                        PackageParser.Package newChildPkg = newPackage.childPackages.get(j);
14026                        if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) {
14027                            childPackageDeleted = false;
14028                            break;
14029                        }
14030                    }
14031                    if (childPackageDeleted) {
14032                        PackageSetting ps = mSettings.getDisabledSystemPkgLPr(
14033                                deletedChildPkg.packageName);
14034                        if (ps != null && res.removedInfo.removedChildPackages != null) {
14035                            PackageRemovedInfo removedChildRes = res.removedInfo
14036                                    .removedChildPackages.get(deletedChildPkg.packageName);
14037                            removePackageDataLIF(ps, allUsers, removedChildRes, 0, false);
14038                            removedChildRes.removedForAllUsers = mPackages.get(ps.name) == null;
14039                        }
14040                    }
14041                }
14042
14043                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user);
14044                prepareAppDataAfterInstallLIF(newPackage);
14045            }
14046        } catch (PackageManagerException e) {
14047            res.setReturnCode(INSTALL_FAILED_INTERNAL_ERROR);
14048            res.setError("Package couldn't be installed in " + pkg.codePath, e);
14049        }
14050
14051        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
14052            // Re installation failed. Restore old information
14053            // Remove new pkg information
14054            if (newPackage != null) {
14055                removeInstalledPackageLI(newPackage, true);
14056            }
14057            // Add back the old system package
14058            try {
14059                scanPackageTracedLI(deletedPackage, policyFlags, SCAN_UPDATE_SIGNATURE, 0, user);
14060            } catch (PackageManagerException e) {
14061                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
14062            }
14063
14064            synchronized (mPackages) {
14065                if (disabledSystem) {
14066                    enableSystemPackageLPw(deletedPackage);
14067                }
14068
14069                // Ensure the installer package name up to date
14070                setInstallerPackageNameLPw(deletedPackage, installerPackageName);
14071
14072                // Update permissions for restored package
14073                updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
14074
14075                mSettings.writeLPr();
14076            }
14077
14078            Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName
14079                    + " after failed upgrade");
14080        }
14081    }
14082
14083    /**
14084     * Checks whether the parent or any of the child packages have a change shared
14085     * user. For a package to be a valid update the shred users of the parent and
14086     * the children should match. We may later support changing child shared users.
14087     * @param oldPkg The updated package.
14088     * @param newPkg The update package.
14089     * @return The shared user that change between the versions.
14090     */
14091    private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg,
14092            PackageParser.Package newPkg) {
14093        // Check parent shared user
14094        if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) {
14095            return newPkg.packageName;
14096        }
14097        // Check child shared users
14098        final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
14099        final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0;
14100        for (int i = 0; i < newChildCount; i++) {
14101            PackageParser.Package newChildPkg = newPkg.childPackages.get(i);
14102            // If this child was present, did it have the same shared user?
14103            for (int j = 0; j < oldChildCount; j++) {
14104                PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j);
14105                if (newChildPkg.packageName.equals(oldChildPkg.packageName)
14106                        && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) {
14107                    return newChildPkg.packageName;
14108                }
14109            }
14110        }
14111        return null;
14112    }
14113
14114    private void removeNativeBinariesLI(PackageSetting ps) {
14115        // Remove the lib path for the parent package
14116        if (ps != null) {
14117            NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString);
14118            // Remove the lib path for the child packages
14119            final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
14120            for (int i = 0; i < childCount; i++) {
14121                PackageSetting childPs = null;
14122                synchronized (mPackages) {
14123                    childPs = mSettings.peekPackageLPr(ps.childPackageNames.get(i));
14124                }
14125                if (childPs != null) {
14126                    NativeLibraryHelper.removeNativeBinariesLI(childPs
14127                            .legacyNativeLibraryPathString);
14128                }
14129            }
14130        }
14131    }
14132
14133    private void enableSystemPackageLPw(PackageParser.Package pkg) {
14134        // Enable the parent package
14135        mSettings.enableSystemPackageLPw(pkg.packageName);
14136        // Enable the child packages
14137        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
14138        for (int i = 0; i < childCount; i++) {
14139            PackageParser.Package childPkg = pkg.childPackages.get(i);
14140            mSettings.enableSystemPackageLPw(childPkg.packageName);
14141        }
14142    }
14143
14144    private boolean disableSystemPackageLPw(PackageParser.Package oldPkg,
14145            PackageParser.Package newPkg) {
14146        // Disable the parent package (parent always replaced)
14147        boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true);
14148        // Disable the child packages
14149        final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
14150        for (int i = 0; i < childCount; i++) {
14151            PackageParser.Package childPkg = oldPkg.childPackages.get(i);
14152            final boolean replace = newPkg.hasChildPackage(childPkg.packageName);
14153            disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace);
14154        }
14155        return disabled;
14156    }
14157
14158    private void setInstallerPackageNameLPw(PackageParser.Package pkg,
14159            String installerPackageName) {
14160        // Enable the parent package
14161        mSettings.setInstallerPackageName(pkg.packageName, installerPackageName);
14162        // Enable the child packages
14163        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
14164        for (int i = 0; i < childCount; i++) {
14165            PackageParser.Package childPkg = pkg.childPackages.get(i);
14166            mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName);
14167        }
14168    }
14169
14170    private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) {
14171        // Collect all used permissions in the UID
14172        ArraySet<String> usedPermissions = new ArraySet<>();
14173        final int packageCount = su.packages.size();
14174        for (int i = 0; i < packageCount; i++) {
14175            PackageSetting ps = su.packages.valueAt(i);
14176            if (ps.pkg == null) {
14177                continue;
14178            }
14179            final int requestedPermCount = ps.pkg.requestedPermissions.size();
14180            for (int j = 0; j < requestedPermCount; j++) {
14181                String permission = ps.pkg.requestedPermissions.get(j);
14182                BasePermission bp = mSettings.mPermissions.get(permission);
14183                if (bp != null) {
14184                    usedPermissions.add(permission);
14185                }
14186            }
14187        }
14188
14189        PermissionsState permissionsState = su.getPermissionsState();
14190        // Prune install permissions
14191        List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates();
14192        final int installPermCount = installPermStates.size();
14193        for (int i = installPermCount - 1; i >= 0;  i--) {
14194            PermissionState permissionState = installPermStates.get(i);
14195            if (!usedPermissions.contains(permissionState.getName())) {
14196                BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
14197                if (bp != null) {
14198                    permissionsState.revokeInstallPermission(bp);
14199                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
14200                            PackageManager.MASK_PERMISSION_FLAGS, 0);
14201                }
14202            }
14203        }
14204
14205        int[] runtimePermissionChangedUserIds = EmptyArray.INT;
14206
14207        // Prune runtime permissions
14208        for (int userId : allUserIds) {
14209            List<PermissionState> runtimePermStates = permissionsState
14210                    .getRuntimePermissionStates(userId);
14211            final int runtimePermCount = runtimePermStates.size();
14212            for (int i = runtimePermCount - 1; i >= 0; i--) {
14213                PermissionState permissionState = runtimePermStates.get(i);
14214                if (!usedPermissions.contains(permissionState.getName())) {
14215                    BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
14216                    if (bp != null) {
14217                        permissionsState.revokeRuntimePermission(bp, userId);
14218                        permissionsState.updatePermissionFlags(bp, userId,
14219                                PackageManager.MASK_PERMISSION_FLAGS, 0);
14220                        runtimePermissionChangedUserIds = ArrayUtils.appendInt(
14221                                runtimePermissionChangedUserIds, userId);
14222                    }
14223                }
14224            }
14225        }
14226
14227        return runtimePermissionChangedUserIds;
14228    }
14229
14230    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
14231            int[] allUsers, PackageInstalledInfo res, UserHandle user) {
14232        // Update the parent package setting
14233        updateSettingsInternalLI(newPackage, installerPackageName, allUsers, res.origUsers,
14234                res, user);
14235        // Update the child packages setting
14236        final int childCount = (newPackage.childPackages != null)
14237                ? newPackage.childPackages.size() : 0;
14238        for (int i = 0; i < childCount; i++) {
14239            PackageParser.Package childPackage = newPackage.childPackages.get(i);
14240            PackageInstalledInfo childRes = res.addedChildPackages.get(childPackage.packageName);
14241            updateSettingsInternalLI(childPackage, installerPackageName, allUsers,
14242                    childRes.origUsers, childRes, user);
14243        }
14244    }
14245
14246    private void updateSettingsInternalLI(PackageParser.Package newPackage,
14247            String installerPackageName, int[] allUsers, int[] installedForUsers,
14248            PackageInstalledInfo res, UserHandle user) {
14249        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
14250
14251        String pkgName = newPackage.packageName;
14252        synchronized (mPackages) {
14253            //write settings. the installStatus will be incomplete at this stage.
14254            //note that the new package setting would have already been
14255            //added to mPackages. It hasn't been persisted yet.
14256            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
14257            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
14258            mSettings.writeLPr();
14259            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
14260        }
14261
14262        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath);
14263        synchronized (mPackages) {
14264            updatePermissionsLPw(newPackage.packageName, newPackage,
14265                    UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
14266                            ? UPDATE_PERMISSIONS_ALL : 0));
14267            // For system-bundled packages, we assume that installing an upgraded version
14268            // of the package implies that the user actually wants to run that new code,
14269            // so we enable the package.
14270            PackageSetting ps = mSettings.mPackages.get(pkgName);
14271            final int userId = user.getIdentifier();
14272            if (ps != null) {
14273                if (isSystemApp(newPackage)) {
14274                    if (DEBUG_INSTALL) {
14275                        Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
14276                    }
14277                    // Enable system package for requested users
14278                    if (res.origUsers != null) {
14279                        for (int origUserId : res.origUsers) {
14280                            if (userId == UserHandle.USER_ALL || userId == origUserId) {
14281                                ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
14282                                        origUserId, installerPackageName);
14283                            }
14284                        }
14285                    }
14286                    // Also convey the prior install/uninstall state
14287                    if (allUsers != null && installedForUsers != null) {
14288                        for (int currentUserId : allUsers) {
14289                            final boolean installed = ArrayUtils.contains(
14290                                    installedForUsers, currentUserId);
14291                            if (DEBUG_INSTALL) {
14292                                Slog.d(TAG, "    user " + currentUserId + " => " + installed);
14293                            }
14294                            ps.setInstalled(installed, currentUserId);
14295                        }
14296                        // these install state changes will be persisted in the
14297                        // upcoming call to mSettings.writeLPr().
14298                    }
14299                }
14300                // It's implied that when a user requests installation, they want the app to be
14301                // installed and enabled.
14302                if (userId != UserHandle.USER_ALL) {
14303                    ps.setInstalled(true, userId);
14304                    ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName);
14305                }
14306            }
14307            res.name = pkgName;
14308            res.uid = newPackage.applicationInfo.uid;
14309            res.pkg = newPackage;
14310            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
14311            mSettings.setInstallerPackageName(pkgName, installerPackageName);
14312            res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
14313            //to update install status
14314            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
14315            mSettings.writeLPr();
14316            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
14317        }
14318
14319        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
14320    }
14321
14322    private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) {
14323        try {
14324            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage");
14325            installPackageLI(args, res);
14326        } finally {
14327            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
14328        }
14329    }
14330
14331    private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
14332        final int installFlags = args.installFlags;
14333        final String installerPackageName = args.installerPackageName;
14334        final String volumeUuid = args.volumeUuid;
14335        final File tmpPackageFile = new File(args.getCodePath());
14336        final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
14337        final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0)
14338                || (args.volumeUuid != null));
14339        final boolean ephemeral = ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0);
14340        boolean replace = false;
14341        int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE;
14342        if (args.move != null) {
14343            // moving a complete application; perform an initial scan on the new install location
14344            scanFlags |= SCAN_INITIAL;
14345        }
14346        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
14347            scanFlags |= SCAN_DONT_KILL_APP;
14348        }
14349
14350        // Result object to be returned
14351        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
14352
14353        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
14354
14355        // Sanity check
14356        if (ephemeral && (forwardLocked || onExternal)) {
14357            Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked
14358                    + " external=" + onExternal);
14359            res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID);
14360            return;
14361        }
14362
14363        // Retrieve PackageSettings and parse package
14364        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
14365                | PackageParser.PARSE_ENFORCE_CODE
14366                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
14367                | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0)
14368                | (ephemeral ? PackageParser.PARSE_IS_EPHEMERAL : 0);
14369        PackageParser pp = new PackageParser();
14370        pp.setSeparateProcesses(mSeparateProcesses);
14371        pp.setDisplayMetrics(mMetrics);
14372
14373        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
14374        final PackageParser.Package pkg;
14375        try {
14376            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
14377        } catch (PackageParserException e) {
14378            res.setError("Failed parse during installPackageLI", e);
14379            return;
14380        } finally {
14381            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
14382        }
14383
14384        // If we are installing a clustered package add results for the children
14385        if (pkg.childPackages != null) {
14386            synchronized (mPackages) {
14387                final int childCount = pkg.childPackages.size();
14388                for (int i = 0; i < childCount; i++) {
14389                    PackageParser.Package childPkg = pkg.childPackages.get(i);
14390                    PackageInstalledInfo childRes = new PackageInstalledInfo();
14391                    childRes.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
14392                    childRes.pkg = childPkg;
14393                    childRes.name = childPkg.packageName;
14394                    PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName);
14395                    if (childPs != null) {
14396                        childRes.origUsers = childPs.queryInstalledUsers(
14397                                sUserManager.getUserIds(), true);
14398                    }
14399                    if ((mPackages.containsKey(childPkg.packageName))) {
14400                        childRes.removedInfo = new PackageRemovedInfo();
14401                        childRes.removedInfo.removedPackage = childPkg.packageName;
14402                    }
14403                    if (res.addedChildPackages == null) {
14404                        res.addedChildPackages = new ArrayMap<>();
14405                    }
14406                    res.addedChildPackages.put(childPkg.packageName, childRes);
14407                }
14408            }
14409        }
14410
14411        // If package doesn't declare API override, mark that we have an install
14412        // time CPU ABI override.
14413        if (TextUtils.isEmpty(pkg.cpuAbiOverride)) {
14414            pkg.cpuAbiOverride = args.abiOverride;
14415        }
14416
14417        String pkgName = res.name = pkg.packageName;
14418        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
14419            if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
14420                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
14421                return;
14422            }
14423        }
14424
14425        try {
14426            // either use what we've been given or parse directly from the APK
14427            if (args.certificates != null) {
14428                try {
14429                    PackageParser.populateCertificates(pkg, args.certificates);
14430                } catch (PackageParserException e) {
14431                    // there was something wrong with the certificates we were given;
14432                    // try to pull them from the APK
14433                    PackageParser.collectCertificates(pkg, parseFlags);
14434                }
14435            } else {
14436                PackageParser.collectCertificates(pkg, parseFlags);
14437            }
14438        } catch (PackageParserException e) {
14439            res.setError("Failed collect during installPackageLI", e);
14440            return;
14441        }
14442
14443        // Get rid of all references to package scan path via parser.
14444        pp = null;
14445        String oldCodePath = null;
14446        boolean systemApp = false;
14447        synchronized (mPackages) {
14448            // Check if installing already existing package
14449            if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
14450                String oldName = mSettings.mRenamedPackages.get(pkgName);
14451                if (pkg.mOriginalPackages != null
14452                        && pkg.mOriginalPackages.contains(oldName)
14453                        && mPackages.containsKey(oldName)) {
14454                    // This package is derived from an original package,
14455                    // and this device has been updating from that original
14456                    // name.  We must continue using the original name, so
14457                    // rename the new package here.
14458                    pkg.setPackageName(oldName);
14459                    pkgName = pkg.packageName;
14460                    replace = true;
14461                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
14462                            + oldName + " pkgName=" + pkgName);
14463                } else if (mPackages.containsKey(pkgName)) {
14464                    // This package, under its official name, already exists
14465                    // on the device; we should replace it.
14466                    replace = true;
14467                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
14468                }
14469
14470                // Child packages are installed through the parent package
14471                if (pkg.parentPackage != null) {
14472                    res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
14473                            "Package " + pkg.packageName + " is child of package "
14474                                    + pkg.parentPackage.parentPackage + ". Child packages "
14475                                    + "can be updated only through the parent package.");
14476                    return;
14477                }
14478
14479                if (replace) {
14480                    // Prevent apps opting out from runtime permissions
14481                    PackageParser.Package oldPackage = mPackages.get(pkgName);
14482                    final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion;
14483                    final int newTargetSdk = pkg.applicationInfo.targetSdkVersion;
14484                    if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1
14485                            && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) {
14486                        res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE,
14487                                "Package " + pkg.packageName + " new target SDK " + newTargetSdk
14488                                        + " doesn't support runtime permissions but the old"
14489                                        + " target SDK " + oldTargetSdk + " does.");
14490                        return;
14491                    }
14492
14493                    // Prevent installing of child packages
14494                    if (oldPackage.parentPackage != null) {
14495                        res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
14496                                "Package " + pkg.packageName + " is child of package "
14497                                        + oldPackage.parentPackage + ". Child packages "
14498                                        + "can be updated only through the parent package.");
14499                        return;
14500                    }
14501                }
14502            }
14503
14504            PackageSetting ps = mSettings.mPackages.get(pkgName);
14505            if (ps != null) {
14506                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
14507
14508                // Quick sanity check that we're signed correctly if updating;
14509                // we'll check this again later when scanning, but we want to
14510                // bail early here before tripping over redefined permissions.
14511                if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
14512                    if (!checkUpgradeKeySetLP(ps, pkg)) {
14513                        res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
14514                                + pkg.packageName + " upgrade keys do not match the "
14515                                + "previously installed version");
14516                        return;
14517                    }
14518                } else {
14519                    try {
14520                        verifySignaturesLP(ps, pkg);
14521                    } catch (PackageManagerException e) {
14522                        res.setError(e.error, e.getMessage());
14523                        return;
14524                    }
14525                }
14526
14527                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
14528                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
14529                    systemApp = (ps.pkg.applicationInfo.flags &
14530                            ApplicationInfo.FLAG_SYSTEM) != 0;
14531                }
14532                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
14533            }
14534
14535            // Check whether the newly-scanned package wants to define an already-defined perm
14536            int N = pkg.permissions.size();
14537            for (int i = N-1; i >= 0; i--) {
14538                PackageParser.Permission perm = pkg.permissions.get(i);
14539                BasePermission bp = mSettings.mPermissions.get(perm.info.name);
14540                if (bp != null) {
14541                    // If the defining package is signed with our cert, it's okay.  This
14542                    // also includes the "updating the same package" case, of course.
14543                    // "updating same package" could also involve key-rotation.
14544                    final boolean sigsOk;
14545                    if (bp.sourcePackage.equals(pkg.packageName)
14546                            && (bp.packageSetting instanceof PackageSetting)
14547                            && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting,
14548                                    scanFlags))) {
14549                        sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg);
14550                    } else {
14551                        sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures,
14552                                pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
14553                    }
14554                    if (!sigsOk) {
14555                        // If the owning package is the system itself, we log but allow
14556                        // install to proceed; we fail the install on all other permission
14557                        // redefinitions.
14558                        if (!bp.sourcePackage.equals("android")) {
14559                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
14560                                    + pkg.packageName + " attempting to redeclare permission "
14561                                    + perm.info.name + " already owned by " + bp.sourcePackage);
14562                            res.origPermission = perm.info.name;
14563                            res.origPackage = bp.sourcePackage;
14564                            return;
14565                        } else {
14566                            Slog.w(TAG, "Package " + pkg.packageName
14567                                    + " attempting to redeclare system permission "
14568                                    + perm.info.name + "; ignoring new declaration");
14569                            pkg.permissions.remove(i);
14570                        }
14571                    }
14572                }
14573            }
14574        }
14575
14576        if (systemApp) {
14577            if (onExternal) {
14578                // Abort update; system app can't be replaced with app on sdcard
14579                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
14580                        "Cannot install updates to system apps on sdcard");
14581                return;
14582            } else if (ephemeral) {
14583                // Abort update; system app can't be replaced with an ephemeral app
14584                res.setError(INSTALL_FAILED_EPHEMERAL_INVALID,
14585                        "Cannot update a system app with an ephemeral app");
14586                return;
14587            }
14588        }
14589
14590        if (args.move != null) {
14591            // We did an in-place move, so dex is ready to roll
14592            scanFlags |= SCAN_NO_DEX;
14593            scanFlags |= SCAN_MOVE;
14594
14595            synchronized (mPackages) {
14596                final PackageSetting ps = mSettings.mPackages.get(pkgName);
14597                if (ps == null) {
14598                    res.setError(INSTALL_FAILED_INTERNAL_ERROR,
14599                            "Missing settings for moved package " + pkgName);
14600                }
14601
14602                // We moved the entire application as-is, so bring over the
14603                // previously derived ABI information.
14604                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
14605                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
14606            }
14607
14608        } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) {
14609            // Enable SCAN_NO_DEX flag to skip dexopt at a later stage
14610            scanFlags |= SCAN_NO_DEX;
14611
14612            try {
14613                String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ?
14614                    args.abiOverride : pkg.cpuAbiOverride);
14615                derivePackageAbi(pkg, new File(pkg.codePath), abiOverride,
14616                        true /* extract libs */);
14617            } catch (PackageManagerException pme) {
14618                Slog.e(TAG, "Error deriving application ABI", pme);
14619                res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI");
14620                return;
14621            }
14622
14623            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
14624            // Do not run PackageDexOptimizer through the local performDexOpt
14625            // method because `pkg` is not in `mPackages` yet.
14626            int result = mPackageDexOptimizer.performDexOpt(pkg, null /* instructionSets */,
14627                    false /* checkProfiles */, getCompilerFilterForReason(REASON_INSTALL));
14628            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
14629            if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
14630                String msg = "Extracting package failed for " + pkgName;
14631                res.setError(INSTALL_FAILED_DEXOPT, msg);
14632                return;
14633            }
14634
14635            // Notify BackgroundDexOptService that the package has been changed.
14636            // If this is an update of a package which used to fail to compile,
14637            // BDOS will remove it from its blacklist.
14638            BackgroundDexOptService.notifyPackageChanged(pkg.packageName);
14639        }
14640
14641        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
14642            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
14643            return;
14644        }
14645
14646        startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg);
14647
14648        try (PackageFreezer freezer = freezePackageForInstall(pkgName, installFlags,
14649                "installPackageLI")) {
14650            if (replace) {
14651                replacePackageLIF(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user,
14652                        installerPackageName, res);
14653            } else {
14654                installNewPackageLIF(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
14655                        args.user, installerPackageName, volumeUuid, res);
14656            }
14657        }
14658        synchronized (mPackages) {
14659            final PackageSetting ps = mSettings.mPackages.get(pkgName);
14660            if (ps != null) {
14661                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
14662            }
14663
14664            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
14665            for (int i = 0; i < childCount; i++) {
14666                PackageParser.Package childPkg = pkg.childPackages.get(i);
14667                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
14668                PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName);
14669                if (childPs != null) {
14670                    childRes.newUsers = childPs.queryInstalledUsers(
14671                            sUserManager.getUserIds(), true);
14672                }
14673            }
14674        }
14675    }
14676
14677    private void startIntentFilterVerifications(int userId, boolean replacing,
14678            PackageParser.Package pkg) {
14679        if (mIntentFilterVerifierComponent == null) {
14680            Slog.w(TAG, "No IntentFilter verification will not be done as "
14681                    + "there is no IntentFilterVerifier available!");
14682            return;
14683        }
14684
14685        final int verifierUid = getPackageUid(
14686                mIntentFilterVerifierComponent.getPackageName(),
14687                MATCH_DEBUG_TRIAGED_MISSING,
14688                (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId);
14689
14690        Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
14691        msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid);
14692        mHandler.sendMessage(msg);
14693
14694        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
14695        for (int i = 0; i < childCount; i++) {
14696            PackageParser.Package childPkg = pkg.childPackages.get(i);
14697            msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
14698            msg.obj = new IFVerificationParams(childPkg, replacing, userId, verifierUid);
14699            mHandler.sendMessage(msg);
14700        }
14701    }
14702
14703    private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing,
14704            PackageParser.Package pkg) {
14705        int size = pkg.activities.size();
14706        if (size == 0) {
14707            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
14708                    "No activity, so no need to verify any IntentFilter!");
14709            return;
14710        }
14711
14712        final boolean hasDomainURLs = hasDomainURLs(pkg);
14713        if (!hasDomainURLs) {
14714            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
14715                    "No domain URLs, so no need to verify any IntentFilter!");
14716            return;
14717        }
14718
14719        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId
14720                + " if any IntentFilter from the " + size
14721                + " Activities needs verification ...");
14722
14723        int count = 0;
14724        final String packageName = pkg.packageName;
14725
14726        synchronized (mPackages) {
14727            // If this is a new install and we see that we've already run verification for this
14728            // package, we have nothing to do: it means the state was restored from backup.
14729            if (!replacing) {
14730                IntentFilterVerificationInfo ivi =
14731                        mSettings.getIntentFilterVerificationLPr(packageName);
14732                if (ivi != null) {
14733                    if (DEBUG_DOMAIN_VERIFICATION) {
14734                        Slog.i(TAG, "Package " + packageName+ " already verified: status="
14735                                + ivi.getStatusString());
14736                    }
14737                    return;
14738                }
14739            }
14740
14741            // If any filters need to be verified, then all need to be.
14742            boolean needToVerify = false;
14743            for (PackageParser.Activity a : pkg.activities) {
14744                for (ActivityIntentInfo filter : a.intents) {
14745                    if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) {
14746                        if (DEBUG_DOMAIN_VERIFICATION) {
14747                            Slog.d(TAG, "Intent filter needs verification, so processing all filters");
14748                        }
14749                        needToVerify = true;
14750                        break;
14751                    }
14752                }
14753            }
14754
14755            if (needToVerify) {
14756                final int verificationId = mIntentFilterVerificationToken++;
14757                for (PackageParser.Activity a : pkg.activities) {
14758                    for (ActivityIntentInfo filter : a.intents) {
14759                        if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) {
14760                            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
14761                                    "Verification needed for IntentFilter:" + filter.toString());
14762                            mIntentFilterVerifier.addOneIntentFilterVerification(
14763                                    verifierUid, userId, verificationId, filter, packageName);
14764                            count++;
14765                        }
14766                    }
14767                }
14768            }
14769        }
14770
14771        if (count > 0) {
14772            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count
14773                    + " IntentFilter verification" + (count > 1 ? "s" : "")
14774                    +  " for userId:" + userId);
14775            mIntentFilterVerifier.startVerifications(userId);
14776        } else {
14777            if (DEBUG_DOMAIN_VERIFICATION) {
14778                Slog.d(TAG, "No filters or not all autoVerify for " + packageName);
14779            }
14780        }
14781    }
14782
14783    private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) {
14784        final ComponentName cn  = filter.activity.getComponentName();
14785        final String packageName = cn.getPackageName();
14786
14787        IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr(
14788                packageName);
14789        if (ivi == null) {
14790            return true;
14791        }
14792        int status = ivi.getStatus();
14793        switch (status) {
14794            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
14795            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
14796                return true;
14797
14798            default:
14799                // Nothing to do
14800                return false;
14801        }
14802    }
14803
14804    private static boolean isMultiArch(ApplicationInfo info) {
14805        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
14806    }
14807
14808    private static boolean isExternal(PackageParser.Package pkg) {
14809        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
14810    }
14811
14812    private static boolean isExternal(PackageSetting ps) {
14813        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
14814    }
14815
14816    private static boolean isEphemeral(PackageParser.Package pkg) {
14817        return pkg.applicationInfo.isEphemeralApp();
14818    }
14819
14820    private static boolean isEphemeral(PackageSetting ps) {
14821        return ps.pkg != null && isEphemeral(ps.pkg);
14822    }
14823
14824    private static boolean isSystemApp(PackageParser.Package pkg) {
14825        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
14826    }
14827
14828    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
14829        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
14830    }
14831
14832    private static boolean hasDomainURLs(PackageParser.Package pkg) {
14833        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0;
14834    }
14835
14836    private static boolean isSystemApp(PackageSetting ps) {
14837        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
14838    }
14839
14840    private static boolean isUpdatedSystemApp(PackageSetting ps) {
14841        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
14842    }
14843
14844    private int packageFlagsToInstallFlags(PackageSetting ps) {
14845        int installFlags = 0;
14846        if (isEphemeral(ps)) {
14847            installFlags |= PackageManager.INSTALL_EPHEMERAL;
14848        }
14849        if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) {
14850            // This existing package was an external ASEC install when we have
14851            // the external flag without a UUID
14852            installFlags |= PackageManager.INSTALL_EXTERNAL;
14853        }
14854        if (ps.isForwardLocked()) {
14855            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
14856        }
14857        return installFlags;
14858    }
14859
14860    private String getVolumeUuidForPackage(PackageParser.Package pkg) {
14861        if (isExternal(pkg)) {
14862            if (TextUtils.isEmpty(pkg.volumeUuid)) {
14863                return StorageManager.UUID_PRIMARY_PHYSICAL;
14864            } else {
14865                return pkg.volumeUuid;
14866            }
14867        } else {
14868            return StorageManager.UUID_PRIVATE_INTERNAL;
14869        }
14870    }
14871
14872    private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) {
14873        if (isExternal(pkg)) {
14874            if (TextUtils.isEmpty(pkg.volumeUuid)) {
14875                return mSettings.getExternalVersion();
14876            } else {
14877                return mSettings.findOrCreateVersion(pkg.volumeUuid);
14878            }
14879        } else {
14880            return mSettings.getInternalVersion();
14881        }
14882    }
14883
14884    private void deleteTempPackageFiles() {
14885        final FilenameFilter filter = new FilenameFilter() {
14886            public boolean accept(File dir, String name) {
14887                return name.startsWith("vmdl") && name.endsWith(".tmp");
14888            }
14889        };
14890        for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) {
14891            file.delete();
14892        }
14893    }
14894
14895    @Override
14896    public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId,
14897            int flags) {
14898        deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId,
14899                flags);
14900    }
14901
14902    @Override
14903    public void deletePackage(final String packageName,
14904            final IPackageDeleteObserver2 observer, final int userId, final int deleteFlags) {
14905        mContext.enforceCallingOrSelfPermission(
14906                android.Manifest.permission.DELETE_PACKAGES, null);
14907        Preconditions.checkNotNull(packageName);
14908        Preconditions.checkNotNull(observer);
14909        final int uid = Binder.getCallingUid();
14910        final boolean deleteAllUsers = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0;
14911        final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId };
14912        if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) {
14913            mContext.enforceCallingOrSelfPermission(
14914                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
14915                    "deletePackage for user " + userId);
14916        }
14917
14918        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
14919            try {
14920                observer.onPackageDeleted(packageName,
14921                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
14922            } catch (RemoteException re) {
14923            }
14924            return;
14925        }
14926
14927        if (!deleteAllUsers && getBlockUninstallForUser(packageName, userId)) {
14928            try {
14929                observer.onPackageDeleted(packageName,
14930                        PackageManager.DELETE_FAILED_OWNER_BLOCKED, null);
14931            } catch (RemoteException re) {
14932            }
14933            return;
14934        }
14935
14936        if (DEBUG_REMOVE) {
14937            Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId
14938                    + " deleteAllUsers: " + deleteAllUsers );
14939        }
14940        // Queue up an async operation since the package deletion may take a little while.
14941        mHandler.post(new Runnable() {
14942            public void run() {
14943                mHandler.removeCallbacks(this);
14944                int returnCode;
14945                if (!deleteAllUsers) {
14946                    returnCode = deletePackageX(packageName, userId, deleteFlags);
14947                } else {
14948                    int[] blockUninstallUserIds = getBlockUninstallForUsers(packageName, users);
14949                    // If nobody is blocking uninstall, proceed with delete for all users
14950                    if (ArrayUtils.isEmpty(blockUninstallUserIds)) {
14951                        returnCode = deletePackageX(packageName, userId, deleteFlags);
14952                    } else {
14953                        // Otherwise uninstall individually for users with blockUninstalls=false
14954                        final int userFlags = deleteFlags & ~PackageManager.DELETE_ALL_USERS;
14955                        for (int userId : users) {
14956                            if (!ArrayUtils.contains(blockUninstallUserIds, userId)) {
14957                                returnCode = deletePackageX(packageName, userId, userFlags);
14958                                if (returnCode != PackageManager.DELETE_SUCCEEDED) {
14959                                    Slog.w(TAG, "Package delete failed for user " + userId
14960                                            + ", returnCode " + returnCode);
14961                                }
14962                            }
14963                        }
14964                        // The app has only been marked uninstalled for certain users.
14965                        // We still need to report that delete was blocked
14966                        returnCode = PackageManager.DELETE_FAILED_OWNER_BLOCKED;
14967                    }
14968                }
14969                try {
14970                    observer.onPackageDeleted(packageName, returnCode, null);
14971                } catch (RemoteException e) {
14972                    Log.i(TAG, "Observer no longer exists.");
14973                } //end catch
14974            } //end run
14975        });
14976    }
14977
14978    private int[] getBlockUninstallForUsers(String packageName, int[] userIds) {
14979        int[] result = EMPTY_INT_ARRAY;
14980        for (int userId : userIds) {
14981            if (getBlockUninstallForUser(packageName, userId)) {
14982                result = ArrayUtils.appendInt(result, userId);
14983            }
14984        }
14985        return result;
14986    }
14987
14988    @Override
14989    public boolean isPackageDeviceAdminOnAnyUser(String packageName) {
14990        return isPackageDeviceAdmin(packageName, UserHandle.USER_ALL);
14991    }
14992
14993    private boolean isPackageDeviceAdmin(String packageName, int userId) {
14994        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
14995                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
14996        try {
14997            if (dpm != null) {
14998                final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent(
14999                        /* callingUserOnly =*/ false);
15000                final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null
15001                        : deviceOwnerComponentName.getPackageName();
15002                // Does the package contains the device owner?
15003                // TODO Do we have to do it even if userId != UserHandle.USER_ALL?  Otherwise,
15004                // this check is probably not needed, since DO should be registered as a device
15005                // admin on some user too. (Original bug for this: b/17657954)
15006                if (packageName.equals(deviceOwnerPackageName)) {
15007                    return true;
15008                }
15009                // Does it contain a device admin for any user?
15010                int[] users;
15011                if (userId == UserHandle.USER_ALL) {
15012                    users = sUserManager.getUserIds();
15013                } else {
15014                    users = new int[]{userId};
15015                }
15016                for (int i = 0; i < users.length; ++i) {
15017                    if (dpm.packageHasActiveAdmins(packageName, users[i])) {
15018                        return true;
15019                    }
15020                }
15021            }
15022        } catch (RemoteException e) {
15023        }
15024        return false;
15025    }
15026
15027    private boolean shouldKeepUninstalledPackageLPr(String packageName) {
15028        return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName);
15029    }
15030
15031    /**
15032     *  This method is an internal method that could be get invoked either
15033     *  to delete an installed package or to clean up a failed installation.
15034     *  After deleting an installed package, a broadcast is sent to notify any
15035     *  listeners that the package has been removed. For cleaning up a failed
15036     *  installation, the broadcast is not necessary since the package's
15037     *  installation wouldn't have sent the initial broadcast either
15038     *  The key steps in deleting a package are
15039     *  deleting the package information in internal structures like mPackages,
15040     *  deleting the packages base directories through installd
15041     *  updating mSettings to reflect current status
15042     *  persisting settings for later use
15043     *  sending a broadcast if necessary
15044     */
15045    private int deletePackageX(String packageName, int userId, int deleteFlags) {
15046        final PackageRemovedInfo info = new PackageRemovedInfo();
15047        final boolean res;
15048
15049        final UserHandle removeForUser = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0
15050                ? UserHandle.ALL : new UserHandle(userId);
15051
15052        if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) {
15053            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
15054            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
15055        }
15056
15057        PackageSetting uninstalledPs = null;
15058
15059        // for the uninstall-updates case and restricted profiles, remember the per-
15060        // user handle installed state
15061        int[] allUsers;
15062        synchronized (mPackages) {
15063            uninstalledPs = mSettings.mPackages.get(packageName);
15064            if (uninstalledPs == null) {
15065                Slog.w(TAG, "Not removing non-existent package " + packageName);
15066                return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
15067            }
15068            allUsers = sUserManager.getUserIds();
15069            info.origUsers = uninstalledPs.queryInstalledUsers(allUsers, true);
15070        }
15071
15072        synchronized (mInstallLock) {
15073            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
15074            try (PackageFreezer freezer = freezePackageForDelete(packageName, deleteFlags,
15075                    "deletePackageX")) {
15076                res = deletePackageLIF(packageName, removeForUser, true, allUsers,
15077                        deleteFlags | REMOVE_CHATTY, info, true, null);
15078            }
15079            synchronized (mPackages) {
15080                if (res) {
15081                    mEphemeralApplicationRegistry.onPackageUninstalledLPw(uninstalledPs.pkg);
15082                }
15083            }
15084        }
15085
15086        if (res) {
15087            final boolean killApp = (deleteFlags & PackageManager.DELETE_DONT_KILL_APP) == 0;
15088            info.sendPackageRemovedBroadcasts(killApp);
15089            info.sendSystemPackageUpdatedBroadcasts();
15090            info.sendSystemPackageAppearedBroadcasts();
15091        }
15092        // Force a gc here.
15093        Runtime.getRuntime().gc();
15094        // Delete the resources here after sending the broadcast to let
15095        // other processes clean up before deleting resources.
15096        if (info.args != null) {
15097            synchronized (mInstallLock) {
15098                info.args.doPostDeleteLI(true);
15099            }
15100        }
15101
15102        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
15103    }
15104
15105    class PackageRemovedInfo {
15106        String removedPackage;
15107        int uid = -1;
15108        int removedAppId = -1;
15109        int[] origUsers;
15110        int[] removedUsers = null;
15111        boolean isRemovedPackageSystemUpdate = false;
15112        boolean isUpdate;
15113        boolean dataRemoved;
15114        boolean removedForAllUsers;
15115        // Clean up resources deleted packages.
15116        InstallArgs args = null;
15117        ArrayMap<String, PackageRemovedInfo> removedChildPackages;
15118        ArrayMap<String, PackageInstalledInfo> appearedChildPackages;
15119
15120        void sendPackageRemovedBroadcasts(boolean killApp) {
15121            sendPackageRemovedBroadcastInternal(killApp);
15122            final int childCount = removedChildPackages != null ? removedChildPackages.size() : 0;
15123            for (int i = 0; i < childCount; i++) {
15124                PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
15125                childInfo.sendPackageRemovedBroadcastInternal(killApp);
15126            }
15127        }
15128
15129        void sendSystemPackageUpdatedBroadcasts() {
15130            if (isRemovedPackageSystemUpdate) {
15131                sendSystemPackageUpdatedBroadcastsInternal();
15132                final int childCount = (removedChildPackages != null)
15133                        ? removedChildPackages.size() : 0;
15134                for (int i = 0; i < childCount; i++) {
15135                    PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
15136                    if (childInfo.isRemovedPackageSystemUpdate) {
15137                        childInfo.sendSystemPackageUpdatedBroadcastsInternal();
15138                    }
15139                }
15140            }
15141        }
15142
15143        void sendSystemPackageAppearedBroadcasts() {
15144            final int packageCount = (appearedChildPackages != null)
15145                    ? appearedChildPackages.size() : 0;
15146            for (int i = 0; i < packageCount; i++) {
15147                PackageInstalledInfo installedInfo = appearedChildPackages.valueAt(i);
15148                for (int userId : installedInfo.newUsers) {
15149                    sendPackageAddedForUser(installedInfo.name, true,
15150                            UserHandle.getAppId(installedInfo.uid), userId);
15151                }
15152            }
15153        }
15154
15155        private void sendSystemPackageUpdatedBroadcastsInternal() {
15156            Bundle extras = new Bundle(2);
15157            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
15158            extras.putBoolean(Intent.EXTRA_REPLACING, true);
15159            sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, removedPackage,
15160                    extras, 0, null, null, null);
15161            sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, removedPackage,
15162                    extras, 0, null, null, null);
15163            sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null,
15164                    null, 0, removedPackage, null, null);
15165        }
15166
15167        private void sendPackageRemovedBroadcastInternal(boolean killApp) {
15168            Bundle extras = new Bundle(2);
15169            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0  ? removedAppId : uid);
15170            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, dataRemoved);
15171            extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, !killApp);
15172            if (isUpdate || isRemovedPackageSystemUpdate) {
15173                extras.putBoolean(Intent.EXTRA_REPLACING, true);
15174            }
15175            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
15176            if (removedPackage != null) {
15177                sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
15178                        extras, 0, null, null, removedUsers);
15179                if (dataRemoved && !isRemovedPackageSystemUpdate) {
15180                    sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED,
15181                            removedPackage, extras, 0, null, null, removedUsers);
15182                }
15183            }
15184            if (removedAppId >= 0) {
15185                sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, 0, null, null,
15186                        removedUsers);
15187            }
15188        }
15189    }
15190
15191    /*
15192     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
15193     * flag is not set, the data directory is removed as well.
15194     * make sure this flag is set for partially installed apps. If not its meaningless to
15195     * delete a partially installed application.
15196     */
15197    private void removePackageDataLIF(PackageSetting ps, int[] allUserHandles,
15198            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
15199        String packageName = ps.name;
15200        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
15201        // Retrieve object to delete permissions for shared user later on
15202        final PackageParser.Package deletedPkg;
15203        final PackageSetting deletedPs;
15204        // reader
15205        synchronized (mPackages) {
15206            deletedPkg = mPackages.get(packageName);
15207            deletedPs = mSettings.mPackages.get(packageName);
15208            if (outInfo != null) {
15209                outInfo.removedPackage = packageName;
15210                outInfo.removedUsers = deletedPs != null
15211                        ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true)
15212                        : null;
15213            }
15214        }
15215
15216        removePackageLI(ps, (flags & REMOVE_CHATTY) != 0);
15217
15218        if ((flags & PackageManager.DELETE_KEEP_DATA) == 0) {
15219            destroyAppDataLIF(deletedPkg, UserHandle.USER_ALL,
15220                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
15221            destroyAppProfilesLIF(deletedPkg);
15222            if (outInfo != null) {
15223                outInfo.dataRemoved = true;
15224            }
15225            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
15226        }
15227
15228        // writer
15229        synchronized (mPackages) {
15230            if (deletedPs != null) {
15231                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
15232                    clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL);
15233                    clearDefaultBrowserIfNeeded(packageName);
15234                    if (outInfo != null) {
15235                        mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
15236                        outInfo.removedAppId = mSettings.removePackageLPw(packageName);
15237                    }
15238                    updatePermissionsLPw(deletedPs.name, null, 0);
15239                    if (deletedPs.sharedUser != null) {
15240                        // Remove permissions associated with package. Since runtime
15241                        // permissions are per user we have to kill the removed package
15242                        // or packages running under the shared user of the removed
15243                        // package if revoking the permissions requested only by the removed
15244                        // package is successful and this causes a change in gids.
15245                        for (int userId : UserManagerService.getInstance().getUserIds()) {
15246                            final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs,
15247                                    userId);
15248                            if (userIdToKill == UserHandle.USER_ALL
15249                                    || userIdToKill >= UserHandle.USER_SYSTEM) {
15250                                // If gids changed for this user, kill all affected packages.
15251                                mHandler.post(new Runnable() {
15252                                    @Override
15253                                    public void run() {
15254                                        // This has to happen with no lock held.
15255                                        killApplication(deletedPs.name, deletedPs.appId,
15256                                                KILL_APP_REASON_GIDS_CHANGED);
15257                                    }
15258                                });
15259                                break;
15260                            }
15261                        }
15262                    }
15263                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
15264                }
15265                // make sure to preserve per-user disabled state if this removal was just
15266                // a downgrade of a system app to the factory package
15267                if (allUserHandles != null && outInfo != null && outInfo.origUsers != null) {
15268                    if (DEBUG_REMOVE) {
15269                        Slog.d(TAG, "Propagating install state across downgrade");
15270                    }
15271                    for (int userId : allUserHandles) {
15272                        final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
15273                        if (DEBUG_REMOVE) {
15274                            Slog.d(TAG, "    user " + userId + " => " + installed);
15275                        }
15276                        ps.setInstalled(installed, userId);
15277                    }
15278                }
15279            }
15280            // can downgrade to reader
15281            if (writeSettings) {
15282                // Save settings now
15283                mSettings.writeLPr();
15284            }
15285        }
15286        if (outInfo != null) {
15287            // A user ID was deleted here. Go through all users and remove it
15288            // from KeyStore.
15289            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId);
15290        }
15291    }
15292
15293    static boolean locationIsPrivileged(File path) {
15294        try {
15295            final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
15296                    .getCanonicalPath();
15297            return path.getCanonicalPath().startsWith(privilegedAppDir);
15298        } catch (IOException e) {
15299            Slog.e(TAG, "Unable to access code path " + path);
15300        }
15301        return false;
15302    }
15303
15304    /*
15305     * Tries to delete system package.
15306     */
15307    private boolean deleteSystemPackageLIF(PackageParser.Package deletedPkg,
15308            PackageSetting deletedPs, int[] allUserHandles, int flags, PackageRemovedInfo outInfo,
15309            boolean writeSettings) {
15310        if (deletedPs.parentPackageName != null) {
15311            Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName);
15312            return false;
15313        }
15314
15315        final boolean applyUserRestrictions
15316                = (allUserHandles != null) && (outInfo.origUsers != null);
15317        final PackageSetting disabledPs;
15318        // Confirm if the system package has been updated
15319        // An updated system app can be deleted. This will also have to restore
15320        // the system pkg from system partition
15321        // reader
15322        synchronized (mPackages) {
15323            disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPs.name);
15324        }
15325
15326        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName
15327                + " disabledPs=" + disabledPs);
15328
15329        if (disabledPs == null) {
15330            Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName);
15331            return false;
15332        } else if (DEBUG_REMOVE) {
15333            Slog.d(TAG, "Deleting system pkg from data partition");
15334        }
15335
15336        if (DEBUG_REMOVE) {
15337            if (applyUserRestrictions) {
15338                Slog.d(TAG, "Remembering install states:");
15339                for (int userId : allUserHandles) {
15340                    final boolean finstalled = ArrayUtils.contains(outInfo.origUsers, userId);
15341                    Slog.d(TAG, "   u=" + userId + " inst=" + finstalled);
15342                }
15343            }
15344        }
15345
15346        // Delete the updated package
15347        outInfo.isRemovedPackageSystemUpdate = true;
15348        if (outInfo.removedChildPackages != null) {
15349            final int childCount = (deletedPs.childPackageNames != null)
15350                    ? deletedPs.childPackageNames.size() : 0;
15351            for (int i = 0; i < childCount; i++) {
15352                String childPackageName = deletedPs.childPackageNames.get(i);
15353                if (disabledPs.childPackageNames != null && disabledPs.childPackageNames
15354                        .contains(childPackageName)) {
15355                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
15356                            childPackageName);
15357                    if (childInfo != null) {
15358                        childInfo.isRemovedPackageSystemUpdate = true;
15359                    }
15360                }
15361            }
15362        }
15363
15364        if (disabledPs.versionCode < deletedPs.versionCode) {
15365            // Delete data for downgrades
15366            flags &= ~PackageManager.DELETE_KEEP_DATA;
15367        } else {
15368            // Preserve data by setting flag
15369            flags |= PackageManager.DELETE_KEEP_DATA;
15370        }
15371
15372        boolean ret = deleteInstalledPackageLIF(deletedPs, true, flags, allUserHandles,
15373                outInfo, writeSettings, disabledPs.pkg);
15374        if (!ret) {
15375            return false;
15376        }
15377
15378        // writer
15379        synchronized (mPackages) {
15380            // Reinstate the old system package
15381            enableSystemPackageLPw(disabledPs.pkg);
15382            // Remove any native libraries from the upgraded package.
15383            removeNativeBinariesLI(deletedPs);
15384        }
15385
15386        // Install the system package
15387        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
15388        int parseFlags = mDefParseFlags
15389                | PackageParser.PARSE_MUST_BE_APK
15390                | PackageParser.PARSE_IS_SYSTEM
15391                | PackageParser.PARSE_IS_SYSTEM_DIR;
15392        if (locationIsPrivileged(disabledPs.codePath)) {
15393            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
15394        }
15395
15396        final PackageParser.Package newPkg;
15397        try {
15398            newPkg = scanPackageTracedLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null);
15399        } catch (PackageManagerException e) {
15400            Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": "
15401                    + e.getMessage());
15402            return false;
15403        }
15404
15405        prepareAppDataAfterInstallLIF(newPkg);
15406
15407        // writer
15408        synchronized (mPackages) {
15409            PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
15410
15411            // Propagate the permissions state as we do not want to drop on the floor
15412            // runtime permissions. The update permissions method below will take
15413            // care of removing obsolete permissions and grant install permissions.
15414            ps.getPermissionsState().copyFrom(deletedPs.getPermissionsState());
15415            updatePermissionsLPw(newPkg.packageName, newPkg,
15416                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
15417
15418            if (applyUserRestrictions) {
15419                if (DEBUG_REMOVE) {
15420                    Slog.d(TAG, "Propagating install state across reinstall");
15421                }
15422                for (int userId : allUserHandles) {
15423                    final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
15424                    if (DEBUG_REMOVE) {
15425                        Slog.d(TAG, "    user " + userId + " => " + installed);
15426                    }
15427                    ps.setInstalled(installed, userId);
15428
15429                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
15430                }
15431                // Regardless of writeSettings we need to ensure that this restriction
15432                // state propagation is persisted
15433                mSettings.writeAllUsersPackageRestrictionsLPr();
15434            }
15435            // can downgrade to reader here
15436            if (writeSettings) {
15437                mSettings.writeLPr();
15438            }
15439        }
15440        return true;
15441    }
15442
15443    private boolean deleteInstalledPackageLIF(PackageSetting ps,
15444            boolean deleteCodeAndResources, int flags, int[] allUserHandles,
15445            PackageRemovedInfo outInfo, boolean writeSettings,
15446            PackageParser.Package replacingPackage) {
15447        synchronized (mPackages) {
15448            if (outInfo != null) {
15449                outInfo.uid = ps.appId;
15450            }
15451
15452            if (outInfo != null && outInfo.removedChildPackages != null) {
15453                final int childCount = (ps.childPackageNames != null)
15454                        ? ps.childPackageNames.size() : 0;
15455                for (int i = 0; i < childCount; i++) {
15456                    String childPackageName = ps.childPackageNames.get(i);
15457                    PackageSetting childPs = mSettings.mPackages.get(childPackageName);
15458                    if (childPs == null) {
15459                        return false;
15460                    }
15461                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
15462                            childPackageName);
15463                    if (childInfo != null) {
15464                        childInfo.uid = childPs.appId;
15465                    }
15466                }
15467            }
15468        }
15469
15470        // Delete package data from internal structures and also remove data if flag is set
15471        removePackageDataLIF(ps, allUserHandles, outInfo, flags, writeSettings);
15472
15473        // Delete the child packages data
15474        final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
15475        for (int i = 0; i < childCount; i++) {
15476            PackageSetting childPs;
15477            synchronized (mPackages) {
15478                childPs = mSettings.peekPackageLPr(ps.childPackageNames.get(i));
15479            }
15480            if (childPs != null) {
15481                PackageRemovedInfo childOutInfo = (outInfo != null
15482                        && outInfo.removedChildPackages != null)
15483                        ? outInfo.removedChildPackages.get(childPs.name) : null;
15484                final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0
15485                        && (replacingPackage != null
15486                        && !replacingPackage.hasChildPackage(childPs.name))
15487                        ? flags & ~DELETE_KEEP_DATA : flags;
15488                removePackageDataLIF(childPs, allUserHandles, childOutInfo,
15489                        deleteFlags, writeSettings);
15490            }
15491        }
15492
15493        // Delete application code and resources only for parent packages
15494        if (ps.parentPackageName == null) {
15495            if (deleteCodeAndResources && (outInfo != null)) {
15496                outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
15497                        ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
15498                if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
15499            }
15500        }
15501
15502        return true;
15503    }
15504
15505    @Override
15506    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
15507            int userId) {
15508        mContext.enforceCallingOrSelfPermission(
15509                android.Manifest.permission.DELETE_PACKAGES, null);
15510        synchronized (mPackages) {
15511            PackageSetting ps = mSettings.mPackages.get(packageName);
15512            if (ps == null) {
15513                Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName);
15514                return false;
15515            }
15516            if (!ps.getInstalled(userId)) {
15517                // Can't block uninstall for an app that is not installed or enabled.
15518                Log.i(TAG, "Package not installed in set block uninstall " + packageName);
15519                return false;
15520            }
15521            ps.setBlockUninstall(blockUninstall, userId);
15522            mSettings.writePackageRestrictionsLPr(userId);
15523        }
15524        return true;
15525    }
15526
15527    @Override
15528    public boolean getBlockUninstallForUser(String packageName, int userId) {
15529        synchronized (mPackages) {
15530            PackageSetting ps = mSettings.mPackages.get(packageName);
15531            if (ps == null) {
15532                Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName);
15533                return false;
15534            }
15535            return ps.getBlockUninstall(userId);
15536        }
15537    }
15538
15539    @Override
15540    public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) {
15541        int callingUid = Binder.getCallingUid();
15542        if (callingUid != Process.SYSTEM_UID && callingUid != Process.ROOT_UID) {
15543            throw new SecurityException(
15544                    "setRequiredForSystemUser can only be run by the system or root");
15545        }
15546        synchronized (mPackages) {
15547            PackageSetting ps = mSettings.mPackages.get(packageName);
15548            if (ps == null) {
15549                Log.w(TAG, "Package doesn't exist: " + packageName);
15550                return false;
15551            }
15552            if (systemUserApp) {
15553                ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
15554            } else {
15555                ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
15556            }
15557            mSettings.writeLPr();
15558        }
15559        return true;
15560    }
15561
15562    /*
15563     * This method handles package deletion in general
15564     */
15565    private boolean deletePackageLIF(String packageName, UserHandle user,
15566            boolean deleteCodeAndResources, int[] allUserHandles, int flags,
15567            PackageRemovedInfo outInfo, boolean writeSettings,
15568            PackageParser.Package replacingPackage) {
15569        if (packageName == null) {
15570            Slog.w(TAG, "Attempt to delete null packageName.");
15571            return false;
15572        }
15573
15574        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
15575
15576        PackageSetting ps;
15577
15578        synchronized (mPackages) {
15579            ps = mSettings.mPackages.get(packageName);
15580            if (ps == null) {
15581                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
15582                return false;
15583            }
15584
15585            if (ps.parentPackageName != null && (!isSystemApp(ps)
15586                    || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) {
15587                if (DEBUG_REMOVE) {
15588                    Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:"
15589                            + ((user == null) ? UserHandle.USER_ALL : user));
15590                }
15591                final int removedUserId = (user != null) ? user.getIdentifier()
15592                        : UserHandle.USER_ALL;
15593                if (!clearPackageStateForUserLIF(ps, removedUserId, outInfo)) {
15594                    return false;
15595                }
15596                markPackageUninstalledForUserLPw(ps, user);
15597                scheduleWritePackageRestrictionsLocked(user);
15598                return true;
15599            }
15600        }
15601
15602        if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
15603                && user.getIdentifier() != UserHandle.USER_ALL)) {
15604            // The caller is asking that the package only be deleted for a single
15605            // user.  To do this, we just mark its uninstalled state and delete
15606            // its data. If this is a system app, we only allow this to happen if
15607            // they have set the special DELETE_SYSTEM_APP which requests different
15608            // semantics than normal for uninstalling system apps.
15609            markPackageUninstalledForUserLPw(ps, user);
15610
15611            if (!isSystemApp(ps)) {
15612                // Do not uninstall the APK if an app should be cached
15613                boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName);
15614                if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) {
15615                    // Other user still have this package installed, so all
15616                    // we need to do is clear this user's data and save that
15617                    // it is uninstalled.
15618                    if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
15619                    if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
15620                        return false;
15621                    }
15622                    scheduleWritePackageRestrictionsLocked(user);
15623                    return true;
15624                } else {
15625                    // We need to set it back to 'installed' so the uninstall
15626                    // broadcasts will be sent correctly.
15627                    if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
15628                    ps.setInstalled(true, user.getIdentifier());
15629                }
15630            } else {
15631                // This is a system app, so we assume that the
15632                // other users still have this package installed, so all
15633                // we need to do is clear this user's data and save that
15634                // it is uninstalled.
15635                if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
15636                if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
15637                    return false;
15638                }
15639                scheduleWritePackageRestrictionsLocked(user);
15640                return true;
15641            }
15642        }
15643
15644        // If we are deleting a composite package for all users, keep track
15645        // of result for each child.
15646        if (ps.childPackageNames != null && outInfo != null) {
15647            synchronized (mPackages) {
15648                final int childCount = ps.childPackageNames.size();
15649                outInfo.removedChildPackages = new ArrayMap<>(childCount);
15650                for (int i = 0; i < childCount; i++) {
15651                    String childPackageName = ps.childPackageNames.get(i);
15652                    PackageRemovedInfo childInfo = new PackageRemovedInfo();
15653                    childInfo.removedPackage = childPackageName;
15654                    outInfo.removedChildPackages.put(childPackageName, childInfo);
15655                    PackageSetting childPs = mSettings.peekPackageLPr(childPackageName);
15656                    if (childPs != null) {
15657                        childInfo.origUsers = childPs.queryInstalledUsers(allUserHandles, true);
15658                    }
15659                }
15660            }
15661        }
15662
15663        boolean ret = false;
15664        if (isSystemApp(ps)) {
15665            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name);
15666            // When an updated system application is deleted we delete the existing resources
15667            // as well and fall back to existing code in system partition
15668            ret = deleteSystemPackageLIF(ps.pkg, ps, allUserHandles, flags, outInfo, writeSettings);
15669        } else {
15670            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name);
15671            ret = deleteInstalledPackageLIF(ps, deleteCodeAndResources, flags, allUserHandles,
15672                    outInfo, writeSettings, replacingPackage);
15673        }
15674
15675        // Take a note whether we deleted the package for all users
15676        if (outInfo != null) {
15677            outInfo.removedForAllUsers = mPackages.get(ps.name) == null;
15678            if (outInfo.removedChildPackages != null) {
15679                synchronized (mPackages) {
15680                    final int childCount = outInfo.removedChildPackages.size();
15681                    for (int i = 0; i < childCount; i++) {
15682                        PackageRemovedInfo childInfo = outInfo.removedChildPackages.valueAt(i);
15683                        if (childInfo != null) {
15684                            childInfo.removedForAllUsers = mPackages.get(
15685                                    childInfo.removedPackage) == null;
15686                        }
15687                    }
15688                }
15689            }
15690            // If we uninstalled an update to a system app there may be some
15691            // child packages that appeared as they are declared in the system
15692            // app but were not declared in the update.
15693            if (isSystemApp(ps)) {
15694                synchronized (mPackages) {
15695                    PackageSetting updatedPs = mSettings.peekPackageLPr(ps.name);
15696                    final int childCount = (updatedPs.childPackageNames != null)
15697                            ? updatedPs.childPackageNames.size() : 0;
15698                    for (int i = 0; i < childCount; i++) {
15699                        String childPackageName = updatedPs.childPackageNames.get(i);
15700                        if (outInfo.removedChildPackages == null
15701                                || outInfo.removedChildPackages.indexOfKey(childPackageName) < 0) {
15702                            PackageSetting childPs = mSettings.peekPackageLPr(childPackageName);
15703                            if (childPs == null) {
15704                                continue;
15705                            }
15706                            PackageInstalledInfo installRes = new PackageInstalledInfo();
15707                            installRes.name = childPackageName;
15708                            installRes.newUsers = childPs.queryInstalledUsers(allUserHandles, true);
15709                            installRes.pkg = mPackages.get(childPackageName);
15710                            installRes.uid = childPs.pkg.applicationInfo.uid;
15711                            if (outInfo.appearedChildPackages == null) {
15712                                outInfo.appearedChildPackages = new ArrayMap<>();
15713                            }
15714                            outInfo.appearedChildPackages.put(childPackageName, installRes);
15715                        }
15716                    }
15717                }
15718            }
15719        }
15720
15721        return ret;
15722    }
15723
15724    private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) {
15725        final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL)
15726                ? sUserManager.getUserIds() : new int[] {user.getIdentifier()};
15727        for (int nextUserId : userIds) {
15728            if (DEBUG_REMOVE) {
15729                Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId);
15730            }
15731            ps.setUserState(nextUserId, 0, COMPONENT_ENABLED_STATE_DEFAULT,
15732                    false /*installed*/, true /*stopped*/, true /*notLaunched*/,
15733                    false /*hidden*/, false /*suspended*/, null, null, null,
15734                    false /*blockUninstall*/,
15735                    ps.readUserState(nextUserId).domainVerificationStatus, 0);
15736        }
15737    }
15738
15739    private boolean clearPackageStateForUserLIF(PackageSetting ps, int userId,
15740            PackageRemovedInfo outInfo) {
15741        final PackageParser.Package pkg;
15742        synchronized (mPackages) {
15743            pkg = mPackages.get(ps.name);
15744        }
15745
15746        final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds()
15747                : new int[] {userId};
15748        for (int nextUserId : userIds) {
15749            if (DEBUG_REMOVE) {
15750                Slog.d(TAG, "Updating package:" + ps.name + " install state for user:"
15751                        + nextUserId);
15752            }
15753
15754            destroyAppDataLIF(pkg, userId,
15755                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
15756            removeKeystoreDataIfNeeded(nextUserId, ps.appId);
15757            schedulePackageCleaning(ps.name, nextUserId, false);
15758            synchronized (mPackages) {
15759                if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) {
15760                    scheduleWritePackageRestrictionsLocked(nextUserId);
15761                }
15762                resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId);
15763            }
15764        }
15765
15766        if (outInfo != null) {
15767            outInfo.removedPackage = ps.name;
15768            outInfo.removedAppId = ps.appId;
15769            outInfo.removedUsers = userIds;
15770        }
15771
15772        return true;
15773    }
15774
15775    private final class ClearStorageConnection implements ServiceConnection {
15776        IMediaContainerService mContainerService;
15777
15778        @Override
15779        public void onServiceConnected(ComponentName name, IBinder service) {
15780            synchronized (this) {
15781                mContainerService = IMediaContainerService.Stub.asInterface(service);
15782                notifyAll();
15783            }
15784        }
15785
15786        @Override
15787        public void onServiceDisconnected(ComponentName name) {
15788        }
15789    }
15790
15791    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
15792        if (DEFAULT_CONTAINER_PACKAGE.equals(packageName)) return;
15793
15794        final boolean mounted;
15795        if (Environment.isExternalStorageEmulated()) {
15796            mounted = true;
15797        } else {
15798            final String status = Environment.getExternalStorageState();
15799
15800            mounted = status.equals(Environment.MEDIA_MOUNTED)
15801                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
15802        }
15803
15804        if (!mounted) {
15805            return;
15806        }
15807
15808        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
15809        int[] users;
15810        if (userId == UserHandle.USER_ALL) {
15811            users = sUserManager.getUserIds();
15812        } else {
15813            users = new int[] { userId };
15814        }
15815        final ClearStorageConnection conn = new ClearStorageConnection();
15816        if (mContext.bindServiceAsUser(
15817                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
15818            try {
15819                for (int curUser : users) {
15820                    long timeout = SystemClock.uptimeMillis() + 5000;
15821                    synchronized (conn) {
15822                        long now = SystemClock.uptimeMillis();
15823                        while (conn.mContainerService == null && now < timeout) {
15824                            try {
15825                                conn.wait(timeout - now);
15826                            } catch (InterruptedException e) {
15827                            }
15828                        }
15829                    }
15830                    if (conn.mContainerService == null) {
15831                        return;
15832                    }
15833
15834                    final UserEnvironment userEnv = new UserEnvironment(curUser);
15835                    clearDirectory(conn.mContainerService,
15836                            userEnv.buildExternalStorageAppCacheDirs(packageName));
15837                    if (allData) {
15838                        clearDirectory(conn.mContainerService,
15839                                userEnv.buildExternalStorageAppDataDirs(packageName));
15840                        clearDirectory(conn.mContainerService,
15841                                userEnv.buildExternalStorageAppMediaDirs(packageName));
15842                    }
15843                }
15844            } finally {
15845                mContext.unbindService(conn);
15846            }
15847        }
15848    }
15849
15850    @Override
15851    public void clearApplicationProfileData(String packageName) {
15852        enforceSystemOrRoot("Only the system can clear all profile data");
15853
15854        final PackageParser.Package pkg;
15855        synchronized (mPackages) {
15856            pkg = mPackages.get(packageName);
15857        }
15858
15859        try (PackageFreezer freezer = freezePackage(packageName, "clearApplicationProfileData")) {
15860            synchronized (mInstallLock) {
15861                clearAppProfilesLIF(pkg);
15862            }
15863        }
15864    }
15865
15866    @Override
15867    public void clearApplicationUserData(final String packageName,
15868            final IPackageDataObserver observer, final int userId) {
15869        mContext.enforceCallingOrSelfPermission(
15870                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
15871
15872        enforceCrossUserPermission(Binder.getCallingUid(), userId,
15873                true /* requireFullPermission */, false /* checkShell */, "clear application data");
15874
15875        final DevicePolicyManagerInternal dpmi = LocalServices
15876                .getService(DevicePolicyManagerInternal.class);
15877        if (dpmi != null && dpmi.hasDeviceOwnerOrProfileOwner(packageName, userId)) {
15878            throw new SecurityException("Cannot clear data for a device owner or a profile owner");
15879        }
15880        // Queue up an async operation since the package deletion may take a little while.
15881        mHandler.post(new Runnable() {
15882            public void run() {
15883                mHandler.removeCallbacks(this);
15884                final boolean succeeded;
15885                try (PackageFreezer freezer = freezePackage(packageName,
15886                        "clearApplicationUserData")) {
15887                    synchronized (mInstallLock) {
15888                        succeeded = clearApplicationUserDataLIF(packageName, userId);
15889                    }
15890                    clearExternalStorageDataSync(packageName, userId, true);
15891                }
15892                if (succeeded) {
15893                    // invoke DeviceStorageMonitor's update method to clear any notifications
15894                    DeviceStorageMonitorInternal dsm = LocalServices
15895                            .getService(DeviceStorageMonitorInternal.class);
15896                    if (dsm != null) {
15897                        dsm.checkMemory();
15898                    }
15899                }
15900                if(observer != null) {
15901                    try {
15902                        observer.onRemoveCompleted(packageName, succeeded);
15903                    } catch (RemoteException e) {
15904                        Log.i(TAG, "Observer no longer exists.");
15905                    }
15906                } //end if observer
15907            } //end run
15908        });
15909    }
15910
15911    private boolean clearApplicationUserDataLIF(String packageName, int userId) {
15912        if (packageName == null) {
15913            Slog.w(TAG, "Attempt to delete null packageName.");
15914            return false;
15915        }
15916
15917        // Try finding details about the requested package
15918        PackageParser.Package pkg;
15919        synchronized (mPackages) {
15920            pkg = mPackages.get(packageName);
15921            if (pkg == null) {
15922                final PackageSetting ps = mSettings.mPackages.get(packageName);
15923                if (ps != null) {
15924                    pkg = ps.pkg;
15925                }
15926            }
15927
15928            if (pkg == null) {
15929                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
15930                return false;
15931            }
15932
15933            PackageSetting ps = (PackageSetting) pkg.mExtras;
15934            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
15935        }
15936
15937        clearAppDataLIF(pkg, userId,
15938                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
15939
15940        final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
15941        removeKeystoreDataIfNeeded(userId, appId);
15942
15943        final UserManager um = mContext.getSystemService(UserManager.class);
15944        final int flags;
15945        if (um.isUserUnlocked(userId)) {
15946            flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
15947        } else if (um.isUserRunning(userId)) {
15948            flags = StorageManager.FLAG_STORAGE_DE;
15949        } else {
15950            flags = 0;
15951        }
15952        prepareAppDataContentsLIF(pkg, userId, flags);
15953
15954        return true;
15955    }
15956
15957    /**
15958     * Reverts user permission state changes (permissions and flags) in
15959     * all packages for a given user.
15960     *
15961     * @param userId The device user for which to do a reset.
15962     */
15963    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) {
15964        final int packageCount = mPackages.size();
15965        for (int i = 0; i < packageCount; i++) {
15966            PackageParser.Package pkg = mPackages.valueAt(i);
15967            PackageSetting ps = (PackageSetting) pkg.mExtras;
15968            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
15969        }
15970    }
15971
15972    /**
15973     * Reverts user permission state changes (permissions and flags).
15974     *
15975     * @param ps The package for which to reset.
15976     * @param userId The device user for which to do a reset.
15977     */
15978    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(
15979            final PackageSetting ps, final int userId) {
15980        if (ps.pkg == null) {
15981            return;
15982        }
15983
15984        // These are flags that can change base on user actions.
15985        final int userSettableMask = FLAG_PERMISSION_USER_SET
15986                | FLAG_PERMISSION_USER_FIXED
15987                | FLAG_PERMISSION_REVOKE_ON_UPGRADE
15988                | FLAG_PERMISSION_REVIEW_REQUIRED;
15989
15990        final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED
15991                | FLAG_PERMISSION_POLICY_FIXED;
15992
15993        boolean writeInstallPermissions = false;
15994        boolean writeRuntimePermissions = false;
15995
15996        final int permissionCount = ps.pkg.requestedPermissions.size();
15997        for (int i = 0; i < permissionCount; i++) {
15998            String permission = ps.pkg.requestedPermissions.get(i);
15999
16000            BasePermission bp = mSettings.mPermissions.get(permission);
16001            if (bp == null) {
16002                continue;
16003            }
16004
16005            // If shared user we just reset the state to which only this app contributed.
16006            if (ps.sharedUser != null) {
16007                boolean used = false;
16008                final int packageCount = ps.sharedUser.packages.size();
16009                for (int j = 0; j < packageCount; j++) {
16010                    PackageSetting pkg = ps.sharedUser.packages.valueAt(j);
16011                    if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName)
16012                            && pkg.pkg.requestedPermissions.contains(permission)) {
16013                        used = true;
16014                        break;
16015                    }
16016                }
16017                if (used) {
16018                    continue;
16019                }
16020            }
16021
16022            PermissionsState permissionsState = ps.getPermissionsState();
16023
16024            final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId);
16025
16026            // Always clear the user settable flags.
16027            final boolean hasInstallState = permissionsState.getInstallPermissionState(
16028                    bp.name) != null;
16029            // If permission review is enabled and this is a legacy app, mark the
16030            // permission as requiring a review as this is the initial state.
16031            int flags = 0;
16032            if (Build.PERMISSIONS_REVIEW_REQUIRED
16033                    && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
16034                flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
16035            }
16036            if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) {
16037                if (hasInstallState) {
16038                    writeInstallPermissions = true;
16039                } else {
16040                    writeRuntimePermissions = true;
16041                }
16042            }
16043
16044            // Below is only runtime permission handling.
16045            if (!bp.isRuntime()) {
16046                continue;
16047            }
16048
16049            // Never clobber system or policy.
16050            if ((oldFlags & policyOrSystemFlags) != 0) {
16051                continue;
16052            }
16053
16054            // If this permission was granted by default, make sure it is.
16055            if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) {
16056                if (permissionsState.grantRuntimePermission(bp, userId)
16057                        != PERMISSION_OPERATION_FAILURE) {
16058                    writeRuntimePermissions = true;
16059                }
16060            // If permission review is enabled the permissions for a legacy apps
16061            // are represented as constantly granted runtime ones, so don't revoke.
16062            } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
16063                // Otherwise, reset the permission.
16064                final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId);
16065                switch (revokeResult) {
16066                    case PERMISSION_OPERATION_SUCCESS:
16067                    case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
16068                        writeRuntimePermissions = true;
16069                        final int appId = ps.appId;
16070                        mHandler.post(new Runnable() {
16071                            @Override
16072                            public void run() {
16073                                killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
16074                            }
16075                        });
16076                    } break;
16077                }
16078            }
16079        }
16080
16081        // Synchronously write as we are taking permissions away.
16082        if (writeRuntimePermissions) {
16083            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
16084        }
16085
16086        // Synchronously write as we are taking permissions away.
16087        if (writeInstallPermissions) {
16088            mSettings.writeLPr();
16089        }
16090    }
16091
16092    /**
16093     * Remove entries from the keystore daemon. Will only remove it if the
16094     * {@code appId} is valid.
16095     */
16096    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
16097        if (appId < 0) {
16098            return;
16099        }
16100
16101        final KeyStore keyStore = KeyStore.getInstance();
16102        if (keyStore != null) {
16103            if (userId == UserHandle.USER_ALL) {
16104                for (final int individual : sUserManager.getUserIds()) {
16105                    keyStore.clearUid(UserHandle.getUid(individual, appId));
16106                }
16107            } else {
16108                keyStore.clearUid(UserHandle.getUid(userId, appId));
16109            }
16110        } else {
16111            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
16112        }
16113    }
16114
16115    @Override
16116    public void deleteApplicationCacheFiles(final String packageName,
16117            final IPackageDataObserver observer) {
16118        final int userId = UserHandle.getCallingUserId();
16119        deleteApplicationCacheFilesAsUser(packageName, userId, observer);
16120    }
16121
16122    @Override
16123    public void deleteApplicationCacheFilesAsUser(final String packageName, final int userId,
16124            final IPackageDataObserver observer) {
16125        mContext.enforceCallingOrSelfPermission(
16126                android.Manifest.permission.DELETE_CACHE_FILES, null);
16127        enforceCrossUserPermission(Binder.getCallingUid(), userId,
16128                /* requireFullPermission= */ true, /* checkShell= */ false,
16129                "delete application cache files");
16130
16131        final PackageParser.Package pkg;
16132        synchronized (mPackages) {
16133            pkg = mPackages.get(packageName);
16134        }
16135
16136        // Queue up an async operation since the package deletion may take a little while.
16137        mHandler.post(new Runnable() {
16138            public void run() {
16139                synchronized (mInstallLock) {
16140                    final int flags = StorageManager.FLAG_STORAGE_DE
16141                            | StorageManager.FLAG_STORAGE_CE;
16142                    // We're only clearing cache files, so we don't care if the
16143                    // app is unfrozen and still able to run
16144                    clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CACHE_ONLY);
16145                    clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
16146                }
16147                clearExternalStorageDataSync(packageName, userId, false);
16148                if (observer != null) {
16149                    try {
16150                        observer.onRemoveCompleted(packageName, true);
16151                    } catch (RemoteException e) {
16152                        Log.i(TAG, "Observer no longer exists.");
16153                    }
16154                }
16155            }
16156        });
16157    }
16158
16159    @Override
16160    public void getPackageSizeInfo(final String packageName, int userHandle,
16161            final IPackageStatsObserver observer) {
16162        mContext.enforceCallingOrSelfPermission(
16163                android.Manifest.permission.GET_PACKAGE_SIZE, null);
16164        if (packageName == null) {
16165            throw new IllegalArgumentException("Attempt to get size of null packageName");
16166        }
16167
16168        PackageStats stats = new PackageStats(packageName, userHandle);
16169
16170        /*
16171         * Queue up an async operation since the package measurement may take a
16172         * little while.
16173         */
16174        Message msg = mHandler.obtainMessage(INIT_COPY);
16175        msg.obj = new MeasureParams(stats, observer);
16176        mHandler.sendMessage(msg);
16177    }
16178
16179    private boolean getPackageSizeInfoLI(String packageName, int userId, PackageStats stats) {
16180        final PackageSetting ps;
16181        synchronized (mPackages) {
16182            ps = mSettings.mPackages.get(packageName);
16183            if (ps == null) {
16184                Slog.w(TAG, "Failed to find settings for " + packageName);
16185                return false;
16186            }
16187        }
16188        try {
16189            mInstaller.getAppSize(ps.volumeUuid, packageName, userId,
16190                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE,
16191                    ps.getCeDataInode(userId), ps.codePathString, stats);
16192        } catch (InstallerException e) {
16193            Slog.w(TAG, String.valueOf(e));
16194            return false;
16195        }
16196
16197        // For now, ignore code size of packages on system partition
16198        if (isSystemApp(ps) && !isUpdatedSystemApp(ps)) {
16199            stats.codeSize = 0;
16200        }
16201
16202        return true;
16203    }
16204
16205    private int getUidTargetSdkVersionLockedLPr(int uid) {
16206        Object obj = mSettings.getUserIdLPr(uid);
16207        if (obj instanceof SharedUserSetting) {
16208            final SharedUserSetting sus = (SharedUserSetting) obj;
16209            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
16210            final Iterator<PackageSetting> it = sus.packages.iterator();
16211            while (it.hasNext()) {
16212                final PackageSetting ps = it.next();
16213                if (ps.pkg != null) {
16214                    int v = ps.pkg.applicationInfo.targetSdkVersion;
16215                    if (v < vers) vers = v;
16216                }
16217            }
16218            return vers;
16219        } else if (obj instanceof PackageSetting) {
16220            final PackageSetting ps = (PackageSetting) obj;
16221            if (ps.pkg != null) {
16222                return ps.pkg.applicationInfo.targetSdkVersion;
16223            }
16224        }
16225        return Build.VERSION_CODES.CUR_DEVELOPMENT;
16226    }
16227
16228    @Override
16229    public void addPreferredActivity(IntentFilter filter, int match,
16230            ComponentName[] set, ComponentName activity, int userId) {
16231        addPreferredActivityInternal(filter, match, set, activity, true, userId,
16232                "Adding preferred");
16233    }
16234
16235    private void addPreferredActivityInternal(IntentFilter filter, int match,
16236            ComponentName[] set, ComponentName activity, boolean always, int userId,
16237            String opname) {
16238        // writer
16239        int callingUid = Binder.getCallingUid();
16240        enforceCrossUserPermission(callingUid, userId,
16241                true /* requireFullPermission */, false /* checkShell */, "add preferred activity");
16242        if (filter.countActions() == 0) {
16243            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
16244            return;
16245        }
16246        synchronized (mPackages) {
16247            if (mContext.checkCallingOrSelfPermission(
16248                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
16249                    != PackageManager.PERMISSION_GRANTED) {
16250                if (getUidTargetSdkVersionLockedLPr(callingUid)
16251                        < Build.VERSION_CODES.FROYO) {
16252                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
16253                            + callingUid);
16254                    return;
16255                }
16256                mContext.enforceCallingOrSelfPermission(
16257                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
16258            }
16259
16260            PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
16261            Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
16262                    + userId + ":");
16263            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
16264            pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
16265            scheduleWritePackageRestrictionsLocked(userId);
16266        }
16267    }
16268
16269    @Override
16270    public void replacePreferredActivity(IntentFilter filter, int match,
16271            ComponentName[] set, ComponentName activity, int userId) {
16272        if (filter.countActions() != 1) {
16273            throw new IllegalArgumentException(
16274                    "replacePreferredActivity expects filter to have only 1 action.");
16275        }
16276        if (filter.countDataAuthorities() != 0
16277                || filter.countDataPaths() != 0
16278                || filter.countDataSchemes() > 1
16279                || filter.countDataTypes() != 0) {
16280            throw new IllegalArgumentException(
16281                    "replacePreferredActivity expects filter to have no data authorities, " +
16282                    "paths, or types; and at most one scheme.");
16283        }
16284
16285        final int callingUid = Binder.getCallingUid();
16286        enforceCrossUserPermission(callingUid, userId,
16287                true /* requireFullPermission */, false /* checkShell */,
16288                "replace preferred activity");
16289        synchronized (mPackages) {
16290            if (mContext.checkCallingOrSelfPermission(
16291                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
16292                    != PackageManager.PERMISSION_GRANTED) {
16293                if (getUidTargetSdkVersionLockedLPr(callingUid)
16294                        < Build.VERSION_CODES.FROYO) {
16295                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
16296                            + Binder.getCallingUid());
16297                    return;
16298                }
16299                mContext.enforceCallingOrSelfPermission(
16300                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
16301            }
16302
16303            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
16304            if (pir != null) {
16305                // Get all of the existing entries that exactly match this filter.
16306                ArrayList<PreferredActivity> existing = pir.findFilters(filter);
16307                if (existing != null && existing.size() == 1) {
16308                    PreferredActivity cur = existing.get(0);
16309                    if (DEBUG_PREFERRED) {
16310                        Slog.i(TAG, "Checking replace of preferred:");
16311                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
16312                        if (!cur.mPref.mAlways) {
16313                            Slog.i(TAG, "  -- CUR; not mAlways!");
16314                        } else {
16315                            Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
16316                            Slog.i(TAG, "  -- CUR: mSet="
16317                                    + Arrays.toString(cur.mPref.mSetComponents));
16318                            Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
16319                            Slog.i(TAG, "  -- NEW: mMatch="
16320                                    + (match&IntentFilter.MATCH_CATEGORY_MASK));
16321                            Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
16322                            Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
16323                        }
16324                    }
16325                    if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
16326                            && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
16327                            && cur.mPref.sameSet(set)) {
16328                        // Setting the preferred activity to what it happens to be already
16329                        if (DEBUG_PREFERRED) {
16330                            Slog.i(TAG, "Replacing with same preferred activity "
16331                                    + cur.mPref.mShortComponent + " for user "
16332                                    + userId + ":");
16333                            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
16334                        }
16335                        return;
16336                    }
16337                }
16338
16339                if (existing != null) {
16340                    if (DEBUG_PREFERRED) {
16341                        Slog.i(TAG, existing.size() + " existing preferred matches for:");
16342                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
16343                    }
16344                    for (int i = 0; i < existing.size(); i++) {
16345                        PreferredActivity pa = existing.get(i);
16346                        if (DEBUG_PREFERRED) {
16347                            Slog.i(TAG, "Removing existing preferred activity "
16348                                    + pa.mPref.mComponent + ":");
16349                            pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
16350                        }
16351                        pir.removeFilter(pa);
16352                    }
16353                }
16354            }
16355            addPreferredActivityInternal(filter, match, set, activity, true, userId,
16356                    "Replacing preferred");
16357        }
16358    }
16359
16360    @Override
16361    public void clearPackagePreferredActivities(String packageName) {
16362        final int uid = Binder.getCallingUid();
16363        // writer
16364        synchronized (mPackages) {
16365            PackageParser.Package pkg = mPackages.get(packageName);
16366            if (pkg == null || pkg.applicationInfo.uid != uid) {
16367                if (mContext.checkCallingOrSelfPermission(
16368                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
16369                        != PackageManager.PERMISSION_GRANTED) {
16370                    if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid())
16371                            < Build.VERSION_CODES.FROYO) {
16372                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
16373                                + Binder.getCallingUid());
16374                        return;
16375                    }
16376                    mContext.enforceCallingOrSelfPermission(
16377                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
16378                }
16379            }
16380
16381            int user = UserHandle.getCallingUserId();
16382            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
16383                scheduleWritePackageRestrictionsLocked(user);
16384            }
16385        }
16386    }
16387
16388    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
16389    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
16390        ArrayList<PreferredActivity> removed = null;
16391        boolean changed = false;
16392        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
16393            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
16394            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
16395            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
16396                continue;
16397            }
16398            Iterator<PreferredActivity> it = pir.filterIterator();
16399            while (it.hasNext()) {
16400                PreferredActivity pa = it.next();
16401                // Mark entry for removal only if it matches the package name
16402                // and the entry is of type "always".
16403                if (packageName == null ||
16404                        (pa.mPref.mComponent.getPackageName().equals(packageName)
16405                                && pa.mPref.mAlways)) {
16406                    if (removed == null) {
16407                        removed = new ArrayList<PreferredActivity>();
16408                    }
16409                    removed.add(pa);
16410                }
16411            }
16412            if (removed != null) {
16413                for (int j=0; j<removed.size(); j++) {
16414                    PreferredActivity pa = removed.get(j);
16415                    pir.removeFilter(pa);
16416                }
16417                changed = true;
16418            }
16419        }
16420        return changed;
16421    }
16422
16423    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
16424    private void clearIntentFilterVerificationsLPw(int userId) {
16425        final int packageCount = mPackages.size();
16426        for (int i = 0; i < packageCount; i++) {
16427            PackageParser.Package pkg = mPackages.valueAt(i);
16428            clearIntentFilterVerificationsLPw(pkg.packageName, userId);
16429        }
16430    }
16431
16432    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
16433    void clearIntentFilterVerificationsLPw(String packageName, int userId) {
16434        if (userId == UserHandle.USER_ALL) {
16435            if (mSettings.removeIntentFilterVerificationLPw(packageName,
16436                    sUserManager.getUserIds())) {
16437                for (int oneUserId : sUserManager.getUserIds()) {
16438                    scheduleWritePackageRestrictionsLocked(oneUserId);
16439                }
16440            }
16441        } else {
16442            if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) {
16443                scheduleWritePackageRestrictionsLocked(userId);
16444            }
16445        }
16446    }
16447
16448    void clearDefaultBrowserIfNeeded(String packageName) {
16449        for (int oneUserId : sUserManager.getUserIds()) {
16450            String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId);
16451            if (TextUtils.isEmpty(defaultBrowserPackageName)) continue;
16452            if (packageName.equals(defaultBrowserPackageName)) {
16453                setDefaultBrowserPackageName(null, oneUserId);
16454            }
16455        }
16456    }
16457
16458    @Override
16459    public void resetApplicationPreferences(int userId) {
16460        mContext.enforceCallingOrSelfPermission(
16461                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
16462        // writer
16463        synchronized (mPackages) {
16464            final long identity = Binder.clearCallingIdentity();
16465            try {
16466                clearPackagePreferredActivitiesLPw(null, userId);
16467                mSettings.applyDefaultPreferredAppsLPw(this, userId);
16468                // TODO: We have to reset the default SMS and Phone. This requires
16469                // significant refactoring to keep all default apps in the package
16470                // manager (cleaner but more work) or have the services provide
16471                // callbacks to the package manager to request a default app reset.
16472                applyFactoryDefaultBrowserLPw(userId);
16473                clearIntentFilterVerificationsLPw(userId);
16474                primeDomainVerificationsLPw(userId);
16475                resetUserChangesToRuntimePermissionsAndFlagsLPw(userId);
16476                scheduleWritePackageRestrictionsLocked(userId);
16477            } finally {
16478                Binder.restoreCallingIdentity(identity);
16479            }
16480        }
16481    }
16482
16483    @Override
16484    public int getPreferredActivities(List<IntentFilter> outFilters,
16485            List<ComponentName> outActivities, String packageName) {
16486
16487        int num = 0;
16488        final int userId = UserHandle.getCallingUserId();
16489        // reader
16490        synchronized (mPackages) {
16491            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
16492            if (pir != null) {
16493                final Iterator<PreferredActivity> it = pir.filterIterator();
16494                while (it.hasNext()) {
16495                    final PreferredActivity pa = it.next();
16496                    if (packageName == null
16497                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
16498                                    && pa.mPref.mAlways)) {
16499                        if (outFilters != null) {
16500                            outFilters.add(new IntentFilter(pa));
16501                        }
16502                        if (outActivities != null) {
16503                            outActivities.add(pa.mPref.mComponent);
16504                        }
16505                    }
16506                }
16507            }
16508        }
16509
16510        return num;
16511    }
16512
16513    @Override
16514    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
16515            int userId) {
16516        int callingUid = Binder.getCallingUid();
16517        if (callingUid != Process.SYSTEM_UID) {
16518            throw new SecurityException(
16519                    "addPersistentPreferredActivity can only be run by the system");
16520        }
16521        if (filter.countActions() == 0) {
16522            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
16523            return;
16524        }
16525        synchronized (mPackages) {
16526            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
16527                    ":");
16528            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
16529            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
16530                    new PersistentPreferredActivity(filter, activity));
16531            scheduleWritePackageRestrictionsLocked(userId);
16532        }
16533    }
16534
16535    @Override
16536    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
16537        int callingUid = Binder.getCallingUid();
16538        if (callingUid != Process.SYSTEM_UID) {
16539            throw new SecurityException(
16540                    "clearPackagePersistentPreferredActivities can only be run by the system");
16541        }
16542        ArrayList<PersistentPreferredActivity> removed = null;
16543        boolean changed = false;
16544        synchronized (mPackages) {
16545            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
16546                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
16547                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
16548                        .valueAt(i);
16549                if (userId != thisUserId) {
16550                    continue;
16551                }
16552                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
16553                while (it.hasNext()) {
16554                    PersistentPreferredActivity ppa = it.next();
16555                    // Mark entry for removal only if it matches the package name.
16556                    if (ppa.mComponent.getPackageName().equals(packageName)) {
16557                        if (removed == null) {
16558                            removed = new ArrayList<PersistentPreferredActivity>();
16559                        }
16560                        removed.add(ppa);
16561                    }
16562                }
16563                if (removed != null) {
16564                    for (int j=0; j<removed.size(); j++) {
16565                        PersistentPreferredActivity ppa = removed.get(j);
16566                        ppir.removeFilter(ppa);
16567                    }
16568                    changed = true;
16569                }
16570            }
16571
16572            if (changed) {
16573                scheduleWritePackageRestrictionsLocked(userId);
16574            }
16575        }
16576    }
16577
16578    /**
16579     * Common machinery for picking apart a restored XML blob and passing
16580     * it to a caller-supplied functor to be applied to the running system.
16581     */
16582    private void restoreFromXml(XmlPullParser parser, int userId,
16583            String expectedStartTag, BlobXmlRestorer functor)
16584            throws IOException, XmlPullParserException {
16585        int type;
16586        while ((type = parser.next()) != XmlPullParser.START_TAG
16587                && type != XmlPullParser.END_DOCUMENT) {
16588        }
16589        if (type != XmlPullParser.START_TAG) {
16590            // oops didn't find a start tag?!
16591            if (DEBUG_BACKUP) {
16592                Slog.e(TAG, "Didn't find start tag during restore");
16593            }
16594            return;
16595        }
16596Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName());
16597        // this is supposed to be TAG_PREFERRED_BACKUP
16598        if (!expectedStartTag.equals(parser.getName())) {
16599            if (DEBUG_BACKUP) {
16600                Slog.e(TAG, "Found unexpected tag " + parser.getName());
16601            }
16602            return;
16603        }
16604
16605        // skip interfering stuff, then we're aligned with the backing implementation
16606        while ((type = parser.next()) == XmlPullParser.TEXT) { }
16607Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName());
16608        functor.apply(parser, userId);
16609    }
16610
16611    private interface BlobXmlRestorer {
16612        public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException;
16613    }
16614
16615    /**
16616     * Non-Binder method, support for the backup/restore mechanism: write the
16617     * full set of preferred activities in its canonical XML format.  Returns the
16618     * XML output as a byte array, or null if there is none.
16619     */
16620    @Override
16621    public byte[] getPreferredActivityBackup(int userId) {
16622        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
16623            throw new SecurityException("Only the system may call getPreferredActivityBackup()");
16624        }
16625
16626        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
16627        try {
16628            final XmlSerializer serializer = new FastXmlSerializer();
16629            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
16630            serializer.startDocument(null, true);
16631            serializer.startTag(null, TAG_PREFERRED_BACKUP);
16632
16633            synchronized (mPackages) {
16634                mSettings.writePreferredActivitiesLPr(serializer, userId, true);
16635            }
16636
16637            serializer.endTag(null, TAG_PREFERRED_BACKUP);
16638            serializer.endDocument();
16639            serializer.flush();
16640        } catch (Exception e) {
16641            if (DEBUG_BACKUP) {
16642                Slog.e(TAG, "Unable to write preferred activities for backup", e);
16643            }
16644            return null;
16645        }
16646
16647        return dataStream.toByteArray();
16648    }
16649
16650    @Override
16651    public void restorePreferredActivities(byte[] backup, int userId) {
16652        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
16653            throw new SecurityException("Only the system may call restorePreferredActivities()");
16654        }
16655
16656        try {
16657            final XmlPullParser parser = Xml.newPullParser();
16658            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
16659            restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP,
16660                    new BlobXmlRestorer() {
16661                        @Override
16662                        public void apply(XmlPullParser parser, int userId)
16663                                throws XmlPullParserException, IOException {
16664                            synchronized (mPackages) {
16665                                mSettings.readPreferredActivitiesLPw(parser, userId);
16666                            }
16667                        }
16668                    } );
16669        } catch (Exception e) {
16670            if (DEBUG_BACKUP) {
16671                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
16672            }
16673        }
16674    }
16675
16676    /**
16677     * Non-Binder method, support for the backup/restore mechanism: write the
16678     * default browser (etc) settings in its canonical XML format.  Returns the default
16679     * browser XML representation as a byte array, or null if there is none.
16680     */
16681    @Override
16682    public byte[] getDefaultAppsBackup(int userId) {
16683        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
16684            throw new SecurityException("Only the system may call getDefaultAppsBackup()");
16685        }
16686
16687        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
16688        try {
16689            final XmlSerializer serializer = new FastXmlSerializer();
16690            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
16691            serializer.startDocument(null, true);
16692            serializer.startTag(null, TAG_DEFAULT_APPS);
16693
16694            synchronized (mPackages) {
16695                mSettings.writeDefaultAppsLPr(serializer, userId);
16696            }
16697
16698            serializer.endTag(null, TAG_DEFAULT_APPS);
16699            serializer.endDocument();
16700            serializer.flush();
16701        } catch (Exception e) {
16702            if (DEBUG_BACKUP) {
16703                Slog.e(TAG, "Unable to write default apps for backup", e);
16704            }
16705            return null;
16706        }
16707
16708        return dataStream.toByteArray();
16709    }
16710
16711    @Override
16712    public void restoreDefaultApps(byte[] backup, int userId) {
16713        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
16714            throw new SecurityException("Only the system may call restoreDefaultApps()");
16715        }
16716
16717        try {
16718            final XmlPullParser parser = Xml.newPullParser();
16719            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
16720            restoreFromXml(parser, userId, TAG_DEFAULT_APPS,
16721                    new BlobXmlRestorer() {
16722                        @Override
16723                        public void apply(XmlPullParser parser, int userId)
16724                                throws XmlPullParserException, IOException {
16725                            synchronized (mPackages) {
16726                                mSettings.readDefaultAppsLPw(parser, userId);
16727                            }
16728                        }
16729                    } );
16730        } catch (Exception e) {
16731            if (DEBUG_BACKUP) {
16732                Slog.e(TAG, "Exception restoring default apps: " + e.getMessage());
16733            }
16734        }
16735    }
16736
16737    @Override
16738    public byte[] getIntentFilterVerificationBackup(int userId) {
16739        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
16740            throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()");
16741        }
16742
16743        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
16744        try {
16745            final XmlSerializer serializer = new FastXmlSerializer();
16746            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
16747            serializer.startDocument(null, true);
16748            serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION);
16749
16750            synchronized (mPackages) {
16751                mSettings.writeAllDomainVerificationsLPr(serializer, userId);
16752            }
16753
16754            serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION);
16755            serializer.endDocument();
16756            serializer.flush();
16757        } catch (Exception e) {
16758            if (DEBUG_BACKUP) {
16759                Slog.e(TAG, "Unable to write default apps for backup", e);
16760            }
16761            return null;
16762        }
16763
16764        return dataStream.toByteArray();
16765    }
16766
16767    @Override
16768    public void restoreIntentFilterVerification(byte[] backup, int userId) {
16769        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
16770            throw new SecurityException("Only the system may call restorePreferredActivities()");
16771        }
16772
16773        try {
16774            final XmlPullParser parser = Xml.newPullParser();
16775            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
16776            restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION,
16777                    new BlobXmlRestorer() {
16778                        @Override
16779                        public void apply(XmlPullParser parser, int userId)
16780                                throws XmlPullParserException, IOException {
16781                            synchronized (mPackages) {
16782                                mSettings.readAllDomainVerificationsLPr(parser, userId);
16783                                mSettings.writeLPr();
16784                            }
16785                        }
16786                    } );
16787        } catch (Exception e) {
16788            if (DEBUG_BACKUP) {
16789                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
16790            }
16791        }
16792    }
16793
16794    @Override
16795    public byte[] getPermissionGrantBackup(int userId) {
16796        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
16797            throw new SecurityException("Only the system may call getPermissionGrantBackup()");
16798        }
16799
16800        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
16801        try {
16802            final XmlSerializer serializer = new FastXmlSerializer();
16803            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
16804            serializer.startDocument(null, true);
16805            serializer.startTag(null, TAG_PERMISSION_BACKUP);
16806
16807            synchronized (mPackages) {
16808                serializeRuntimePermissionGrantsLPr(serializer, userId);
16809            }
16810
16811            serializer.endTag(null, TAG_PERMISSION_BACKUP);
16812            serializer.endDocument();
16813            serializer.flush();
16814        } catch (Exception e) {
16815            if (DEBUG_BACKUP) {
16816                Slog.e(TAG, "Unable to write default apps for backup", e);
16817            }
16818            return null;
16819        }
16820
16821        return dataStream.toByteArray();
16822    }
16823
16824    @Override
16825    public void restorePermissionGrants(byte[] backup, int userId) {
16826        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
16827            throw new SecurityException("Only the system may call restorePermissionGrants()");
16828        }
16829
16830        try {
16831            final XmlPullParser parser = Xml.newPullParser();
16832            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
16833            restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP,
16834                    new BlobXmlRestorer() {
16835                        @Override
16836                        public void apply(XmlPullParser parser, int userId)
16837                                throws XmlPullParserException, IOException {
16838                            synchronized (mPackages) {
16839                                processRestoredPermissionGrantsLPr(parser, userId);
16840                            }
16841                        }
16842                    } );
16843        } catch (Exception e) {
16844            if (DEBUG_BACKUP) {
16845                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
16846            }
16847        }
16848    }
16849
16850    private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId)
16851            throws IOException {
16852        serializer.startTag(null, TAG_ALL_GRANTS);
16853
16854        final int N = mSettings.mPackages.size();
16855        for (int i = 0; i < N; i++) {
16856            final PackageSetting ps = mSettings.mPackages.valueAt(i);
16857            boolean pkgGrantsKnown = false;
16858
16859            PermissionsState packagePerms = ps.getPermissionsState();
16860
16861            for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) {
16862                final int grantFlags = state.getFlags();
16863                // only look at grants that are not system/policy fixed
16864                if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) {
16865                    final boolean isGranted = state.isGranted();
16866                    // And only back up the user-twiddled state bits
16867                    if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) {
16868                        final String packageName = mSettings.mPackages.keyAt(i);
16869                        if (!pkgGrantsKnown) {
16870                            serializer.startTag(null, TAG_GRANT);
16871                            serializer.attribute(null, ATTR_PACKAGE_NAME, packageName);
16872                            pkgGrantsKnown = true;
16873                        }
16874
16875                        final boolean userSet =
16876                                (grantFlags & FLAG_PERMISSION_USER_SET) != 0;
16877                        final boolean userFixed =
16878                                (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0;
16879                        final boolean revoke =
16880                                (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0;
16881
16882                        serializer.startTag(null, TAG_PERMISSION);
16883                        serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName());
16884                        if (isGranted) {
16885                            serializer.attribute(null, ATTR_IS_GRANTED, "true");
16886                        }
16887                        if (userSet) {
16888                            serializer.attribute(null, ATTR_USER_SET, "true");
16889                        }
16890                        if (userFixed) {
16891                            serializer.attribute(null, ATTR_USER_FIXED, "true");
16892                        }
16893                        if (revoke) {
16894                            serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true");
16895                        }
16896                        serializer.endTag(null, TAG_PERMISSION);
16897                    }
16898                }
16899            }
16900
16901            if (pkgGrantsKnown) {
16902                serializer.endTag(null, TAG_GRANT);
16903            }
16904        }
16905
16906        serializer.endTag(null, TAG_ALL_GRANTS);
16907    }
16908
16909    private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId)
16910            throws XmlPullParserException, IOException {
16911        String pkgName = null;
16912        int outerDepth = parser.getDepth();
16913        int type;
16914        while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
16915                && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
16916            if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
16917                continue;
16918            }
16919
16920            final String tagName = parser.getName();
16921            if (tagName.equals(TAG_GRANT)) {
16922                pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME);
16923                if (DEBUG_BACKUP) {
16924                    Slog.v(TAG, "+++ Restoring grants for package " + pkgName);
16925                }
16926            } else if (tagName.equals(TAG_PERMISSION)) {
16927
16928                final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED));
16929                final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME);
16930
16931                int newFlagSet = 0;
16932                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) {
16933                    newFlagSet |= FLAG_PERMISSION_USER_SET;
16934                }
16935                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) {
16936                    newFlagSet |= FLAG_PERMISSION_USER_FIXED;
16937                }
16938                if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) {
16939                    newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE;
16940                }
16941                if (DEBUG_BACKUP) {
16942                    Slog.v(TAG, "  + Restoring grant: pkg=" + pkgName + " perm=" + permName
16943                            + " granted=" + isGranted + " bits=0x" + Integer.toHexString(newFlagSet));
16944                }
16945                final PackageSetting ps = mSettings.mPackages.get(pkgName);
16946                if (ps != null) {
16947                    // Already installed so we apply the grant immediately
16948                    if (DEBUG_BACKUP) {
16949                        Slog.v(TAG, "        + already installed; applying");
16950                    }
16951                    PermissionsState perms = ps.getPermissionsState();
16952                    BasePermission bp = mSettings.mPermissions.get(permName);
16953                    if (bp != null) {
16954                        if (isGranted) {
16955                            perms.grantRuntimePermission(bp, userId);
16956                        }
16957                        if (newFlagSet != 0) {
16958                            perms.updatePermissionFlags(bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet);
16959                        }
16960                    }
16961                } else {
16962                    // Need to wait for post-restore install to apply the grant
16963                    if (DEBUG_BACKUP) {
16964                        Slog.v(TAG, "        - not yet installed; saving for later");
16965                    }
16966                    mSettings.processRestoredPermissionGrantLPr(pkgName, permName,
16967                            isGranted, newFlagSet, userId);
16968                }
16969            } else {
16970                PackageManagerService.reportSettingsProblem(Log.WARN,
16971                        "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName);
16972                XmlUtils.skipCurrentTag(parser);
16973            }
16974        }
16975
16976        scheduleWriteSettingsLocked();
16977        mSettings.writeRuntimePermissionsForUserLPr(userId, false);
16978    }
16979
16980    @Override
16981    public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
16982            int sourceUserId, int targetUserId, int flags) {
16983        mContext.enforceCallingOrSelfPermission(
16984                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
16985        int callingUid = Binder.getCallingUid();
16986        enforceOwnerRights(ownerPackage, callingUid);
16987        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
16988        if (intentFilter.countActions() == 0) {
16989            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
16990            return;
16991        }
16992        synchronized (mPackages) {
16993            CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter,
16994                    ownerPackage, targetUserId, flags);
16995            CrossProfileIntentResolver resolver =
16996                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
16997            ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter);
16998            // We have all those whose filter is equal. Now checking if the rest is equal as well.
16999            if (existing != null) {
17000                int size = existing.size();
17001                for (int i = 0; i < size; i++) {
17002                    if (newFilter.equalsIgnoreFilter(existing.get(i))) {
17003                        return;
17004                    }
17005                }
17006            }
17007            resolver.addFilter(newFilter);
17008            scheduleWritePackageRestrictionsLocked(sourceUserId);
17009        }
17010    }
17011
17012    @Override
17013    public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) {
17014        mContext.enforceCallingOrSelfPermission(
17015                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
17016        int callingUid = Binder.getCallingUid();
17017        enforceOwnerRights(ownerPackage, callingUid);
17018        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
17019        synchronized (mPackages) {
17020            CrossProfileIntentResolver resolver =
17021                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
17022            ArraySet<CrossProfileIntentFilter> set =
17023                    new ArraySet<CrossProfileIntentFilter>(resolver.filterSet());
17024            for (CrossProfileIntentFilter filter : set) {
17025                if (filter.getOwnerPackage().equals(ownerPackage)) {
17026                    resolver.removeFilter(filter);
17027                }
17028            }
17029            scheduleWritePackageRestrictionsLocked(sourceUserId);
17030        }
17031    }
17032
17033    // Enforcing that callingUid is owning pkg on userId
17034    private void enforceOwnerRights(String pkg, int callingUid) {
17035        // The system owns everything.
17036        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
17037            return;
17038        }
17039        int callingUserId = UserHandle.getUserId(callingUid);
17040        PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
17041        if (pi == null) {
17042            throw new IllegalArgumentException("Unknown package " + pkg + " on user "
17043                    + callingUserId);
17044        }
17045        if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
17046            throw new SecurityException("Calling uid " + callingUid
17047                    + " does not own package " + pkg);
17048        }
17049    }
17050
17051    @Override
17052    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
17053        return getHomeActivitiesAsUser(allHomeCandidates, UserHandle.getCallingUserId());
17054    }
17055
17056    private Intent getHomeIntent() {
17057        Intent intent = new Intent(Intent.ACTION_MAIN);
17058        intent.addCategory(Intent.CATEGORY_HOME);
17059        return intent;
17060    }
17061
17062    private IntentFilter getHomeFilter() {
17063        IntentFilter filter = new IntentFilter(Intent.ACTION_MAIN);
17064        filter.addCategory(Intent.CATEGORY_HOME);
17065        filter.addCategory(Intent.CATEGORY_DEFAULT);
17066        return filter;
17067    }
17068
17069    ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
17070            int userId) {
17071        Intent intent  = getHomeIntent();
17072        List<ResolveInfo> list = queryIntentActivitiesInternal(intent, null,
17073                PackageManager.GET_META_DATA, userId);
17074        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
17075                true, false, false, userId);
17076
17077        allHomeCandidates.clear();
17078        if (list != null) {
17079            for (ResolveInfo ri : list) {
17080                allHomeCandidates.add(ri);
17081            }
17082        }
17083        return (preferred == null || preferred.activityInfo == null)
17084                ? null
17085                : new ComponentName(preferred.activityInfo.packageName,
17086                        preferred.activityInfo.name);
17087    }
17088
17089    @Override
17090    public void setHomeActivity(ComponentName comp, int userId) {
17091        ArrayList<ResolveInfo> homeActivities = new ArrayList<>();
17092        getHomeActivitiesAsUser(homeActivities, userId);
17093
17094        boolean found = false;
17095
17096        final int size = homeActivities.size();
17097        final ComponentName[] set = new ComponentName[size];
17098        for (int i = 0; i < size; i++) {
17099            final ResolveInfo candidate = homeActivities.get(i);
17100            final ActivityInfo info = candidate.activityInfo;
17101            final ComponentName activityName = new ComponentName(info.packageName, info.name);
17102            set[i] = activityName;
17103            if (!found && activityName.equals(comp)) {
17104                found = true;
17105            }
17106        }
17107        if (!found) {
17108            throw new IllegalArgumentException("Component " + comp + " cannot be home on user "
17109                    + userId);
17110        }
17111        replacePreferredActivity(getHomeFilter(), IntentFilter.MATCH_CATEGORY_EMPTY,
17112                set, comp, userId);
17113    }
17114
17115    private @Nullable String getSetupWizardPackageName() {
17116        final Intent intent = new Intent(Intent.ACTION_MAIN);
17117        intent.addCategory(Intent.CATEGORY_SETUP_WIZARD);
17118
17119        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
17120                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
17121                        | MATCH_DISABLED_COMPONENTS,
17122                UserHandle.myUserId());
17123        if (matches.size() == 1) {
17124            return matches.get(0).getComponentInfo().packageName;
17125        } else {
17126            Slog.e(TAG, "There should probably be exactly one setup wizard; found " + matches.size()
17127                    + ": matches=" + matches);
17128            return null;
17129        }
17130    }
17131
17132    @Override
17133    public void setApplicationEnabledSetting(String appPackageName,
17134            int newState, int flags, int userId, String callingPackage) {
17135        if (!sUserManager.exists(userId)) return;
17136        if (callingPackage == null) {
17137            callingPackage = Integer.toString(Binder.getCallingUid());
17138        }
17139        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
17140    }
17141
17142    @Override
17143    public void setComponentEnabledSetting(ComponentName componentName,
17144            int newState, int flags, int userId) {
17145        if (!sUserManager.exists(userId)) return;
17146        setEnabledSetting(componentName.getPackageName(),
17147                componentName.getClassName(), newState, flags, userId, null);
17148    }
17149
17150    private void setEnabledSetting(final String packageName, String className, int newState,
17151            final int flags, int userId, String callingPackage) {
17152        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
17153              || newState == COMPONENT_ENABLED_STATE_ENABLED
17154              || newState == COMPONENT_ENABLED_STATE_DISABLED
17155              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
17156              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
17157            throw new IllegalArgumentException("Invalid new component state: "
17158                    + newState);
17159        }
17160        PackageSetting pkgSetting;
17161        final int uid = Binder.getCallingUid();
17162        final int permission;
17163        if (uid == Process.SYSTEM_UID) {
17164            permission = PackageManager.PERMISSION_GRANTED;
17165        } else {
17166            permission = mContext.checkCallingOrSelfPermission(
17167                    android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
17168        }
17169        enforceCrossUserPermission(uid, userId,
17170                false /* requireFullPermission */, true /* checkShell */, "set enabled");
17171        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
17172        boolean sendNow = false;
17173        boolean isApp = (className == null);
17174        String componentName = isApp ? packageName : className;
17175        int packageUid = -1;
17176        ArrayList<String> components;
17177
17178        // writer
17179        synchronized (mPackages) {
17180            pkgSetting = mSettings.mPackages.get(packageName);
17181            if (pkgSetting == null) {
17182                if (className == null) {
17183                    throw new IllegalArgumentException("Unknown package: " + packageName);
17184                }
17185                throw new IllegalArgumentException(
17186                        "Unknown component: " + packageName + "/" + className);
17187            }
17188            // Allow root and verify that userId is not being specified by a different user
17189            if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) {
17190                throw new SecurityException(
17191                        "Permission Denial: attempt to change component state from pid="
17192                        + Binder.getCallingPid()
17193                        + ", uid=" + uid + ", package uid=" + pkgSetting.appId);
17194            }
17195            if (className == null) {
17196                // We're dealing with an application/package level state change
17197                if (pkgSetting.getEnabled(userId) == newState) {
17198                    // Nothing to do
17199                    return;
17200                }
17201                if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
17202                    || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
17203                    // Don't care about who enables an app.
17204                    callingPackage = null;
17205                }
17206                pkgSetting.setEnabled(newState, userId, callingPackage);
17207                // pkgSetting.pkg.mSetEnabled = newState;
17208            } else {
17209                // We're dealing with a component level state change
17210                // First, verify that this is a valid class name.
17211                PackageParser.Package pkg = pkgSetting.pkg;
17212                if (pkg == null || !pkg.hasComponentClassName(className)) {
17213                    if (pkg != null &&
17214                            pkg.applicationInfo.targetSdkVersion >=
17215                                    Build.VERSION_CODES.JELLY_BEAN) {
17216                        throw new IllegalArgumentException("Component class " + className
17217                                + " does not exist in " + packageName);
17218                    } else {
17219                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
17220                                + className + " does not exist in " + packageName);
17221                    }
17222                }
17223                switch (newState) {
17224                case COMPONENT_ENABLED_STATE_ENABLED:
17225                    if (!pkgSetting.enableComponentLPw(className, userId)) {
17226                        return;
17227                    }
17228                    break;
17229                case COMPONENT_ENABLED_STATE_DISABLED:
17230                    if (!pkgSetting.disableComponentLPw(className, userId)) {
17231                        return;
17232                    }
17233                    break;
17234                case COMPONENT_ENABLED_STATE_DEFAULT:
17235                    if (!pkgSetting.restoreComponentLPw(className, userId)) {
17236                        return;
17237                    }
17238                    break;
17239                default:
17240                    Slog.e(TAG, "Invalid new component state: " + newState);
17241                    return;
17242                }
17243            }
17244            scheduleWritePackageRestrictionsLocked(userId);
17245            components = mPendingBroadcasts.get(userId, packageName);
17246            final boolean newPackage = components == null;
17247            if (newPackage) {
17248                components = new ArrayList<String>();
17249            }
17250            if (!components.contains(componentName)) {
17251                components.add(componentName);
17252            }
17253            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
17254                sendNow = true;
17255                // Purge entry from pending broadcast list if another one exists already
17256                // since we are sending one right away.
17257                mPendingBroadcasts.remove(userId, packageName);
17258            } else {
17259                if (newPackage) {
17260                    mPendingBroadcasts.put(userId, packageName, components);
17261                }
17262                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
17263                    // Schedule a message
17264                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
17265                }
17266            }
17267        }
17268
17269        long callingId = Binder.clearCallingIdentity();
17270        try {
17271            if (sendNow) {
17272                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
17273                sendPackageChangedBroadcast(packageName,
17274                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
17275            }
17276        } finally {
17277            Binder.restoreCallingIdentity(callingId);
17278        }
17279    }
17280
17281    @Override
17282    public void flushPackageRestrictionsAsUser(int userId) {
17283        if (!sUserManager.exists(userId)) {
17284            return;
17285        }
17286        enforceCrossUserPermission(Binder.getCallingUid(), userId, false /* requireFullPermission*/,
17287                false /* checkShell */, "flushPackageRestrictions");
17288        synchronized (mPackages) {
17289            mSettings.writePackageRestrictionsLPr(userId);
17290            mDirtyUsers.remove(userId);
17291            if (mDirtyUsers.isEmpty()) {
17292                mHandler.removeMessages(WRITE_PACKAGE_RESTRICTIONS);
17293            }
17294        }
17295    }
17296
17297    private void sendPackageChangedBroadcast(String packageName,
17298            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
17299        if (DEBUG_INSTALL)
17300            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
17301                    + componentNames);
17302        Bundle extras = new Bundle(4);
17303        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
17304        String nameList[] = new String[componentNames.size()];
17305        componentNames.toArray(nameList);
17306        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
17307        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
17308        extras.putInt(Intent.EXTRA_UID, packageUid);
17309        // If this is not reporting a change of the overall package, then only send it
17310        // to registered receivers.  We don't want to launch a swath of apps for every
17311        // little component state change.
17312        final int flags = !componentNames.contains(packageName)
17313                ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0;
17314        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, flags, null, null,
17315                new int[] {UserHandle.getUserId(packageUid)});
17316    }
17317
17318    @Override
17319    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
17320        if (!sUserManager.exists(userId)) return;
17321        final int uid = Binder.getCallingUid();
17322        final int permission = mContext.checkCallingOrSelfPermission(
17323                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
17324        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
17325        enforceCrossUserPermission(uid, userId,
17326                true /* requireFullPermission */, true /* checkShell */, "stop package");
17327        // writer
17328        synchronized (mPackages) {
17329            if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped,
17330                    allowedByPermission, uid, userId)) {
17331                scheduleWritePackageRestrictionsLocked(userId);
17332            }
17333        }
17334    }
17335
17336    @Override
17337    public String getInstallerPackageName(String packageName) {
17338        // reader
17339        synchronized (mPackages) {
17340            return mSettings.getInstallerPackageNameLPr(packageName);
17341        }
17342    }
17343
17344    @Override
17345    public int getApplicationEnabledSetting(String packageName, int userId) {
17346        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
17347        int uid = Binder.getCallingUid();
17348        enforceCrossUserPermission(uid, userId,
17349                false /* requireFullPermission */, false /* checkShell */, "get enabled");
17350        // reader
17351        synchronized (mPackages) {
17352            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
17353        }
17354    }
17355
17356    @Override
17357    public int getComponentEnabledSetting(ComponentName componentName, int userId) {
17358        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
17359        int uid = Binder.getCallingUid();
17360        enforceCrossUserPermission(uid, userId,
17361                false /* requireFullPermission */, false /* checkShell */, "get component enabled");
17362        // reader
17363        synchronized (mPackages) {
17364            return mSettings.getComponentEnabledSettingLPr(componentName, userId);
17365        }
17366    }
17367
17368    @Override
17369    public void enterSafeMode() {
17370        enforceSystemOrRoot("Only the system can request entering safe mode");
17371
17372        if (!mSystemReady) {
17373            mSafeMode = true;
17374        }
17375    }
17376
17377    @Override
17378    public void systemReady() {
17379        mSystemReady = true;
17380
17381        // Read the compatibilty setting when the system is ready.
17382        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
17383                mContext.getContentResolver(),
17384                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
17385        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
17386        if (DEBUG_SETTINGS) {
17387            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
17388        }
17389
17390        int[] grantPermissionsUserIds = EMPTY_INT_ARRAY;
17391
17392        synchronized (mPackages) {
17393            // Verify that all of the preferred activity components actually
17394            // exist.  It is possible for applications to be updated and at
17395            // that point remove a previously declared activity component that
17396            // had been set as a preferred activity.  We try to clean this up
17397            // the next time we encounter that preferred activity, but it is
17398            // possible for the user flow to never be able to return to that
17399            // situation so here we do a sanity check to make sure we haven't
17400            // left any junk around.
17401            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
17402            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
17403                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
17404                removed.clear();
17405                for (PreferredActivity pa : pir.filterSet()) {
17406                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
17407                        removed.add(pa);
17408                    }
17409                }
17410                if (removed.size() > 0) {
17411                    for (int r=0; r<removed.size(); r++) {
17412                        PreferredActivity pa = removed.get(r);
17413                        Slog.w(TAG, "Removing dangling preferred activity: "
17414                                + pa.mPref.mComponent);
17415                        pir.removeFilter(pa);
17416                    }
17417                    mSettings.writePackageRestrictionsLPr(
17418                            mSettings.mPreferredActivities.keyAt(i));
17419                }
17420            }
17421
17422            for (int userId : UserManagerService.getInstance().getUserIds()) {
17423                if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) {
17424                    grantPermissionsUserIds = ArrayUtils.appendInt(
17425                            grantPermissionsUserIds, userId);
17426                }
17427            }
17428        }
17429        sUserManager.systemReady();
17430
17431        // If we upgraded grant all default permissions before kicking off.
17432        for (int userId : grantPermissionsUserIds) {
17433            mDefaultPermissionPolicy.grantDefaultPermissions(userId);
17434        }
17435
17436        // Kick off any messages waiting for system ready
17437        if (mPostSystemReadyMessages != null) {
17438            for (Message msg : mPostSystemReadyMessages) {
17439                msg.sendToTarget();
17440            }
17441            mPostSystemReadyMessages = null;
17442        }
17443
17444        // Watch for external volumes that come and go over time
17445        final StorageManager storage = mContext.getSystemService(StorageManager.class);
17446        storage.registerListener(mStorageListener);
17447
17448        mInstallerService.systemReady();
17449        mPackageDexOptimizer.systemReady();
17450
17451        MountServiceInternal mountServiceInternal = LocalServices.getService(
17452                MountServiceInternal.class);
17453        mountServiceInternal.addExternalStoragePolicy(
17454                new MountServiceInternal.ExternalStorageMountPolicy() {
17455            @Override
17456            public int getMountMode(int uid, String packageName) {
17457                if (Process.isIsolated(uid)) {
17458                    return Zygote.MOUNT_EXTERNAL_NONE;
17459                }
17460                if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) {
17461                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
17462                }
17463                if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
17464                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
17465                }
17466                if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
17467                    return Zygote.MOUNT_EXTERNAL_READ;
17468                }
17469                return Zygote.MOUNT_EXTERNAL_WRITE;
17470            }
17471
17472            @Override
17473            public boolean hasExternalStorage(int uid, String packageName) {
17474                return true;
17475            }
17476        });
17477
17478        // Now that we're mostly running, clean up stale users and apps
17479        reconcileUsers(StorageManager.UUID_PRIVATE_INTERNAL);
17480        reconcileApps(StorageManager.UUID_PRIVATE_INTERNAL);
17481    }
17482
17483    @Override
17484    public boolean isSafeMode() {
17485        return mSafeMode;
17486    }
17487
17488    @Override
17489    public boolean hasSystemUidErrors() {
17490        return mHasSystemUidErrors;
17491    }
17492
17493    static String arrayToString(int[] array) {
17494        StringBuffer buf = new StringBuffer(128);
17495        buf.append('[');
17496        if (array != null) {
17497            for (int i=0; i<array.length; i++) {
17498                if (i > 0) buf.append(", ");
17499                buf.append(array[i]);
17500            }
17501        }
17502        buf.append(']');
17503        return buf.toString();
17504    }
17505
17506    static class DumpState {
17507        public static final int DUMP_LIBS = 1 << 0;
17508        public static final int DUMP_FEATURES = 1 << 1;
17509        public static final int DUMP_ACTIVITY_RESOLVERS = 1 << 2;
17510        public static final int DUMP_SERVICE_RESOLVERS = 1 << 3;
17511        public static final int DUMP_RECEIVER_RESOLVERS = 1 << 4;
17512        public static final int DUMP_CONTENT_RESOLVERS = 1 << 5;
17513        public static final int DUMP_PERMISSIONS = 1 << 6;
17514        public static final int DUMP_PACKAGES = 1 << 7;
17515        public static final int DUMP_SHARED_USERS = 1 << 8;
17516        public static final int DUMP_MESSAGES = 1 << 9;
17517        public static final int DUMP_PROVIDERS = 1 << 10;
17518        public static final int DUMP_VERIFIERS = 1 << 11;
17519        public static final int DUMP_PREFERRED = 1 << 12;
17520        public static final int DUMP_PREFERRED_XML = 1 << 13;
17521        public static final int DUMP_KEYSETS = 1 << 14;
17522        public static final int DUMP_VERSION = 1 << 15;
17523        public static final int DUMP_INSTALLS = 1 << 16;
17524        public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 17;
17525        public static final int DUMP_DOMAIN_PREFERRED = 1 << 18;
17526        public static final int DUMP_FROZEN = 1 << 19;
17527
17528        public static final int OPTION_SHOW_FILTERS = 1 << 0;
17529
17530        private int mTypes;
17531
17532        private int mOptions;
17533
17534        private boolean mTitlePrinted;
17535
17536        private SharedUserSetting mSharedUser;
17537
17538        public boolean isDumping(int type) {
17539            if (mTypes == 0 && type != DUMP_PREFERRED_XML) {
17540                return true;
17541            }
17542
17543            return (mTypes & type) != 0;
17544        }
17545
17546        public void setDump(int type) {
17547            mTypes |= type;
17548        }
17549
17550        public boolean isOptionEnabled(int option) {
17551            return (mOptions & option) != 0;
17552        }
17553
17554        public void setOptionEnabled(int option) {
17555            mOptions |= option;
17556        }
17557
17558        public boolean onTitlePrinted() {
17559            final boolean printed = mTitlePrinted;
17560            mTitlePrinted = true;
17561            return printed;
17562        }
17563
17564        public boolean getTitlePrinted() {
17565            return mTitlePrinted;
17566        }
17567
17568        public void setTitlePrinted(boolean enabled) {
17569            mTitlePrinted = enabled;
17570        }
17571
17572        public SharedUserSetting getSharedUser() {
17573            return mSharedUser;
17574        }
17575
17576        public void setSharedUser(SharedUserSetting user) {
17577            mSharedUser = user;
17578        }
17579    }
17580
17581    @Override
17582    public void onShellCommand(FileDescriptor in, FileDescriptor out,
17583            FileDescriptor err, String[] args, ResultReceiver resultReceiver) {
17584        (new PackageManagerShellCommand(this)).exec(
17585                this, in, out, err, args, resultReceiver);
17586    }
17587
17588    @Override
17589    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
17590        if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
17591                != PackageManager.PERMISSION_GRANTED) {
17592            pw.println("Permission Denial: can't dump ActivityManager from from pid="
17593                    + Binder.getCallingPid()
17594                    + ", uid=" + Binder.getCallingUid()
17595                    + " without permission "
17596                    + android.Manifest.permission.DUMP);
17597            return;
17598        }
17599
17600        DumpState dumpState = new DumpState();
17601        boolean fullPreferred = false;
17602        boolean checkin = false;
17603
17604        String packageName = null;
17605        ArraySet<String> permissionNames = null;
17606
17607        int opti = 0;
17608        while (opti < args.length) {
17609            String opt = args[opti];
17610            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
17611                break;
17612            }
17613            opti++;
17614
17615            if ("-a".equals(opt)) {
17616                // Right now we only know how to print all.
17617            } else if ("-h".equals(opt)) {
17618                pw.println("Package manager dump options:");
17619                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
17620                pw.println("    --checkin: dump for a checkin");
17621                pw.println("    -f: print details of intent filters");
17622                pw.println("    -h: print this help");
17623                pw.println("  cmd may be one of:");
17624                pw.println("    l[ibraries]: list known shared libraries");
17625                pw.println("    f[eatures]: list device features");
17626                pw.println("    k[eysets]: print known keysets");
17627                pw.println("    r[esolvers] [activity|service|receiver|content]: dump intent resolvers");
17628                pw.println("    perm[issions]: dump permissions");
17629                pw.println("    permission [name ...]: dump declaration and use of given permission");
17630                pw.println("    pref[erred]: print preferred package settings");
17631                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
17632                pw.println("    prov[iders]: dump content providers");
17633                pw.println("    p[ackages]: dump installed packages");
17634                pw.println("    s[hared-users]: dump shared user IDs");
17635                pw.println("    m[essages]: print collected runtime messages");
17636                pw.println("    v[erifiers]: print package verifier info");
17637                pw.println("    d[omain-preferred-apps]: print domains preferred apps");
17638                pw.println("    i[ntent-filter-verifiers]|ifv: print intent filter verifier info");
17639                pw.println("    version: print database version info");
17640                pw.println("    write: write current settings now");
17641                pw.println("    installs: details about install sessions");
17642                pw.println("    check-permission <permission> <package> [<user>]: does pkg hold perm?");
17643                pw.println("    <package.name>: info about given package");
17644                return;
17645            } else if ("--checkin".equals(opt)) {
17646                checkin = true;
17647            } else if ("-f".equals(opt)) {
17648                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
17649            } else {
17650                pw.println("Unknown argument: " + opt + "; use -h for help");
17651            }
17652        }
17653
17654        // Is the caller requesting to dump a particular piece of data?
17655        if (opti < args.length) {
17656            String cmd = args[opti];
17657            opti++;
17658            // Is this a package name?
17659            if ("android".equals(cmd) || cmd.contains(".")) {
17660                packageName = cmd;
17661                // When dumping a single package, we always dump all of its
17662                // filter information since the amount of data will be reasonable.
17663                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
17664            } else if ("check-permission".equals(cmd)) {
17665                if (opti >= args.length) {
17666                    pw.println("Error: check-permission missing permission argument");
17667                    return;
17668                }
17669                String perm = args[opti];
17670                opti++;
17671                if (opti >= args.length) {
17672                    pw.println("Error: check-permission missing package argument");
17673                    return;
17674                }
17675                String pkg = args[opti];
17676                opti++;
17677                int user = UserHandle.getUserId(Binder.getCallingUid());
17678                if (opti < args.length) {
17679                    try {
17680                        user = Integer.parseInt(args[opti]);
17681                    } catch (NumberFormatException e) {
17682                        pw.println("Error: check-permission user argument is not a number: "
17683                                + args[opti]);
17684                        return;
17685                    }
17686                }
17687                pw.println(checkPermission(perm, pkg, user));
17688                return;
17689            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
17690                dumpState.setDump(DumpState.DUMP_LIBS);
17691            } else if ("f".equals(cmd) || "features".equals(cmd)) {
17692                dumpState.setDump(DumpState.DUMP_FEATURES);
17693            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
17694                if (opti >= args.length) {
17695                    dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS
17696                            | DumpState.DUMP_SERVICE_RESOLVERS
17697                            | DumpState.DUMP_RECEIVER_RESOLVERS
17698                            | DumpState.DUMP_CONTENT_RESOLVERS);
17699                } else {
17700                    while (opti < args.length) {
17701                        String name = args[opti];
17702                        if ("a".equals(name) || "activity".equals(name)) {
17703                            dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS);
17704                        } else if ("s".equals(name) || "service".equals(name)) {
17705                            dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS);
17706                        } else if ("r".equals(name) || "receiver".equals(name)) {
17707                            dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS);
17708                        } else if ("c".equals(name) || "content".equals(name)) {
17709                            dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS);
17710                        } else {
17711                            pw.println("Error: unknown resolver table type: " + name);
17712                            return;
17713                        }
17714                        opti++;
17715                    }
17716                }
17717            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
17718                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
17719            } else if ("permission".equals(cmd)) {
17720                if (opti >= args.length) {
17721                    pw.println("Error: permission requires permission name");
17722                    return;
17723                }
17724                permissionNames = new ArraySet<>();
17725                while (opti < args.length) {
17726                    permissionNames.add(args[opti]);
17727                    opti++;
17728                }
17729                dumpState.setDump(DumpState.DUMP_PERMISSIONS
17730                        | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS);
17731            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
17732                dumpState.setDump(DumpState.DUMP_PREFERRED);
17733            } else if ("preferred-xml".equals(cmd)) {
17734                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
17735                if (opti < args.length && "--full".equals(args[opti])) {
17736                    fullPreferred = true;
17737                    opti++;
17738                }
17739            } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) {
17740                dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED);
17741            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
17742                dumpState.setDump(DumpState.DUMP_PACKAGES);
17743            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
17744                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
17745            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
17746                dumpState.setDump(DumpState.DUMP_PROVIDERS);
17747            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
17748                dumpState.setDump(DumpState.DUMP_MESSAGES);
17749            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
17750                dumpState.setDump(DumpState.DUMP_VERIFIERS);
17751            } else if ("i".equals(cmd) || "ifv".equals(cmd)
17752                    || "intent-filter-verifiers".equals(cmd)) {
17753                dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS);
17754            } else if ("version".equals(cmd)) {
17755                dumpState.setDump(DumpState.DUMP_VERSION);
17756            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
17757                dumpState.setDump(DumpState.DUMP_KEYSETS);
17758            } else if ("installs".equals(cmd)) {
17759                dumpState.setDump(DumpState.DUMP_INSTALLS);
17760            } else if ("frozen".equals(cmd)) {
17761                dumpState.setDump(DumpState.DUMP_FROZEN);
17762            } else if ("write".equals(cmd)) {
17763                synchronized (mPackages) {
17764                    mSettings.writeLPr();
17765                    pw.println("Settings written.");
17766                    return;
17767                }
17768            }
17769        }
17770
17771        if (checkin) {
17772            pw.println("vers,1");
17773        }
17774
17775        // reader
17776        synchronized (mPackages) {
17777            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
17778                if (!checkin) {
17779                    if (dumpState.onTitlePrinted())
17780                        pw.println();
17781                    pw.println("Database versions:");
17782                    mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, "  "));
17783                }
17784            }
17785
17786            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
17787                if (!checkin) {
17788                    if (dumpState.onTitlePrinted())
17789                        pw.println();
17790                    pw.println("Verifiers:");
17791                    pw.print("  Required: ");
17792                    pw.print(mRequiredVerifierPackage);
17793                    pw.print(" (uid=");
17794                    pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
17795                            UserHandle.USER_SYSTEM));
17796                    pw.println(")");
17797                } else if (mRequiredVerifierPackage != null) {
17798                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
17799                    pw.print(",");
17800                    pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
17801                            UserHandle.USER_SYSTEM));
17802                }
17803            }
17804
17805            if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) &&
17806                    packageName == null) {
17807                if (mIntentFilterVerifierComponent != null) {
17808                    String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
17809                    if (!checkin) {
17810                        if (dumpState.onTitlePrinted())
17811                            pw.println();
17812                        pw.println("Intent Filter Verifier:");
17813                        pw.print("  Using: ");
17814                        pw.print(verifierPackageName);
17815                        pw.print(" (uid=");
17816                        pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
17817                                UserHandle.USER_SYSTEM));
17818                        pw.println(")");
17819                    } else if (verifierPackageName != null) {
17820                        pw.print("ifv,"); pw.print(verifierPackageName);
17821                        pw.print(",");
17822                        pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
17823                                UserHandle.USER_SYSTEM));
17824                    }
17825                } else {
17826                    pw.println();
17827                    pw.println("No Intent Filter Verifier available!");
17828                }
17829            }
17830
17831            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
17832                boolean printedHeader = false;
17833                final Iterator<String> it = mSharedLibraries.keySet().iterator();
17834                while (it.hasNext()) {
17835                    String name = it.next();
17836                    SharedLibraryEntry ent = mSharedLibraries.get(name);
17837                    if (!checkin) {
17838                        if (!printedHeader) {
17839                            if (dumpState.onTitlePrinted())
17840                                pw.println();
17841                            pw.println("Libraries:");
17842                            printedHeader = true;
17843                        }
17844                        pw.print("  ");
17845                    } else {
17846                        pw.print("lib,");
17847                    }
17848                    pw.print(name);
17849                    if (!checkin) {
17850                        pw.print(" -> ");
17851                    }
17852                    if (ent.path != null) {
17853                        if (!checkin) {
17854                            pw.print("(jar) ");
17855                            pw.print(ent.path);
17856                        } else {
17857                            pw.print(",jar,");
17858                            pw.print(ent.path);
17859                        }
17860                    } else {
17861                        if (!checkin) {
17862                            pw.print("(apk) ");
17863                            pw.print(ent.apk);
17864                        } else {
17865                            pw.print(",apk,");
17866                            pw.print(ent.apk);
17867                        }
17868                    }
17869                    pw.println();
17870                }
17871            }
17872
17873            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
17874                if (dumpState.onTitlePrinted())
17875                    pw.println();
17876                if (!checkin) {
17877                    pw.println("Features:");
17878                }
17879
17880                for (FeatureInfo feat : mAvailableFeatures.values()) {
17881                    if (checkin) {
17882                        pw.print("feat,");
17883                        pw.print(feat.name);
17884                        pw.print(",");
17885                        pw.println(feat.version);
17886                    } else {
17887                        pw.print("  ");
17888                        pw.print(feat.name);
17889                        if (feat.version > 0) {
17890                            pw.print(" version=");
17891                            pw.print(feat.version);
17892                        }
17893                        pw.println();
17894                    }
17895                }
17896            }
17897
17898            if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) {
17899                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
17900                        : "Activity Resolver Table:", "  ", packageName,
17901                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
17902                    dumpState.setTitlePrinted(true);
17903                }
17904            }
17905            if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) {
17906                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
17907                        : "Receiver Resolver Table:", "  ", packageName,
17908                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
17909                    dumpState.setTitlePrinted(true);
17910                }
17911            }
17912            if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) {
17913                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
17914                        : "Service Resolver Table:", "  ", packageName,
17915                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
17916                    dumpState.setTitlePrinted(true);
17917                }
17918            }
17919            if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) {
17920                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
17921                        : "Provider Resolver Table:", "  ", packageName,
17922                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
17923                    dumpState.setTitlePrinted(true);
17924                }
17925            }
17926
17927            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
17928                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
17929                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
17930                    int user = mSettings.mPreferredActivities.keyAt(i);
17931                    if (pir.dump(pw,
17932                            dumpState.getTitlePrinted()
17933                                ? "\nPreferred Activities User " + user + ":"
17934                                : "Preferred Activities User " + user + ":", "  ",
17935                            packageName, true, false)) {
17936                        dumpState.setTitlePrinted(true);
17937                    }
17938                }
17939            }
17940
17941            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
17942                pw.flush();
17943                FileOutputStream fout = new FileOutputStream(fd);
17944                BufferedOutputStream str = new BufferedOutputStream(fout);
17945                XmlSerializer serializer = new FastXmlSerializer();
17946                try {
17947                    serializer.setOutput(str, StandardCharsets.UTF_8.name());
17948                    serializer.startDocument(null, true);
17949                    serializer.setFeature(
17950                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
17951                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
17952                    serializer.endDocument();
17953                    serializer.flush();
17954                } catch (IllegalArgumentException e) {
17955                    pw.println("Failed writing: " + e);
17956                } catch (IllegalStateException e) {
17957                    pw.println("Failed writing: " + e);
17958                } catch (IOException e) {
17959                    pw.println("Failed writing: " + e);
17960                }
17961            }
17962
17963            if (!checkin
17964                    && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)
17965                    && packageName == null) {
17966                pw.println();
17967                int count = mSettings.mPackages.size();
17968                if (count == 0) {
17969                    pw.println("No applications!");
17970                    pw.println();
17971                } else {
17972                    final String prefix = "  ";
17973                    Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values();
17974                    if (allPackageSettings.size() == 0) {
17975                        pw.println("No domain preferred apps!");
17976                        pw.println();
17977                    } else {
17978                        pw.println("App verification status:");
17979                        pw.println();
17980                        count = 0;
17981                        for (PackageSetting ps : allPackageSettings) {
17982                            IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
17983                            if (ivi == null || ivi.getPackageName() == null) continue;
17984                            pw.println(prefix + "Package: " + ivi.getPackageName());
17985                            pw.println(prefix + "Domains: " + ivi.getDomainsString());
17986                            pw.println(prefix + "Status:  " + ivi.getStatusString());
17987                            pw.println();
17988                            count++;
17989                        }
17990                        if (count == 0) {
17991                            pw.println(prefix + "No app verification established.");
17992                            pw.println();
17993                        }
17994                        for (int userId : sUserManager.getUserIds()) {
17995                            pw.println("App linkages for user " + userId + ":");
17996                            pw.println();
17997                            count = 0;
17998                            for (PackageSetting ps : allPackageSettings) {
17999                                final long status = ps.getDomainVerificationStatusForUser(userId);
18000                                if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
18001                                    continue;
18002                                }
18003                                pw.println(prefix + "Package: " + ps.name);
18004                                pw.println(prefix + "Domains: " + dumpDomainString(ps.name));
18005                                String statusStr = IntentFilterVerificationInfo.
18006                                        getStatusStringFromValue(status);
18007                                pw.println(prefix + "Status:  " + statusStr);
18008                                pw.println();
18009                                count++;
18010                            }
18011                            if (count == 0) {
18012                                pw.println(prefix + "No configured app linkages.");
18013                                pw.println();
18014                            }
18015                        }
18016                    }
18017                }
18018            }
18019
18020            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
18021                mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState);
18022                if (packageName == null && permissionNames == null) {
18023                    for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) {
18024                        if (iperm == 0) {
18025                            if (dumpState.onTitlePrinted())
18026                                pw.println();
18027                            pw.println("AppOp Permissions:");
18028                        }
18029                        pw.print("  AppOp Permission ");
18030                        pw.print(mAppOpPermissionPackages.keyAt(iperm));
18031                        pw.println(":");
18032                        ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm);
18033                        for (int ipkg=0; ipkg<pkgs.size(); ipkg++) {
18034                            pw.print("    "); pw.println(pkgs.valueAt(ipkg));
18035                        }
18036                    }
18037                }
18038            }
18039
18040            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
18041                boolean printedSomething = false;
18042                for (PackageParser.Provider p : mProviders.mProviders.values()) {
18043                    if (packageName != null && !packageName.equals(p.info.packageName)) {
18044                        continue;
18045                    }
18046                    if (!printedSomething) {
18047                        if (dumpState.onTitlePrinted())
18048                            pw.println();
18049                        pw.println("Registered ContentProviders:");
18050                        printedSomething = true;
18051                    }
18052                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
18053                    pw.print("    "); pw.println(p.toString());
18054                }
18055                printedSomething = false;
18056                for (Map.Entry<String, PackageParser.Provider> entry :
18057                        mProvidersByAuthority.entrySet()) {
18058                    PackageParser.Provider p = entry.getValue();
18059                    if (packageName != null && !packageName.equals(p.info.packageName)) {
18060                        continue;
18061                    }
18062                    if (!printedSomething) {
18063                        if (dumpState.onTitlePrinted())
18064                            pw.println();
18065                        pw.println("ContentProvider Authorities:");
18066                        printedSomething = true;
18067                    }
18068                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
18069                    pw.print("    "); pw.println(p.toString());
18070                    if (p.info != null && p.info.applicationInfo != null) {
18071                        final String appInfo = p.info.applicationInfo.toString();
18072                        pw.print("      applicationInfo="); pw.println(appInfo);
18073                    }
18074                }
18075            }
18076
18077            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
18078                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
18079            }
18080
18081            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
18082                mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin);
18083            }
18084
18085            if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
18086                mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin);
18087            }
18088
18089            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) {
18090                mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState);
18091            }
18092
18093            if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
18094                // XXX should handle packageName != null by dumping only install data that
18095                // the given package is involved with.
18096                if (dumpState.onTitlePrinted()) pw.println();
18097                mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
18098            }
18099
18100            if (!checkin && dumpState.isDumping(DumpState.DUMP_FROZEN) && packageName == null) {
18101                // XXX should handle packageName != null by dumping only install data that
18102                // the given package is involved with.
18103                if (dumpState.onTitlePrinted()) pw.println();
18104
18105                final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
18106                ipw.println();
18107                ipw.println("Frozen packages:");
18108                ipw.increaseIndent();
18109                if (mFrozenPackages.size() == 0) {
18110                    ipw.println("(none)");
18111                } else {
18112                    for (int i = 0; i < mFrozenPackages.size(); i++) {
18113                        ipw.println(mFrozenPackages.valueAt(i));
18114                    }
18115                }
18116                ipw.decreaseIndent();
18117            }
18118
18119            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
18120                if (dumpState.onTitlePrinted()) pw.println();
18121                mSettings.dumpReadMessagesLPr(pw, dumpState);
18122
18123                pw.println();
18124                pw.println("Package warning messages:");
18125                BufferedReader in = null;
18126                String line = null;
18127                try {
18128                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
18129                    while ((line = in.readLine()) != null) {
18130                        if (line.contains("ignored: updated version")) continue;
18131                        pw.println(line);
18132                    }
18133                } catch (IOException ignored) {
18134                } finally {
18135                    IoUtils.closeQuietly(in);
18136                }
18137            }
18138
18139            if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) {
18140                BufferedReader in = null;
18141                String line = null;
18142                try {
18143                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
18144                    while ((line = in.readLine()) != null) {
18145                        if (line.contains("ignored: updated version")) continue;
18146                        pw.print("msg,");
18147                        pw.println(line);
18148                    }
18149                } catch (IOException ignored) {
18150                } finally {
18151                    IoUtils.closeQuietly(in);
18152                }
18153            }
18154        }
18155    }
18156
18157    private String dumpDomainString(String packageName) {
18158        List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName)
18159                .getList();
18160        List<IntentFilter> filters = getAllIntentFilters(packageName).getList();
18161
18162        ArraySet<String> result = new ArraySet<>();
18163        if (iviList.size() > 0) {
18164            for (IntentFilterVerificationInfo ivi : iviList) {
18165                for (String host : ivi.getDomains()) {
18166                    result.add(host);
18167                }
18168            }
18169        }
18170        if (filters != null && filters.size() > 0) {
18171            for (IntentFilter filter : filters) {
18172                if (filter.hasCategory(Intent.CATEGORY_BROWSABLE)
18173                        && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
18174                                filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) {
18175                    result.addAll(filter.getHostsList());
18176                }
18177            }
18178        }
18179
18180        StringBuilder sb = new StringBuilder(result.size() * 16);
18181        for (String domain : result) {
18182            if (sb.length() > 0) sb.append(" ");
18183            sb.append(domain);
18184        }
18185        return sb.toString();
18186    }
18187
18188    // ------- apps on sdcard specific code -------
18189    static final boolean DEBUG_SD_INSTALL = false;
18190
18191    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
18192
18193    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
18194
18195    private boolean mMediaMounted = false;
18196
18197    static String getEncryptKey() {
18198        try {
18199            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
18200                    SD_ENCRYPTION_KEYSTORE_NAME);
18201            if (sdEncKey == null) {
18202                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
18203                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
18204                if (sdEncKey == null) {
18205                    Slog.e(TAG, "Failed to create encryption keys");
18206                    return null;
18207                }
18208            }
18209            return sdEncKey;
18210        } catch (NoSuchAlgorithmException nsae) {
18211            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
18212            return null;
18213        } catch (IOException ioe) {
18214            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
18215            return null;
18216        }
18217    }
18218
18219    /*
18220     * Update media status on PackageManager.
18221     */
18222    @Override
18223    public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
18224        int callingUid = Binder.getCallingUid();
18225        if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
18226            throw new SecurityException("Media status can only be updated by the system");
18227        }
18228        // reader; this apparently protects mMediaMounted, but should probably
18229        // be a different lock in that case.
18230        synchronized (mPackages) {
18231            Log.i(TAG, "Updating external media status from "
18232                    + (mMediaMounted ? "mounted" : "unmounted") + " to "
18233                    + (mediaStatus ? "mounted" : "unmounted"));
18234            if (DEBUG_SD_INSTALL)
18235                Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
18236                        + ", mMediaMounted=" + mMediaMounted);
18237            if (mediaStatus == mMediaMounted) {
18238                final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
18239                        : 0, -1);
18240                mHandler.sendMessage(msg);
18241                return;
18242            }
18243            mMediaMounted = mediaStatus;
18244        }
18245        // Queue up an async operation since the package installation may take a
18246        // little while.
18247        mHandler.post(new Runnable() {
18248            public void run() {
18249                updateExternalMediaStatusInner(mediaStatus, reportStatus, true);
18250            }
18251        });
18252    }
18253
18254    /**
18255     * Called by MountService when the initial ASECs to scan are available.
18256     * Should block until all the ASEC containers are finished being scanned.
18257     */
18258    public void scanAvailableAsecs() {
18259        updateExternalMediaStatusInner(true, false, false);
18260    }
18261
18262    /*
18263     * Collect information of applications on external media, map them against
18264     * existing containers and update information based on current mount status.
18265     * Please note that we always have to report status if reportStatus has been
18266     * set to true especially when unloading packages.
18267     */
18268    private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus,
18269            boolean externalStorage) {
18270        ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>();
18271        int[] uidArr = EmptyArray.INT;
18272
18273        final String[] list = PackageHelper.getSecureContainerList();
18274        if (ArrayUtils.isEmpty(list)) {
18275            Log.i(TAG, "No secure containers found");
18276        } else {
18277            // Process list of secure containers and categorize them
18278            // as active or stale based on their package internal state.
18279
18280            // reader
18281            synchronized (mPackages) {
18282                for (String cid : list) {
18283                    // Leave stages untouched for now; installer service owns them
18284                    if (PackageInstallerService.isStageName(cid)) continue;
18285
18286                    if (DEBUG_SD_INSTALL)
18287                        Log.i(TAG, "Processing container " + cid);
18288                    String pkgName = getAsecPackageName(cid);
18289                    if (pkgName == null) {
18290                        Slog.i(TAG, "Found stale container " + cid + " with no package name");
18291                        continue;
18292                    }
18293                    if (DEBUG_SD_INSTALL)
18294                        Log.i(TAG, "Looking for pkg : " + pkgName);
18295
18296                    final PackageSetting ps = mSettings.mPackages.get(pkgName);
18297                    if (ps == null) {
18298                        Slog.i(TAG, "Found stale container " + cid + " with no matching settings");
18299                        continue;
18300                    }
18301
18302                    /*
18303                     * Skip packages that are not external if we're unmounting
18304                     * external storage.
18305                     */
18306                    if (externalStorage && !isMounted && !isExternal(ps)) {
18307                        continue;
18308                    }
18309
18310                    final AsecInstallArgs args = new AsecInstallArgs(cid,
18311                            getAppDexInstructionSets(ps), ps.isForwardLocked());
18312                    // The package status is changed only if the code path
18313                    // matches between settings and the container id.
18314                    if (ps.codePathString != null
18315                            && ps.codePathString.startsWith(args.getCodePath())) {
18316                        if (DEBUG_SD_INSTALL) {
18317                            Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
18318                                    + " at code path: " + ps.codePathString);
18319                        }
18320
18321                        // We do have a valid package installed on sdcard
18322                        processCids.put(args, ps.codePathString);
18323                        final int uid = ps.appId;
18324                        if (uid != -1) {
18325                            uidArr = ArrayUtils.appendInt(uidArr, uid);
18326                        }
18327                    } else {
18328                        Slog.i(TAG, "Found stale container " + cid + ": expected codePath="
18329                                + ps.codePathString);
18330                    }
18331                }
18332            }
18333
18334            Arrays.sort(uidArr);
18335        }
18336
18337        // Process packages with valid entries.
18338        if (isMounted) {
18339            if (DEBUG_SD_INSTALL)
18340                Log.i(TAG, "Loading packages");
18341            loadMediaPackages(processCids, uidArr, externalStorage);
18342            startCleaningPackages();
18343            mInstallerService.onSecureContainersAvailable();
18344        } else {
18345            if (DEBUG_SD_INSTALL)
18346                Log.i(TAG, "Unloading packages");
18347            unloadMediaPackages(processCids, uidArr, reportStatus);
18348        }
18349    }
18350
18351    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
18352            ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) {
18353        final int size = infos.size();
18354        final String[] packageNames = new String[size];
18355        final int[] packageUids = new int[size];
18356        for (int i = 0; i < size; i++) {
18357            final ApplicationInfo info = infos.get(i);
18358            packageNames[i] = info.packageName;
18359            packageUids[i] = info.uid;
18360        }
18361        sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids,
18362                finishedReceiver);
18363    }
18364
18365    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
18366            ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
18367        sendResourcesChangedBroadcast(mediaStatus, replacing,
18368                pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver);
18369    }
18370
18371    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
18372            String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
18373        int size = pkgList.length;
18374        if (size > 0) {
18375            // Send broadcasts here
18376            Bundle extras = new Bundle();
18377            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
18378            if (uidArr != null) {
18379                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
18380            }
18381            if (replacing) {
18382                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
18383            }
18384            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
18385                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
18386            sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null);
18387        }
18388    }
18389
18390   /*
18391     * Look at potentially valid container ids from processCids If package
18392     * information doesn't match the one on record or package scanning fails,
18393     * the cid is added to list of removeCids. We currently don't delete stale
18394     * containers.
18395     */
18396    private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr,
18397            boolean externalStorage) {
18398        ArrayList<String> pkgList = new ArrayList<String>();
18399        Set<AsecInstallArgs> keys = processCids.keySet();
18400
18401        for (AsecInstallArgs args : keys) {
18402            String codePath = processCids.get(args);
18403            if (DEBUG_SD_INSTALL)
18404                Log.i(TAG, "Loading container : " + args.cid);
18405            int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
18406            try {
18407                // Make sure there are no container errors first.
18408                if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
18409                    Slog.e(TAG, "Failed to mount cid : " + args.cid
18410                            + " when installing from sdcard");
18411                    continue;
18412                }
18413                // Check code path here.
18414                if (codePath == null || !codePath.startsWith(args.getCodePath())) {
18415                    Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
18416                            + " does not match one in settings " + codePath);
18417                    continue;
18418                }
18419                // Parse package
18420                int parseFlags = mDefParseFlags;
18421                if (args.isExternalAsec()) {
18422                    parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE;
18423                }
18424                if (args.isFwdLocked()) {
18425                    parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
18426                }
18427
18428                synchronized (mInstallLock) {
18429                    PackageParser.Package pkg = null;
18430                    try {
18431                        // Sadly we don't know the package name yet to freeze it
18432                        pkg = scanPackageTracedLI(new File(codePath), parseFlags,
18433                                SCAN_IGNORE_FROZEN, 0, null);
18434                    } catch (PackageManagerException e) {
18435                        Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage());
18436                    }
18437                    // Scan the package
18438                    if (pkg != null) {
18439                        /*
18440                         * TODO why is the lock being held? doPostInstall is
18441                         * called in other places without the lock. This needs
18442                         * to be straightened out.
18443                         */
18444                        // writer
18445                        synchronized (mPackages) {
18446                            retCode = PackageManager.INSTALL_SUCCEEDED;
18447                            pkgList.add(pkg.packageName);
18448                            // Post process args
18449                            args.doPostInstall(PackageManager.INSTALL_SUCCEEDED,
18450                                    pkg.applicationInfo.uid);
18451                        }
18452                    } else {
18453                        Slog.i(TAG, "Failed to install pkg from  " + codePath + " from sdcard");
18454                    }
18455                }
18456
18457            } finally {
18458                if (retCode != PackageManager.INSTALL_SUCCEEDED) {
18459                    Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode);
18460                }
18461            }
18462        }
18463        // writer
18464        synchronized (mPackages) {
18465            // If the platform SDK has changed since the last time we booted,
18466            // we need to re-grant app permission to catch any new ones that
18467            // appear. This is really a hack, and means that apps can in some
18468            // cases get permissions that the user didn't initially explicitly
18469            // allow... it would be nice to have some better way to handle
18470            // this situation.
18471            final VersionInfo ver = externalStorage ? mSettings.getExternalVersion()
18472                    : mSettings.getInternalVersion();
18473            final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL
18474                    : StorageManager.UUID_PRIVATE_INTERNAL;
18475
18476            int updateFlags = UPDATE_PERMISSIONS_ALL;
18477            if (ver.sdkVersion != mSdkVersion) {
18478                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
18479                        + mSdkVersion + "; regranting permissions for external");
18480                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
18481            }
18482            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
18483
18484            // Yay, everything is now upgraded
18485            ver.forceCurrent();
18486
18487            // can downgrade to reader
18488            // Persist settings
18489            mSettings.writeLPr();
18490        }
18491        // Send a broadcast to let everyone know we are done processing
18492        if (pkgList.size() > 0) {
18493            sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
18494        }
18495    }
18496
18497   /*
18498     * Utility method to unload a list of specified containers
18499     */
18500    private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) {
18501        // Just unmount all valid containers.
18502        for (AsecInstallArgs arg : cidArgs) {
18503            synchronized (mInstallLock) {
18504                arg.doPostDeleteLI(false);
18505           }
18506       }
18507   }
18508
18509    /*
18510     * Unload packages mounted on external media. This involves deleting package
18511     * data from internal structures, sending broadcasts about disabled packages,
18512     * gc'ing to free up references, unmounting all secure containers
18513     * corresponding to packages on external media, and posting a
18514     * UPDATED_MEDIA_STATUS message if status has been requested. Please note
18515     * that we always have to post this message if status has been requested no
18516     * matter what.
18517     */
18518    private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[],
18519            final boolean reportStatus) {
18520        if (DEBUG_SD_INSTALL)
18521            Log.i(TAG, "unloading media packages");
18522        ArrayList<String> pkgList = new ArrayList<String>();
18523        ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>();
18524        final Set<AsecInstallArgs> keys = processCids.keySet();
18525        for (AsecInstallArgs args : keys) {
18526            String pkgName = args.getPackageName();
18527            if (DEBUG_SD_INSTALL)
18528                Log.i(TAG, "Trying to unload pkg : " + pkgName);
18529            // Delete package internally
18530            PackageRemovedInfo outInfo = new PackageRemovedInfo();
18531            synchronized (mInstallLock) {
18532                final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
18533                final boolean res;
18534                try (PackageFreezer freezer = freezePackageForDelete(pkgName, deleteFlags,
18535                        "unloadMediaPackages")) {
18536                    res = deletePackageLIF(pkgName, null, false, null, deleteFlags, outInfo, false,
18537                            null);
18538                }
18539                if (res) {
18540                    pkgList.add(pkgName);
18541                } else {
18542                    Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
18543                    failedList.add(args);
18544                }
18545            }
18546        }
18547
18548        // reader
18549        synchronized (mPackages) {
18550            // We didn't update the settings after removing each package;
18551            // write them now for all packages.
18552            mSettings.writeLPr();
18553        }
18554
18555        // We have to absolutely send UPDATED_MEDIA_STATUS only
18556        // after confirming that all the receivers processed the ordered
18557        // broadcast when packages get disabled, force a gc to clean things up.
18558        // and unload all the containers.
18559        if (pkgList.size() > 0) {
18560            sendResourcesChangedBroadcast(false, false, pkgList, uidArr,
18561                    new IIntentReceiver.Stub() {
18562                public void performReceive(Intent intent, int resultCode, String data,
18563                        Bundle extras, boolean ordered, boolean sticky,
18564                        int sendingUser) throws RemoteException {
18565                    Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
18566                            reportStatus ? 1 : 0, 1, keys);
18567                    mHandler.sendMessage(msg);
18568                }
18569            });
18570        } else {
18571            Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
18572                    keys);
18573            mHandler.sendMessage(msg);
18574        }
18575    }
18576
18577    private void loadPrivatePackages(final VolumeInfo vol) {
18578        mHandler.post(new Runnable() {
18579            @Override
18580            public void run() {
18581                loadPrivatePackagesInner(vol);
18582            }
18583        });
18584    }
18585
18586    private void loadPrivatePackagesInner(VolumeInfo vol) {
18587        final String volumeUuid = vol.fsUuid;
18588        if (TextUtils.isEmpty(volumeUuid)) {
18589            Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring");
18590            return;
18591        }
18592
18593        final ArrayList<PackageFreezer> freezers = new ArrayList<>();
18594        final ArrayList<ApplicationInfo> loaded = new ArrayList<>();
18595        final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE;
18596
18597        final VersionInfo ver;
18598        final List<PackageSetting> packages;
18599        synchronized (mPackages) {
18600            ver = mSettings.findOrCreateVersion(volumeUuid);
18601            packages = mSettings.getVolumePackagesLPr(volumeUuid);
18602        }
18603
18604        for (PackageSetting ps : packages) {
18605            freezers.add(freezePackage(ps.name, "loadPrivatePackagesInner"));
18606            synchronized (mInstallLock) {
18607                final PackageParser.Package pkg;
18608                try {
18609                    pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null);
18610                    loaded.add(pkg.applicationInfo);
18611
18612                } catch (PackageManagerException e) {
18613                    Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage());
18614                }
18615
18616                if (!Build.FINGERPRINT.equals(ver.fingerprint)) {
18617                    clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
18618                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
18619                                    | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
18620                }
18621            }
18622        }
18623
18624        // Reconcile app data for all started/unlocked users
18625        final StorageManager sm = mContext.getSystemService(StorageManager.class);
18626        final UserManager um = mContext.getSystemService(UserManager.class);
18627        for (UserInfo user : um.getUsers()) {
18628            final int flags;
18629            if (um.isUserUnlocked(user.id)) {
18630                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
18631            } else if (um.isUserRunning(user.id)) {
18632                flags = StorageManager.FLAG_STORAGE_DE;
18633            } else {
18634                continue;
18635            }
18636
18637            sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags);
18638            synchronized (mInstallLock) {
18639                reconcileAppsDataLI(volumeUuid, user.id, flags);
18640            }
18641        }
18642
18643        synchronized (mPackages) {
18644            int updateFlags = UPDATE_PERMISSIONS_ALL;
18645            if (ver.sdkVersion != mSdkVersion) {
18646                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
18647                        + mSdkVersion + "; regranting permissions for " + volumeUuid);
18648                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
18649            }
18650            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
18651
18652            // Yay, everything is now upgraded
18653            ver.forceCurrent();
18654
18655            mSettings.writeLPr();
18656        }
18657
18658        for (PackageFreezer freezer : freezers) {
18659            freezer.close();
18660        }
18661
18662        if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded);
18663        sendResourcesChangedBroadcast(true, false, loaded, null);
18664    }
18665
18666    private void unloadPrivatePackages(final VolumeInfo vol) {
18667        mHandler.post(new Runnable() {
18668            @Override
18669            public void run() {
18670                unloadPrivatePackagesInner(vol);
18671            }
18672        });
18673    }
18674
18675    private void unloadPrivatePackagesInner(VolumeInfo vol) {
18676        final String volumeUuid = vol.fsUuid;
18677        if (TextUtils.isEmpty(volumeUuid)) {
18678            Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring");
18679            return;
18680        }
18681
18682        final ArrayList<ApplicationInfo> unloaded = new ArrayList<>();
18683        synchronized (mInstallLock) {
18684        synchronized (mPackages) {
18685            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid);
18686            for (PackageSetting ps : packages) {
18687                if (ps.pkg == null) continue;
18688
18689                final ApplicationInfo info = ps.pkg.applicationInfo;
18690                final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
18691                final PackageRemovedInfo outInfo = new PackageRemovedInfo();
18692
18693                try (PackageFreezer freezer = freezePackageForDelete(ps.name, deleteFlags,
18694                        "unloadPrivatePackagesInner")) {
18695                    if (deletePackageLIF(ps.name, null, false, null, deleteFlags, outInfo,
18696                            false, null)) {
18697                        unloaded.add(info);
18698                    } else {
18699                        Slog.w(TAG, "Failed to unload " + ps.codePath);
18700                    }
18701                }
18702            }
18703
18704            mSettings.writeLPr();
18705        }
18706        }
18707
18708        if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded);
18709        sendResourcesChangedBroadcast(false, false, unloaded, null);
18710    }
18711
18712    /**
18713     * Prepare storage areas for given user on all mounted devices.
18714     */
18715    void prepareUserData(int userId, int userSerial, int flags) {
18716        synchronized (mInstallLock) {
18717            final StorageManager storage = mContext.getSystemService(StorageManager.class);
18718            for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
18719                final String volumeUuid = vol.getFsUuid();
18720                prepareUserDataLI(volumeUuid, userId, userSerial, flags, true);
18721            }
18722        }
18723    }
18724
18725    private void prepareUserDataLI(String volumeUuid, int userId, int userSerial, int flags,
18726            boolean allowRecover) {
18727        // Prepare storage and verify that serial numbers are consistent; if
18728        // there's a mismatch we need to destroy to avoid leaking data
18729        final StorageManager storage = mContext.getSystemService(StorageManager.class);
18730        try {
18731            storage.prepareUserStorage(volumeUuid, userId, userSerial, flags);
18732
18733            if ((flags & StorageManager.FLAG_STORAGE_DE) != 0 && !mOnlyCore) {
18734                UserManagerService.enforceSerialNumber(
18735                        Environment.getDataUserDeDirectory(volumeUuid, userId), userSerial);
18736            }
18737            if ((flags & StorageManager.FLAG_STORAGE_CE) != 0 && !mOnlyCore) {
18738                UserManagerService.enforceSerialNumber(
18739                        Environment.getDataUserCeDirectory(volumeUuid, userId), userSerial);
18740            }
18741
18742            synchronized (mInstallLock) {
18743                mInstaller.createUserData(volumeUuid, userId, userSerial, flags);
18744            }
18745        } catch (Exception e) {
18746            logCriticalInfo(Log.WARN, "Destroying user " + userId + " on volume " + volumeUuid
18747                    + " because we failed to prepare: " + e);
18748            destroyUserDataLI(volumeUuid, userId, flags);
18749
18750            if (allowRecover) {
18751                // Try one last time; if we fail again we're really in trouble
18752                prepareUserDataLI(volumeUuid, userId, userSerial, flags, false);
18753            }
18754        }
18755    }
18756
18757    /**
18758     * Destroy storage areas for given user on all mounted devices.
18759     */
18760    void destroyUserData(int userId, int flags) {
18761        synchronized (mInstallLock) {
18762            final StorageManager storage = mContext.getSystemService(StorageManager.class);
18763            for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
18764                final String volumeUuid = vol.getFsUuid();
18765                destroyUserDataLI(volumeUuid, userId, flags);
18766            }
18767        }
18768    }
18769
18770    private void destroyUserDataLI(String volumeUuid, int userId, int flags) {
18771        final StorageManager storage = mContext.getSystemService(StorageManager.class);
18772        try {
18773            // Clean up app data, profile data, and media data
18774            mInstaller.destroyUserData(volumeUuid, userId, flags);
18775
18776            // Clean up system data
18777            if (Objects.equals(volumeUuid, StorageManager.UUID_PRIVATE_INTERNAL)) {
18778                if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) {
18779                    FileUtils.deleteContentsAndDir(Environment.getUserSystemDirectory(userId));
18780                    FileUtils.deleteContentsAndDir(Environment.getDataSystemDeDirectory(userId));
18781                }
18782                if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
18783                    FileUtils.deleteContentsAndDir(Environment.getDataSystemCeDirectory(userId));
18784                }
18785            }
18786
18787            // Data with special labels is now gone, so finish the job
18788            storage.destroyUserStorage(volumeUuid, userId, flags);
18789
18790        } catch (Exception e) {
18791            logCriticalInfo(Log.WARN,
18792                    "Failed to destroy user " + userId + " on volume " + volumeUuid + ": " + e);
18793        }
18794    }
18795
18796    /**
18797     * Examine all users present on given mounted volume, and destroy data
18798     * belonging to users that are no longer valid, or whose user ID has been
18799     * recycled.
18800     */
18801    private void reconcileUsers(String volumeUuid) {
18802        final List<File> files = new ArrayList<>();
18803        Collections.addAll(files, FileUtils
18804                .listFilesOrEmpty(Environment.getDataUserDeDirectory(volumeUuid)));
18805        Collections.addAll(files, FileUtils
18806                .listFilesOrEmpty(Environment.getDataUserCeDirectory(volumeUuid)));
18807        for (File file : files) {
18808            if (!file.isDirectory()) continue;
18809
18810            final int userId;
18811            final UserInfo info;
18812            try {
18813                userId = Integer.parseInt(file.getName());
18814                info = sUserManager.getUserInfo(userId);
18815            } catch (NumberFormatException e) {
18816                Slog.w(TAG, "Invalid user directory " + file);
18817                continue;
18818            }
18819
18820            boolean destroyUser = false;
18821            if (info == null) {
18822                logCriticalInfo(Log.WARN, "Destroying user directory " + file
18823                        + " because no matching user was found");
18824                destroyUser = true;
18825            } else if (!mOnlyCore) {
18826                try {
18827                    UserManagerService.enforceSerialNumber(file, info.serialNumber);
18828                } catch (IOException e) {
18829                    logCriticalInfo(Log.WARN, "Destroying user directory " + file
18830                            + " because we failed to enforce serial number: " + e);
18831                    destroyUser = true;
18832                }
18833            }
18834
18835            if (destroyUser) {
18836                synchronized (mInstallLock) {
18837                    destroyUserDataLI(volumeUuid, userId,
18838                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
18839                }
18840            }
18841        }
18842    }
18843
18844    private void assertPackageKnown(String volumeUuid, String packageName)
18845            throws PackageManagerException {
18846        synchronized (mPackages) {
18847            final PackageSetting ps = mSettings.mPackages.get(packageName);
18848            if (ps == null) {
18849                throw new PackageManagerException("Package " + packageName + " is unknown");
18850            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
18851                throw new PackageManagerException(
18852                        "Package " + packageName + " found on unknown volume " + volumeUuid
18853                                + "; expected volume " + ps.volumeUuid);
18854            }
18855        }
18856    }
18857
18858    private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId)
18859            throws PackageManagerException {
18860        synchronized (mPackages) {
18861            final PackageSetting ps = mSettings.mPackages.get(packageName);
18862            if (ps == null) {
18863                throw new PackageManagerException("Package " + packageName + " is unknown");
18864            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
18865                throw new PackageManagerException(
18866                        "Package " + packageName + " found on unknown volume " + volumeUuid
18867                                + "; expected volume " + ps.volumeUuid);
18868            } else if (!ps.getInstalled(userId)) {
18869                throw new PackageManagerException(
18870                        "Package " + packageName + " not installed for user " + userId);
18871            }
18872        }
18873    }
18874
18875    /**
18876     * Examine all apps present on given mounted volume, and destroy apps that
18877     * aren't expected, either due to uninstallation or reinstallation on
18878     * another volume.
18879     */
18880    private void reconcileApps(String volumeUuid) {
18881        final File[] files = FileUtils
18882                .listFilesOrEmpty(Environment.getDataAppDirectory(volumeUuid));
18883        for (File file : files) {
18884            final boolean isPackage = (isApkFile(file) || file.isDirectory())
18885                    && !PackageInstallerService.isStageName(file.getName());
18886            if (!isPackage) {
18887                // Ignore entries which are not packages
18888                continue;
18889            }
18890
18891            try {
18892                final PackageLite pkg = PackageParser.parsePackageLite(file,
18893                        PackageParser.PARSE_MUST_BE_APK);
18894                assertPackageKnown(volumeUuid, pkg.packageName);
18895
18896            } catch (PackageParserException | PackageManagerException e) {
18897                logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
18898                synchronized (mInstallLock) {
18899                    removeCodePathLI(file);
18900                }
18901            }
18902        }
18903    }
18904
18905    /**
18906     * Reconcile all app data for the given user.
18907     * <p>
18908     * Verifies that directories exist and that ownership and labeling is
18909     * correct for all installed apps on all mounted volumes.
18910     */
18911    void reconcileAppsData(int userId, int flags) {
18912        final StorageManager storage = mContext.getSystemService(StorageManager.class);
18913        for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
18914            final String volumeUuid = vol.getFsUuid();
18915            synchronized (mInstallLock) {
18916                reconcileAppsDataLI(volumeUuid, userId, flags);
18917            }
18918        }
18919    }
18920
18921    /**
18922     * Reconcile all app data on given mounted volume.
18923     * <p>
18924     * Destroys app data that isn't expected, either due to uninstallation or
18925     * reinstallation on another volume.
18926     * <p>
18927     * Verifies that directories exist and that ownership and labeling is
18928     * correct for all installed apps.
18929     */
18930    private void reconcileAppsDataLI(String volumeUuid, int userId, int flags) {
18931        Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x"
18932                + Integer.toHexString(flags));
18933
18934        final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId);
18935        final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId);
18936
18937        boolean restoreconNeeded = false;
18938
18939        // First look for stale data that doesn't belong, and check if things
18940        // have changed since we did our last restorecon
18941        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
18942            if (!isUserKeyUnlocked(userId)) {
18943                throw new RuntimeException(
18944                        "Yikes, someone asked us to reconcile CE storage while " + userId
18945                                + " was still locked; this would have caused massive data loss!");
18946            }
18947
18948            restoreconNeeded |= SELinuxMMAC.isRestoreconNeeded(ceDir);
18949
18950            final File[] files = FileUtils.listFilesOrEmpty(ceDir);
18951            for (File file : files) {
18952                final String packageName = file.getName();
18953                try {
18954                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
18955                } catch (PackageManagerException e) {
18956                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
18957                    try {
18958                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
18959                                StorageManager.FLAG_STORAGE_CE, 0);
18960                    } catch (InstallerException e2) {
18961                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
18962                    }
18963                }
18964            }
18965        }
18966        if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) {
18967            restoreconNeeded |= SELinuxMMAC.isRestoreconNeeded(deDir);
18968
18969            final File[] files = FileUtils.listFilesOrEmpty(deDir);
18970            for (File file : files) {
18971                final String packageName = file.getName();
18972                try {
18973                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
18974                } catch (PackageManagerException e) {
18975                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
18976                    try {
18977                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
18978                                StorageManager.FLAG_STORAGE_DE, 0);
18979                    } catch (InstallerException e2) {
18980                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
18981                    }
18982                }
18983            }
18984        }
18985
18986        // Ensure that data directories are ready to roll for all packages
18987        // installed for this volume and user
18988        final List<PackageSetting> packages;
18989        synchronized (mPackages) {
18990            packages = mSettings.getVolumePackagesLPr(volumeUuid);
18991        }
18992        int preparedCount = 0;
18993        for (PackageSetting ps : packages) {
18994            final String packageName = ps.name;
18995            if (ps.pkg == null) {
18996                Slog.w(TAG, "Odd, missing scanned package " + packageName);
18997                // TODO: might be due to legacy ASEC apps; we should circle back
18998                // and reconcile again once they're scanned
18999                continue;
19000            }
19001
19002            if (ps.getInstalled(userId)) {
19003                prepareAppDataLIF(ps.pkg, userId, flags, restoreconNeeded);
19004
19005                if (maybeMigrateAppDataLIF(ps.pkg, userId)) {
19006                    // We may have just shuffled around app data directories, so
19007                    // prepare them one more time
19008                    prepareAppDataLIF(ps.pkg, userId, flags, restoreconNeeded);
19009                }
19010
19011                preparedCount++;
19012            }
19013        }
19014
19015        if (restoreconNeeded) {
19016            if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
19017                SELinuxMMAC.setRestoreconDone(ceDir);
19018            }
19019            if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) {
19020                SELinuxMMAC.setRestoreconDone(deDir);
19021            }
19022        }
19023
19024        Slog.v(TAG, "reconcileAppsData finished " + preparedCount
19025                + " packages; restoreconNeeded was " + restoreconNeeded);
19026    }
19027
19028    /**
19029     * Prepare app data for the given app just after it was installed or
19030     * upgraded. This method carefully only touches users that it's installed
19031     * for, and it forces a restorecon to handle any seinfo changes.
19032     * <p>
19033     * Verifies that directories exist and that ownership and labeling is
19034     * correct for all installed apps. If there is an ownership mismatch, it
19035     * will try recovering system apps by wiping data; third-party app data is
19036     * left intact.
19037     * <p>
19038     * <em>Note: To avoid a deadlock, do not call this method with {@code mPackages} lock held</em>
19039     */
19040    private void prepareAppDataAfterInstallLIF(PackageParser.Package pkg) {
19041        final PackageSetting ps;
19042        synchronized (mPackages) {
19043            ps = mSettings.mPackages.get(pkg.packageName);
19044            mSettings.writeKernelMappingLPr(ps);
19045        }
19046
19047        final UserManager um = mContext.getSystemService(UserManager.class);
19048        for (UserInfo user : um.getUsers()) {
19049            final int flags;
19050            if (um.isUserUnlocked(user.id)) {
19051                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
19052            } else if (um.isUserRunning(user.id)) {
19053                flags = StorageManager.FLAG_STORAGE_DE;
19054            } else {
19055                continue;
19056            }
19057
19058            if (ps.getInstalled(user.id)) {
19059                // Whenever an app changes, force a restorecon of its data
19060                // TODO: when user data is locked, mark that we're still dirty
19061                prepareAppDataLIF(pkg, user.id, flags, true);
19062            }
19063        }
19064    }
19065
19066    /**
19067     * Prepare app data for the given app.
19068     * <p>
19069     * Verifies that directories exist and that ownership and labeling is
19070     * correct for all installed apps. If there is an ownership mismatch, this
19071     * will try recovering system apps by wiping data; third-party app data is
19072     * left intact.
19073     */
19074    private void prepareAppDataLIF(PackageParser.Package pkg, int userId, int flags,
19075            boolean restoreconNeeded) {
19076        if (pkg == null) {
19077            Slog.wtf(TAG, "Package was null!", new Throwable());
19078            return;
19079        }
19080        prepareAppDataLeafLIF(pkg, userId, flags, restoreconNeeded);
19081        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
19082        for (int i = 0; i < childCount; i++) {
19083            prepareAppDataLeafLIF(pkg.childPackages.get(i), userId, flags, restoreconNeeded);
19084        }
19085    }
19086
19087    private void prepareAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags,
19088            boolean restoreconNeeded) {
19089        if (DEBUG_APP_DATA) {
19090            Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x"
19091                    + Integer.toHexString(flags) + (restoreconNeeded ? " restoreconNeeded" : ""));
19092        }
19093
19094        final String volumeUuid = pkg.volumeUuid;
19095        final String packageName = pkg.packageName;
19096        final ApplicationInfo app = pkg.applicationInfo;
19097        final int appId = UserHandle.getAppId(app.uid);
19098
19099        Preconditions.checkNotNull(app.seinfo);
19100
19101        try {
19102            mInstaller.createAppData(volumeUuid, packageName, userId, flags,
19103                    appId, app.seinfo, app.targetSdkVersion);
19104        } catch (InstallerException e) {
19105            if (app.isSystemApp()) {
19106                logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName
19107                        + ", but trying to recover: " + e);
19108                destroyAppDataLeafLIF(pkg, userId, flags);
19109                try {
19110                    mInstaller.createAppData(volumeUuid, packageName, userId, flags,
19111                            appId, app.seinfo, app.targetSdkVersion);
19112                    logCriticalInfo(Log.DEBUG, "Recovery succeeded!");
19113                } catch (InstallerException e2) {
19114                    logCriticalInfo(Log.DEBUG, "Recovery failed!");
19115                }
19116            } else {
19117                Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e);
19118            }
19119        }
19120
19121        if (restoreconNeeded) {
19122            try {
19123                mInstaller.restoreconAppData(volumeUuid, packageName, userId, flags, appId,
19124                        app.seinfo);
19125            } catch (InstallerException e) {
19126                Slog.e(TAG, "Failed to restorecon for " + packageName + ": " + e);
19127            }
19128        }
19129
19130        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
19131            try {
19132                // CE storage is unlocked right now, so read out the inode and
19133                // remember for use later when it's locked
19134                // TODO: mark this structure as dirty so we persist it!
19135                final long ceDataInode = mInstaller.getAppDataInode(volumeUuid, packageName, userId,
19136                        StorageManager.FLAG_STORAGE_CE);
19137                synchronized (mPackages) {
19138                    final PackageSetting ps = mSettings.mPackages.get(packageName);
19139                    if (ps != null) {
19140                        ps.setCeDataInode(ceDataInode, userId);
19141                    }
19142                }
19143            } catch (InstallerException e) {
19144                Slog.e(TAG, "Failed to find inode for " + packageName + ": " + e);
19145            }
19146        }
19147
19148        prepareAppDataContentsLeafLIF(pkg, userId, flags);
19149    }
19150
19151    private void prepareAppDataContentsLIF(PackageParser.Package pkg, int userId, int flags) {
19152        if (pkg == null) {
19153            Slog.wtf(TAG, "Package was null!", new Throwable());
19154            return;
19155        }
19156        prepareAppDataContentsLeafLIF(pkg, userId, flags);
19157        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
19158        for (int i = 0; i < childCount; i++) {
19159            prepareAppDataContentsLeafLIF(pkg.childPackages.get(i), userId, flags);
19160        }
19161    }
19162
19163    private void prepareAppDataContentsLeafLIF(PackageParser.Package pkg, int userId, int flags) {
19164        final String volumeUuid = pkg.volumeUuid;
19165        final String packageName = pkg.packageName;
19166        final ApplicationInfo app = pkg.applicationInfo;
19167
19168        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
19169            // Create a native library symlink only if we have native libraries
19170            // and if the native libraries are 32 bit libraries. We do not provide
19171            // this symlink for 64 bit libraries.
19172            if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) {
19173                final String nativeLibPath = app.nativeLibraryDir;
19174                try {
19175                    mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName,
19176                            nativeLibPath, userId);
19177                } catch (InstallerException e) {
19178                    Slog.e(TAG, "Failed to link native for " + packageName + ": " + e);
19179                }
19180            }
19181        }
19182    }
19183
19184    /**
19185     * For system apps on non-FBE devices, this method migrates any existing
19186     * CE/DE data to match the {@code defaultToDeviceProtectedStorage} flag
19187     * requested by the app.
19188     */
19189    private boolean maybeMigrateAppDataLIF(PackageParser.Package pkg, int userId) {
19190        if (pkg.isSystemApp() && !StorageManager.isFileEncryptedNativeOrEmulated()
19191                && PackageManager.APPLY_DEFAULT_TO_DEVICE_PROTECTED_STORAGE) {
19192            final int storageTarget = pkg.applicationInfo.isDefaultToDeviceProtectedStorage()
19193                    ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE;
19194            try {
19195                mInstaller.migrateAppData(pkg.volumeUuid, pkg.packageName, userId,
19196                        storageTarget);
19197            } catch (InstallerException e) {
19198                logCriticalInfo(Log.WARN,
19199                        "Failed to migrate " + pkg.packageName + ": " + e.getMessage());
19200            }
19201            return true;
19202        } else {
19203            return false;
19204        }
19205    }
19206
19207    public PackageFreezer freezePackage(String packageName, String killReason) {
19208        return new PackageFreezer(packageName, killReason);
19209    }
19210
19211    public PackageFreezer freezePackageForInstall(String packageName, int installFlags,
19212            String killReason) {
19213        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
19214            return new PackageFreezer();
19215        } else {
19216            return freezePackage(packageName, killReason);
19217        }
19218    }
19219
19220    public PackageFreezer freezePackageForDelete(String packageName, int deleteFlags,
19221            String killReason) {
19222        if ((deleteFlags & PackageManager.DELETE_DONT_KILL_APP) != 0) {
19223            return new PackageFreezer();
19224        } else {
19225            return freezePackage(packageName, killReason);
19226        }
19227    }
19228
19229    /**
19230     * Class that freezes and kills the given package upon creation, and
19231     * unfreezes it upon closing. This is typically used when doing surgery on
19232     * app code/data to prevent the app from running while you're working.
19233     */
19234    private class PackageFreezer implements AutoCloseable {
19235        private final String mPackageName;
19236        private final PackageFreezer[] mChildren;
19237
19238        private final boolean mWeFroze;
19239
19240        private final AtomicBoolean mClosed = new AtomicBoolean();
19241        private final CloseGuard mCloseGuard = CloseGuard.get();
19242
19243        /**
19244         * Create and return a stub freezer that doesn't actually do anything,
19245         * typically used when someone requested
19246         * {@link PackageManager#INSTALL_DONT_KILL_APP} or
19247         * {@link PackageManager#DELETE_DONT_KILL_APP}.
19248         */
19249        public PackageFreezer() {
19250            mPackageName = null;
19251            mChildren = null;
19252            mWeFroze = false;
19253            mCloseGuard.open("close");
19254        }
19255
19256        public PackageFreezer(String packageName, String killReason) {
19257            synchronized (mPackages) {
19258                mPackageName = packageName;
19259                mWeFroze = mFrozenPackages.add(mPackageName);
19260
19261                final PackageSetting ps = mSettings.mPackages.get(mPackageName);
19262                if (ps != null) {
19263                    killApplication(ps.name, ps.appId, killReason);
19264                }
19265
19266                final PackageParser.Package p = mPackages.get(packageName);
19267                if (p != null && p.childPackages != null) {
19268                    final int N = p.childPackages.size();
19269                    mChildren = new PackageFreezer[N];
19270                    for (int i = 0; i < N; i++) {
19271                        mChildren[i] = new PackageFreezer(p.childPackages.get(i).packageName,
19272                                killReason);
19273                    }
19274                } else {
19275                    mChildren = null;
19276                }
19277            }
19278            mCloseGuard.open("close");
19279        }
19280
19281        @Override
19282        protected void finalize() throws Throwable {
19283            try {
19284                mCloseGuard.warnIfOpen();
19285                close();
19286            } finally {
19287                super.finalize();
19288            }
19289        }
19290
19291        @Override
19292        public void close() {
19293            mCloseGuard.close();
19294            if (mClosed.compareAndSet(false, true)) {
19295                synchronized (mPackages) {
19296                    if (mWeFroze) {
19297                        mFrozenPackages.remove(mPackageName);
19298                    }
19299
19300                    if (mChildren != null) {
19301                        for (PackageFreezer freezer : mChildren) {
19302                            freezer.close();
19303                        }
19304                    }
19305                }
19306            }
19307        }
19308    }
19309
19310    /**
19311     * Verify that given package is currently frozen.
19312     */
19313    private void checkPackageFrozen(String packageName) {
19314        synchronized (mPackages) {
19315            if (!mFrozenPackages.contains(packageName)) {
19316                Slog.wtf(TAG, "Expected " + packageName + " to be frozen!", new Throwable());
19317            }
19318        }
19319    }
19320
19321    @Override
19322    public int movePackage(final String packageName, final String volumeUuid) {
19323        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
19324
19325        final int moveId = mNextMoveId.getAndIncrement();
19326        mHandler.post(new Runnable() {
19327            @Override
19328            public void run() {
19329                try {
19330                    movePackageInternal(packageName, volumeUuid, moveId);
19331                } catch (PackageManagerException e) {
19332                    Slog.w(TAG, "Failed to move " + packageName, e);
19333                    mMoveCallbacks.notifyStatusChanged(moveId,
19334                            PackageManager.MOVE_FAILED_INTERNAL_ERROR);
19335                }
19336            }
19337        });
19338        return moveId;
19339    }
19340
19341    private void movePackageInternal(final String packageName, final String volumeUuid,
19342            final int moveId) throws PackageManagerException {
19343        final UserHandle user = new UserHandle(UserHandle.getCallingUserId());
19344        final StorageManager storage = mContext.getSystemService(StorageManager.class);
19345        final PackageManager pm = mContext.getPackageManager();
19346
19347        final boolean currentAsec;
19348        final String currentVolumeUuid;
19349        final File codeFile;
19350        final String installerPackageName;
19351        final String packageAbiOverride;
19352        final int appId;
19353        final String seinfo;
19354        final String label;
19355        final int targetSdkVersion;
19356        final PackageFreezer freezer;
19357
19358        // reader
19359        synchronized (mPackages) {
19360            final PackageParser.Package pkg = mPackages.get(packageName);
19361            final PackageSetting ps = mSettings.mPackages.get(packageName);
19362            if (pkg == null || ps == null) {
19363                throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package");
19364            }
19365
19366            if (pkg.applicationInfo.isSystemApp()) {
19367                throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE,
19368                        "Cannot move system application");
19369            }
19370
19371            if (pkg.applicationInfo.isExternalAsec()) {
19372                currentAsec = true;
19373                currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL;
19374            } else if (pkg.applicationInfo.isForwardLocked()) {
19375                currentAsec = true;
19376                currentVolumeUuid = "forward_locked";
19377            } else {
19378                currentAsec = false;
19379                currentVolumeUuid = ps.volumeUuid;
19380
19381                final File probe = new File(pkg.codePath);
19382                final File probeOat = new File(probe, "oat");
19383                if (!probe.isDirectory() || !probeOat.isDirectory()) {
19384                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
19385                            "Move only supported for modern cluster style installs");
19386                }
19387            }
19388
19389            if (Objects.equals(currentVolumeUuid, volumeUuid)) {
19390                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
19391                        "Package already moved to " + volumeUuid);
19392            }
19393            if (pkg.applicationInfo.isInternal() && isPackageDeviceAdminOnAnyUser(packageName)) {
19394                throw new PackageManagerException(MOVE_FAILED_DEVICE_ADMIN,
19395                        "Device admin cannot be moved");
19396            }
19397
19398            if (mFrozenPackages.contains(packageName)) {
19399                throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING,
19400                        "Failed to move already frozen package");
19401            }
19402
19403            codeFile = new File(pkg.codePath);
19404            installerPackageName = ps.installerPackageName;
19405            packageAbiOverride = ps.cpuAbiOverrideString;
19406            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
19407            seinfo = pkg.applicationInfo.seinfo;
19408            label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo));
19409            targetSdkVersion = pkg.applicationInfo.targetSdkVersion;
19410            freezer = new PackageFreezer(packageName, "movePackageInternal");
19411        }
19412
19413        final Bundle extras = new Bundle();
19414        extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName);
19415        extras.putString(Intent.EXTRA_TITLE, label);
19416        mMoveCallbacks.notifyCreated(moveId, extras);
19417
19418        int installFlags;
19419        final boolean moveCompleteApp;
19420        final File measurePath;
19421
19422        if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) {
19423            installFlags = INSTALL_INTERNAL;
19424            moveCompleteApp = !currentAsec;
19425            measurePath = Environment.getDataAppDirectory(volumeUuid);
19426        } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) {
19427            installFlags = INSTALL_EXTERNAL;
19428            moveCompleteApp = false;
19429            measurePath = storage.getPrimaryPhysicalVolume().getPath();
19430        } else {
19431            final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid);
19432            if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE
19433                    || !volume.isMountedWritable()) {
19434                freezer.close();
19435                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
19436                        "Move location not mounted private volume");
19437            }
19438
19439            Preconditions.checkState(!currentAsec);
19440
19441            installFlags = INSTALL_INTERNAL;
19442            moveCompleteApp = true;
19443            measurePath = Environment.getDataAppDirectory(volumeUuid);
19444        }
19445
19446        final PackageStats stats = new PackageStats(null, -1);
19447        synchronized (mInstaller) {
19448            if (!getPackageSizeInfoLI(packageName, -1, stats)) {
19449                freezer.close();
19450                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
19451                        "Failed to measure package size");
19452            }
19453        }
19454
19455        if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size "
19456                + stats.dataSize);
19457
19458        final long startFreeBytes = measurePath.getFreeSpace();
19459        final long sizeBytes;
19460        if (moveCompleteApp) {
19461            sizeBytes = stats.codeSize + stats.dataSize;
19462        } else {
19463            sizeBytes = stats.codeSize;
19464        }
19465
19466        if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) {
19467            freezer.close();
19468            throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
19469                    "Not enough free space to move");
19470        }
19471
19472        mMoveCallbacks.notifyStatusChanged(moveId, 10);
19473
19474        final CountDownLatch installedLatch = new CountDownLatch(1);
19475        final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
19476            @Override
19477            public void onUserActionRequired(Intent intent) throws RemoteException {
19478                throw new IllegalStateException();
19479            }
19480
19481            @Override
19482            public void onPackageInstalled(String basePackageName, int returnCode, String msg,
19483                    Bundle extras) throws RemoteException {
19484                if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: "
19485                        + PackageManager.installStatusToString(returnCode, msg));
19486
19487                installedLatch.countDown();
19488                freezer.close();
19489
19490                final int status = PackageManager.installStatusToPublicStatus(returnCode);
19491                switch (status) {
19492                    case PackageInstaller.STATUS_SUCCESS:
19493                        mMoveCallbacks.notifyStatusChanged(moveId,
19494                                PackageManager.MOVE_SUCCEEDED);
19495                        break;
19496                    case PackageInstaller.STATUS_FAILURE_STORAGE:
19497                        mMoveCallbacks.notifyStatusChanged(moveId,
19498                                PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
19499                        break;
19500                    default:
19501                        mMoveCallbacks.notifyStatusChanged(moveId,
19502                                PackageManager.MOVE_FAILED_INTERNAL_ERROR);
19503                        break;
19504                }
19505            }
19506        };
19507
19508        final MoveInfo move;
19509        if (moveCompleteApp) {
19510            // Kick off a thread to report progress estimates
19511            new Thread() {
19512                @Override
19513                public void run() {
19514                    while (true) {
19515                        try {
19516                            if (installedLatch.await(1, TimeUnit.SECONDS)) {
19517                                break;
19518                            }
19519                        } catch (InterruptedException ignored) {
19520                        }
19521
19522                        final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace();
19523                        final int progress = 10 + (int) MathUtils.constrain(
19524                                ((deltaFreeBytes * 80) / sizeBytes), 0, 80);
19525                        mMoveCallbacks.notifyStatusChanged(moveId, progress);
19526                    }
19527                }
19528            }.start();
19529
19530            final String dataAppName = codeFile.getName();
19531            move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName,
19532                    dataAppName, appId, seinfo, targetSdkVersion);
19533        } else {
19534            move = null;
19535        }
19536
19537        installFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
19538
19539        final Message msg = mHandler.obtainMessage(INIT_COPY);
19540        final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
19541        final InstallParams params = new InstallParams(origin, move, installObserver, installFlags,
19542                installerPackageName, volumeUuid, null /*verificationInfo*/, user,
19543                packageAbiOverride, null /*grantedPermissions*/, null /*certificates*/);
19544        params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params));
19545        msg.obj = params;
19546
19547        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage",
19548                System.identityHashCode(msg.obj));
19549        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
19550                System.identityHashCode(msg.obj));
19551
19552        mHandler.sendMessage(msg);
19553    }
19554
19555    @Override
19556    public int movePrimaryStorage(String volumeUuid) throws RemoteException {
19557        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
19558
19559        final int realMoveId = mNextMoveId.getAndIncrement();
19560        final Bundle extras = new Bundle();
19561        extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid);
19562        mMoveCallbacks.notifyCreated(realMoveId, extras);
19563
19564        final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() {
19565            @Override
19566            public void onCreated(int moveId, Bundle extras) {
19567                // Ignored
19568            }
19569
19570            @Override
19571            public void onStatusChanged(int moveId, int status, long estMillis) {
19572                mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis);
19573            }
19574        };
19575
19576        final StorageManager storage = mContext.getSystemService(StorageManager.class);
19577        storage.setPrimaryStorageUuid(volumeUuid, callback);
19578        return realMoveId;
19579    }
19580
19581    @Override
19582    public int getMoveStatus(int moveId) {
19583        mContext.enforceCallingOrSelfPermission(
19584                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
19585        return mMoveCallbacks.mLastStatus.get(moveId);
19586    }
19587
19588    @Override
19589    public void registerMoveCallback(IPackageMoveObserver callback) {
19590        mContext.enforceCallingOrSelfPermission(
19591                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
19592        mMoveCallbacks.register(callback);
19593    }
19594
19595    @Override
19596    public void unregisterMoveCallback(IPackageMoveObserver callback) {
19597        mContext.enforceCallingOrSelfPermission(
19598                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
19599        mMoveCallbacks.unregister(callback);
19600    }
19601
19602    @Override
19603    public boolean setInstallLocation(int loc) {
19604        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
19605                null);
19606        if (getInstallLocation() == loc) {
19607            return true;
19608        }
19609        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
19610                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
19611            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
19612                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
19613            return true;
19614        }
19615        return false;
19616   }
19617
19618    @Override
19619    public int getInstallLocation() {
19620        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
19621                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
19622                PackageHelper.APP_INSTALL_AUTO);
19623    }
19624
19625    /** Called by UserManagerService */
19626    void cleanUpUser(UserManagerService userManager, int userHandle) {
19627        synchronized (mPackages) {
19628            mDirtyUsers.remove(userHandle);
19629            mUserNeedsBadging.delete(userHandle);
19630            mSettings.removeUserLPw(userHandle);
19631            mPendingBroadcasts.remove(userHandle);
19632            mEphemeralApplicationRegistry.onUserRemovedLPw(userHandle);
19633            removeUnusedPackagesLPw(userManager, userHandle);
19634        }
19635    }
19636
19637    /**
19638     * We're removing userHandle and would like to remove any downloaded packages
19639     * that are no longer in use by any other user.
19640     * @param userHandle the user being removed
19641     */
19642    private void removeUnusedPackagesLPw(UserManagerService userManager, final int userHandle) {
19643        final boolean DEBUG_CLEAN_APKS = false;
19644        int [] users = userManager.getUserIds();
19645        Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
19646        while (psit.hasNext()) {
19647            PackageSetting ps = psit.next();
19648            if (ps.pkg == null) {
19649                continue;
19650            }
19651            final String packageName = ps.pkg.packageName;
19652            // Skip over if system app
19653            if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
19654                continue;
19655            }
19656            if (DEBUG_CLEAN_APKS) {
19657                Slog.i(TAG, "Checking package " + packageName);
19658            }
19659            boolean keep = shouldKeepUninstalledPackageLPr(packageName);
19660            if (keep) {
19661                if (DEBUG_CLEAN_APKS) {
19662                    Slog.i(TAG, "  Keeping package " + packageName + " - requested by DO");
19663                }
19664            } else {
19665                for (int i = 0; i < users.length; i++) {
19666                    if (users[i] != userHandle && ps.getInstalled(users[i])) {
19667                        keep = true;
19668                        if (DEBUG_CLEAN_APKS) {
19669                            Slog.i(TAG, "  Keeping package " + packageName + " for user "
19670                                    + users[i]);
19671                        }
19672                        break;
19673                    }
19674                }
19675            }
19676            if (!keep) {
19677                if (DEBUG_CLEAN_APKS) {
19678                    Slog.i(TAG, "  Removing package " + packageName);
19679                }
19680                mHandler.post(new Runnable() {
19681                    public void run() {
19682                        deletePackageX(packageName, userHandle, 0);
19683                    } //end run
19684                });
19685            }
19686        }
19687    }
19688
19689    /** Called by UserManagerService */
19690    void createNewUser(int userHandle) {
19691        synchronized (mInstallLock) {
19692            mSettings.createNewUserLI(this, mInstaller, userHandle);
19693        }
19694        synchronized (mPackages) {
19695            applyFactoryDefaultBrowserLPw(userHandle);
19696            primeDomainVerificationsLPw(userHandle);
19697        }
19698    }
19699
19700    void newUserCreated(final int userHandle) {
19701        mDefaultPermissionPolicy.grantDefaultPermissions(userHandle);
19702        // If permission review for legacy apps is required, we represent
19703        // dagerous permissions for such apps as always granted runtime
19704        // permissions to keep per user flag state whether review is needed.
19705        // Hence, if a new user is added we have to propagate dangerous
19706        // permission grants for these legacy apps.
19707        if (Build.PERMISSIONS_REVIEW_REQUIRED) {
19708            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
19709                    | UPDATE_PERMISSIONS_REPLACE_ALL);
19710        }
19711    }
19712
19713    @Override
19714    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
19715        mContext.enforceCallingOrSelfPermission(
19716                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
19717                "Only package verification agents can read the verifier device identity");
19718
19719        synchronized (mPackages) {
19720            return mSettings.getVerifierDeviceIdentityLPw();
19721        }
19722    }
19723
19724    @Override
19725    public void setPermissionEnforced(String permission, boolean enforced) {
19726        // TODO: Now that we no longer change GID for storage, this should to away.
19727        mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
19728                "setPermissionEnforced");
19729        if (READ_EXTERNAL_STORAGE.equals(permission)) {
19730            synchronized (mPackages) {
19731                if (mSettings.mReadExternalStorageEnforced == null
19732                        || mSettings.mReadExternalStorageEnforced != enforced) {
19733                    mSettings.mReadExternalStorageEnforced = enforced;
19734                    mSettings.writeLPr();
19735                }
19736            }
19737            // kill any non-foreground processes so we restart them and
19738            // grant/revoke the GID.
19739            final IActivityManager am = ActivityManagerNative.getDefault();
19740            if (am != null) {
19741                final long token = Binder.clearCallingIdentity();
19742                try {
19743                    am.killProcessesBelowForeground("setPermissionEnforcement");
19744                } catch (RemoteException e) {
19745                } finally {
19746                    Binder.restoreCallingIdentity(token);
19747                }
19748            }
19749        } else {
19750            throw new IllegalArgumentException("No selective enforcement for " + permission);
19751        }
19752    }
19753
19754    @Override
19755    @Deprecated
19756    public boolean isPermissionEnforced(String permission) {
19757        return true;
19758    }
19759
19760    @Override
19761    public boolean isStorageLow() {
19762        final long token = Binder.clearCallingIdentity();
19763        try {
19764            final DeviceStorageMonitorInternal
19765                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
19766            if (dsm != null) {
19767                return dsm.isMemoryLow();
19768            } else {
19769                return false;
19770            }
19771        } finally {
19772            Binder.restoreCallingIdentity(token);
19773        }
19774    }
19775
19776    @Override
19777    public IPackageInstaller getPackageInstaller() {
19778        return mInstallerService;
19779    }
19780
19781    private boolean userNeedsBadging(int userId) {
19782        int index = mUserNeedsBadging.indexOfKey(userId);
19783        if (index < 0) {
19784            final UserInfo userInfo;
19785            final long token = Binder.clearCallingIdentity();
19786            try {
19787                userInfo = sUserManager.getUserInfo(userId);
19788            } finally {
19789                Binder.restoreCallingIdentity(token);
19790            }
19791            final boolean b;
19792            if (userInfo != null && userInfo.isManagedProfile()) {
19793                b = true;
19794            } else {
19795                b = false;
19796            }
19797            mUserNeedsBadging.put(userId, b);
19798            return b;
19799        }
19800        return mUserNeedsBadging.valueAt(index);
19801    }
19802
19803    @Override
19804    public KeySet getKeySetByAlias(String packageName, String alias) {
19805        if (packageName == null || alias == null) {
19806            return null;
19807        }
19808        synchronized(mPackages) {
19809            final PackageParser.Package pkg = mPackages.get(packageName);
19810            if (pkg == null) {
19811                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
19812                throw new IllegalArgumentException("Unknown package: " + packageName);
19813            }
19814            KeySetManagerService ksms = mSettings.mKeySetManagerService;
19815            return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
19816        }
19817    }
19818
19819    @Override
19820    public KeySet getSigningKeySet(String packageName) {
19821        if (packageName == null) {
19822            return null;
19823        }
19824        synchronized(mPackages) {
19825            final PackageParser.Package pkg = mPackages.get(packageName);
19826            if (pkg == null) {
19827                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
19828                throw new IllegalArgumentException("Unknown package: " + packageName);
19829            }
19830            if (pkg.applicationInfo.uid != Binder.getCallingUid()
19831                    && Process.SYSTEM_UID != Binder.getCallingUid()) {
19832                throw new SecurityException("May not access signing KeySet of other apps.");
19833            }
19834            KeySetManagerService ksms = mSettings.mKeySetManagerService;
19835            return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
19836        }
19837    }
19838
19839    @Override
19840    public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
19841        if (packageName == null || ks == null) {
19842            return false;
19843        }
19844        synchronized(mPackages) {
19845            final PackageParser.Package pkg = mPackages.get(packageName);
19846            if (pkg == null) {
19847                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
19848                throw new IllegalArgumentException("Unknown package: " + packageName);
19849            }
19850            IBinder ksh = ks.getToken();
19851            if (ksh instanceof KeySetHandle) {
19852                KeySetManagerService ksms = mSettings.mKeySetManagerService;
19853                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
19854            }
19855            return false;
19856        }
19857    }
19858
19859    @Override
19860    public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
19861        if (packageName == null || ks == null) {
19862            return false;
19863        }
19864        synchronized(mPackages) {
19865            final PackageParser.Package pkg = mPackages.get(packageName);
19866            if (pkg == null) {
19867                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
19868                throw new IllegalArgumentException("Unknown package: " + packageName);
19869            }
19870            IBinder ksh = ks.getToken();
19871            if (ksh instanceof KeySetHandle) {
19872                KeySetManagerService ksms = mSettings.mKeySetManagerService;
19873                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
19874            }
19875            return false;
19876        }
19877    }
19878
19879    private void deletePackageIfUnusedLPr(final String packageName) {
19880        PackageSetting ps = mSettings.mPackages.get(packageName);
19881        if (ps == null) {
19882            return;
19883        }
19884        if (!ps.isAnyInstalled(sUserManager.getUserIds())) {
19885            // TODO Implement atomic delete if package is unused
19886            // It is currently possible that the package will be deleted even if it is installed
19887            // after this method returns.
19888            mHandler.post(new Runnable() {
19889                public void run() {
19890                    deletePackageX(packageName, 0, PackageManager.DELETE_ALL_USERS);
19891                }
19892            });
19893        }
19894    }
19895
19896    /**
19897     * Check and throw if the given before/after packages would be considered a
19898     * downgrade.
19899     */
19900    private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after)
19901            throws PackageManagerException {
19902        if (after.versionCode < before.mVersionCode) {
19903            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
19904                    "Update version code " + after.versionCode + " is older than current "
19905                    + before.mVersionCode);
19906        } else if (after.versionCode == before.mVersionCode) {
19907            if (after.baseRevisionCode < before.baseRevisionCode) {
19908                throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
19909                        "Update base revision code " + after.baseRevisionCode
19910                        + " is older than current " + before.baseRevisionCode);
19911            }
19912
19913            if (!ArrayUtils.isEmpty(after.splitNames)) {
19914                for (int i = 0; i < after.splitNames.length; i++) {
19915                    final String splitName = after.splitNames[i];
19916                    final int j = ArrayUtils.indexOf(before.splitNames, splitName);
19917                    if (j != -1) {
19918                        if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) {
19919                            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
19920                                    "Update split " + splitName + " revision code "
19921                                    + after.splitRevisionCodes[i] + " is older than current "
19922                                    + before.splitRevisionCodes[j]);
19923                        }
19924                    }
19925                }
19926            }
19927        }
19928    }
19929
19930    private static class MoveCallbacks extends Handler {
19931        private static final int MSG_CREATED = 1;
19932        private static final int MSG_STATUS_CHANGED = 2;
19933
19934        private final RemoteCallbackList<IPackageMoveObserver>
19935                mCallbacks = new RemoteCallbackList<>();
19936
19937        private final SparseIntArray mLastStatus = new SparseIntArray();
19938
19939        public MoveCallbacks(Looper looper) {
19940            super(looper);
19941        }
19942
19943        public void register(IPackageMoveObserver callback) {
19944            mCallbacks.register(callback);
19945        }
19946
19947        public void unregister(IPackageMoveObserver callback) {
19948            mCallbacks.unregister(callback);
19949        }
19950
19951        @Override
19952        public void handleMessage(Message msg) {
19953            final SomeArgs args = (SomeArgs) msg.obj;
19954            final int n = mCallbacks.beginBroadcast();
19955            for (int i = 0; i < n; i++) {
19956                final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i);
19957                try {
19958                    invokeCallback(callback, msg.what, args);
19959                } catch (RemoteException ignored) {
19960                }
19961            }
19962            mCallbacks.finishBroadcast();
19963            args.recycle();
19964        }
19965
19966        private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args)
19967                throws RemoteException {
19968            switch (what) {
19969                case MSG_CREATED: {
19970                    callback.onCreated(args.argi1, (Bundle) args.arg2);
19971                    break;
19972                }
19973                case MSG_STATUS_CHANGED: {
19974                    callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3);
19975                    break;
19976                }
19977            }
19978        }
19979
19980        private void notifyCreated(int moveId, Bundle extras) {
19981            Slog.v(TAG, "Move " + moveId + " created " + extras.toString());
19982
19983            final SomeArgs args = SomeArgs.obtain();
19984            args.argi1 = moveId;
19985            args.arg2 = extras;
19986            obtainMessage(MSG_CREATED, args).sendToTarget();
19987        }
19988
19989        private void notifyStatusChanged(int moveId, int status) {
19990            notifyStatusChanged(moveId, status, -1);
19991        }
19992
19993        private void notifyStatusChanged(int moveId, int status, long estMillis) {
19994            Slog.v(TAG, "Move " + moveId + " status " + status);
19995
19996            final SomeArgs args = SomeArgs.obtain();
19997            args.argi1 = moveId;
19998            args.argi2 = status;
19999            args.arg3 = estMillis;
20000            obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget();
20001
20002            synchronized (mLastStatus) {
20003                mLastStatus.put(moveId, status);
20004            }
20005        }
20006    }
20007
20008    private final static class OnPermissionChangeListeners extends Handler {
20009        private static final int MSG_ON_PERMISSIONS_CHANGED = 1;
20010
20011        private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners =
20012                new RemoteCallbackList<>();
20013
20014        public OnPermissionChangeListeners(Looper looper) {
20015            super(looper);
20016        }
20017
20018        @Override
20019        public void handleMessage(Message msg) {
20020            switch (msg.what) {
20021                case MSG_ON_PERMISSIONS_CHANGED: {
20022                    final int uid = msg.arg1;
20023                    handleOnPermissionsChanged(uid);
20024                } break;
20025            }
20026        }
20027
20028        public void addListenerLocked(IOnPermissionsChangeListener listener) {
20029            mPermissionListeners.register(listener);
20030
20031        }
20032
20033        public void removeListenerLocked(IOnPermissionsChangeListener listener) {
20034            mPermissionListeners.unregister(listener);
20035        }
20036
20037        public void onPermissionsChanged(int uid) {
20038            if (mPermissionListeners.getRegisteredCallbackCount() > 0) {
20039                obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget();
20040            }
20041        }
20042
20043        private void handleOnPermissionsChanged(int uid) {
20044            final int count = mPermissionListeners.beginBroadcast();
20045            try {
20046                for (int i = 0; i < count; i++) {
20047                    IOnPermissionsChangeListener callback = mPermissionListeners
20048                            .getBroadcastItem(i);
20049                    try {
20050                        callback.onPermissionsChanged(uid);
20051                    } catch (RemoteException e) {
20052                        Log.e(TAG, "Permission listener is dead", e);
20053                    }
20054                }
20055            } finally {
20056                mPermissionListeners.finishBroadcast();
20057            }
20058        }
20059    }
20060
20061    private class PackageManagerInternalImpl extends PackageManagerInternal {
20062        @Override
20063        public void setLocationPackagesProvider(PackagesProvider provider) {
20064            synchronized (mPackages) {
20065                mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider);
20066            }
20067        }
20068
20069        @Override
20070        public void setVoiceInteractionPackagesProvider(PackagesProvider provider) {
20071            synchronized (mPackages) {
20072                mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider);
20073            }
20074        }
20075
20076        @Override
20077        public void setSmsAppPackagesProvider(PackagesProvider provider) {
20078            synchronized (mPackages) {
20079                mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider);
20080            }
20081        }
20082
20083        @Override
20084        public void setDialerAppPackagesProvider(PackagesProvider provider) {
20085            synchronized (mPackages) {
20086                mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider);
20087            }
20088        }
20089
20090        @Override
20091        public void setSimCallManagerPackagesProvider(PackagesProvider provider) {
20092            synchronized (mPackages) {
20093                mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider);
20094            }
20095        }
20096
20097        @Override
20098        public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) {
20099            synchronized (mPackages) {
20100                mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider);
20101            }
20102        }
20103
20104        @Override
20105        public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) {
20106            synchronized (mPackages) {
20107                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr(
20108                        packageName, userId);
20109            }
20110        }
20111
20112        @Override
20113        public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) {
20114            synchronized (mPackages) {
20115                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr(
20116                        packageName, userId);
20117            }
20118        }
20119
20120        @Override
20121        public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) {
20122            synchronized (mPackages) {
20123                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr(
20124                        packageName, userId);
20125            }
20126        }
20127
20128        @Override
20129        public void setKeepUninstalledPackages(final List<String> packageList) {
20130            Preconditions.checkNotNull(packageList);
20131            List<String> removedFromList = null;
20132            synchronized (mPackages) {
20133                if (mKeepUninstalledPackages != null) {
20134                    final int packagesCount = mKeepUninstalledPackages.size();
20135                    for (int i = 0; i < packagesCount; i++) {
20136                        String oldPackage = mKeepUninstalledPackages.get(i);
20137                        if (packageList != null && packageList.contains(oldPackage)) {
20138                            continue;
20139                        }
20140                        if (removedFromList == null) {
20141                            removedFromList = new ArrayList<>();
20142                        }
20143                        removedFromList.add(oldPackage);
20144                    }
20145                }
20146                mKeepUninstalledPackages = new ArrayList<>(packageList);
20147                if (removedFromList != null) {
20148                    final int removedCount = removedFromList.size();
20149                    for (int i = 0; i < removedCount; i++) {
20150                        deletePackageIfUnusedLPr(removedFromList.get(i));
20151                    }
20152                }
20153            }
20154        }
20155
20156        @Override
20157        public boolean isPermissionsReviewRequired(String packageName, int userId) {
20158            synchronized (mPackages) {
20159                // If we do not support permission review, done.
20160                if (!Build.PERMISSIONS_REVIEW_REQUIRED) {
20161                    return false;
20162                }
20163
20164                PackageSetting packageSetting = mSettings.mPackages.get(packageName);
20165                if (packageSetting == null) {
20166                    return false;
20167                }
20168
20169                // Permission review applies only to apps not supporting the new permission model.
20170                if (packageSetting.pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.M) {
20171                    return false;
20172                }
20173
20174                // Legacy apps have the permission and get user consent on launch.
20175                PermissionsState permissionsState = packageSetting.getPermissionsState();
20176                return permissionsState.isPermissionReviewRequired(userId);
20177            }
20178        }
20179
20180        @Override
20181        public ApplicationInfo getApplicationInfo(String packageName, int userId) {
20182            return PackageManagerService.this.getApplicationInfo(packageName, 0 /*flags*/, userId);
20183        }
20184
20185        @Override
20186        public ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
20187                int userId) {
20188            return PackageManagerService.this.getHomeActivitiesAsUser(allHomeCandidates, userId);
20189        }
20190    }
20191
20192    @Override
20193    public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) {
20194        enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps");
20195        synchronized (mPackages) {
20196            final long identity = Binder.clearCallingIdentity();
20197            try {
20198                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr(
20199                        packageNames, userId);
20200            } finally {
20201                Binder.restoreCallingIdentity(identity);
20202            }
20203        }
20204    }
20205
20206    private static void enforceSystemOrPhoneCaller(String tag) {
20207        int callingUid = Binder.getCallingUid();
20208        if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) {
20209            throw new SecurityException(
20210                    "Cannot call " + tag + " from UID " + callingUid);
20211        }
20212    }
20213
20214    boolean isHistoricalPackageUsageAvailable() {
20215        return mPackageUsage.isHistoricalPackageUsageAvailable();
20216    }
20217
20218    /**
20219     * Return a <b>copy</b> of the collection of packages known to the package manager.
20220     * @return A copy of the values of mPackages.
20221     */
20222    Collection<PackageParser.Package> getPackages() {
20223        synchronized (mPackages) {
20224            return new ArrayList<>(mPackages.values());
20225        }
20226    }
20227
20228    /**
20229     * Logs process start information (including base APK hash) to the security log.
20230     * @hide
20231     */
20232    public void logAppProcessStartIfNeeded(String processName, int uid, String seinfo,
20233            String apkFile, int pid) {
20234        if (!SecurityLog.isLoggingEnabled()) {
20235            return;
20236        }
20237        Bundle data = new Bundle();
20238        data.putLong("startTimestamp", System.currentTimeMillis());
20239        data.putString("processName", processName);
20240        data.putInt("uid", uid);
20241        data.putString("seinfo", seinfo);
20242        data.putString("apkFile", apkFile);
20243        data.putInt("pid", pid);
20244        Message msg = mProcessLoggingHandler.obtainMessage(
20245                ProcessLoggingHandler.LOG_APP_PROCESS_START_MSG);
20246        msg.setData(data);
20247        mProcessLoggingHandler.sendMessage(msg);
20248    }
20249}
20250