PackageManagerService.java revision 3d92f4ea37e6785605a8d62f1971f2dfe4569638
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 PLATFORM_PACKAGE_NAME = "android";
441
442    static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer";
443
444    static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
445            DEFAULT_CONTAINER_PACKAGE,
446            "com.android.defcontainer.DefaultContainerService");
447
448    private static final String KILL_APP_REASON_GIDS_CHANGED =
449            "permission grant or revoke changed gids";
450
451    private static final String KILL_APP_REASON_PERMISSIONS_REVOKED =
452            "permissions revoked";
453
454    private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive";
455
456    private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay";
457
458    /** Permission grant: not grant the permission. */
459    private static final int GRANT_DENIED = 1;
460
461    /** Permission grant: grant the permission as an install permission. */
462    private static final int GRANT_INSTALL = 2;
463
464    /** Permission grant: grant the permission as a runtime one. */
465    private static final int GRANT_RUNTIME = 3;
466
467    /** Permission grant: grant as runtime a permission that was granted as an install time one. */
468    private static final int GRANT_UPGRADE = 4;
469
470    /** Canonical intent used to identify what counts as a "web browser" app */
471    private static final Intent sBrowserIntent;
472    static {
473        sBrowserIntent = new Intent();
474        sBrowserIntent.setAction(Intent.ACTION_VIEW);
475        sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE);
476        sBrowserIntent.setData(Uri.parse("http:"));
477    }
478
479    /**
480     * The set of all protected actions [i.e. those actions for which a high priority
481     * intent filter is disallowed].
482     */
483    private static final Set<String> PROTECTED_ACTIONS = new ArraySet<>();
484    static {
485        PROTECTED_ACTIONS.add(Intent.ACTION_SEND);
486        PROTECTED_ACTIONS.add(Intent.ACTION_SENDTO);
487        PROTECTED_ACTIONS.add(Intent.ACTION_SEND_MULTIPLE);
488        PROTECTED_ACTIONS.add(Intent.ACTION_VIEW);
489    }
490
491    // Compilation reasons.
492    public static final int REASON_FIRST_BOOT = 0;
493    public static final int REASON_BOOT = 1;
494    public static final int REASON_INSTALL = 2;
495    public static final int REASON_BACKGROUND_DEXOPT = 3;
496    public static final int REASON_AB_OTA = 4;
497    public static final int REASON_NON_SYSTEM_LIBRARY = 5;
498    public static final int REASON_SHARED_APK = 6;
499    public static final int REASON_FORCED_DEXOPT = 7;
500
501    public static final int REASON_LAST = REASON_FORCED_DEXOPT;
502
503    final ServiceThread mHandlerThread;
504
505    final PackageHandler mHandler;
506
507    private final ProcessLoggingHandler mProcessLoggingHandler;
508
509    /**
510     * Messages for {@link #mHandler} that need to wait for system ready before
511     * being dispatched.
512     */
513    private ArrayList<Message> mPostSystemReadyMessages;
514
515    final int mSdkVersion = Build.VERSION.SDK_INT;
516
517    final Context mContext;
518    final boolean mFactoryTest;
519    final boolean mOnlyCore;
520    final DisplayMetrics mMetrics;
521    final int mDefParseFlags;
522    final String[] mSeparateProcesses;
523    final boolean mIsUpgrade;
524    final boolean mIsPreNUpgrade;
525
526    /** The location for ASEC container files on internal storage. */
527    final String mAsecInternalPath;
528
529    // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages
530    // LOCK HELD.  Can be called with mInstallLock held.
531    @GuardedBy("mInstallLock")
532    final Installer mInstaller;
533
534    /** Directory where installed third-party apps stored */
535    final File mAppInstallDir;
536    final File mEphemeralInstallDir;
537
538    /**
539     * Directory to which applications installed internally have their
540     * 32 bit native libraries copied.
541     */
542    private File mAppLib32InstallDir;
543
544    // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked
545    // apps.
546    final File mDrmAppPrivateInstallDir;
547
548    // ----------------------------------------------------------------
549
550    // Lock for state used when installing and doing other long running
551    // operations.  Methods that must be called with this lock held have
552    // the suffix "LI".
553    final Object mInstallLock = new Object();
554
555    // ----------------------------------------------------------------
556
557    // Keys are String (package name), values are Package.  This also serves
558    // as the lock for the global state.  Methods that must be called with
559    // this lock held have the prefix "LP".
560    @GuardedBy("mPackages")
561    final ArrayMap<String, PackageParser.Package> mPackages =
562            new ArrayMap<String, PackageParser.Package>();
563
564    final ArrayMap<String, Set<String>> mKnownCodebase =
565            new ArrayMap<String, Set<String>>();
566
567    // Tracks available target package names -> overlay package paths.
568    final ArrayMap<String, ArrayMap<String, PackageParser.Package>> mOverlays =
569        new ArrayMap<String, ArrayMap<String, PackageParser.Package>>();
570
571    /**
572     * Tracks new system packages [received in an OTA] that we expect to
573     * find updated user-installed versions. Keys are package name, values
574     * are package location.
575     */
576    final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>();
577    /**
578     * Tracks high priority intent filters for protected actions. During boot, certain
579     * filter actions are protected and should never be allowed to have a high priority
580     * intent filter for them. However, there is one, and only one exception -- the
581     * setup wizard. It must be able to define a high priority intent filter for these
582     * actions to ensure there are no escapes from the wizard. We need to delay processing
583     * of these during boot as we need to look at all of the system packages in order
584     * to know which component is the setup wizard.
585     */
586    private final List<PackageParser.ActivityIntentInfo> mProtectedFilters = new ArrayList<>();
587    /**
588     * Whether or not processing protected filters should be deferred.
589     */
590    private boolean mDeferProtectedFilters = true;
591
592    /**
593     * Tracks existing system packages prior to receiving an OTA. Keys are package name.
594     */
595    final private ArraySet<String> mExistingSystemPackages = new ArraySet<>();
596    /**
597     * Whether or not system app permissions should be promoted from install to runtime.
598     */
599    boolean mPromoteSystemApps;
600
601    @GuardedBy("mPackages")
602    final Settings mSettings;
603
604    /**
605     * Set of package names that are currently "frozen", which means active
606     * surgery is being done on the code/data for that package. The platform
607     * will refuse to launch frozen packages to avoid race conditions.
608     *
609     * @see PackageFreezer
610     */
611    @GuardedBy("mPackages")
612    final ArraySet<String> mFrozenPackages = new ArraySet<>();
613
614    boolean mRestoredSettings;
615
616    // System configuration read by SystemConfig.
617    final int[] mGlobalGids;
618    final SparseArray<ArraySet<String>> mSystemPermissions;
619    final ArrayMap<String, FeatureInfo> mAvailableFeatures;
620
621    // If mac_permissions.xml was found for seinfo labeling.
622    boolean mFoundPolicyFile;
623
624    private final EphemeralApplicationRegistry mEphemeralApplicationRegistry;
625
626    public static final class SharedLibraryEntry {
627        public final String path;
628        public final String apk;
629
630        SharedLibraryEntry(String _path, String _apk) {
631            path = _path;
632            apk = _apk;
633        }
634    }
635
636    // Currently known shared libraries.
637    final ArrayMap<String, SharedLibraryEntry> mSharedLibraries =
638            new ArrayMap<String, SharedLibraryEntry>();
639
640    // All available activities, for your resolving pleasure.
641    final ActivityIntentResolver mActivities =
642            new ActivityIntentResolver();
643
644    // All available receivers, for your resolving pleasure.
645    final ActivityIntentResolver mReceivers =
646            new ActivityIntentResolver();
647
648    // All available services, for your resolving pleasure.
649    final ServiceIntentResolver mServices = new ServiceIntentResolver();
650
651    // All available providers, for your resolving pleasure.
652    final ProviderIntentResolver mProviders = new ProviderIntentResolver();
653
654    // Mapping from provider base names (first directory in content URI codePath)
655    // to the provider information.
656    final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority =
657            new ArrayMap<String, PackageParser.Provider>();
658
659    // Mapping from instrumentation class names to info about them.
660    final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
661            new ArrayMap<ComponentName, PackageParser.Instrumentation>();
662
663    // Mapping from permission names to info about them.
664    final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups =
665            new ArrayMap<String, PackageParser.PermissionGroup>();
666
667    // Packages whose data we have transfered into another package, thus
668    // should no longer exist.
669    final ArraySet<String> mTransferedPackages = new ArraySet<String>();
670
671    // Broadcast actions that are only available to the system.
672    final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>();
673
674    /** List of packages waiting for verification. */
675    final SparseArray<PackageVerificationState> mPendingVerification
676            = new SparseArray<PackageVerificationState>();
677
678    /** Set of packages associated with each app op permission. */
679    final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>();
680
681    final PackageInstallerService mInstallerService;
682
683    private final PackageDexOptimizer mPackageDexOptimizer;
684
685    private AtomicInteger mNextMoveId = new AtomicInteger();
686    private final MoveCallbacks mMoveCallbacks;
687
688    private final OnPermissionChangeListeners mOnPermissionChangeListeners;
689
690    // Cache of users who need badging.
691    SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray();
692
693    /** Token for keys in mPendingVerification. */
694    private int mPendingVerificationToken = 0;
695
696    volatile boolean mSystemReady;
697    volatile boolean mSafeMode;
698    volatile boolean mHasSystemUidErrors;
699
700    ApplicationInfo mAndroidApplication;
701    final ActivityInfo mResolveActivity = new ActivityInfo();
702    final ResolveInfo mResolveInfo = new ResolveInfo();
703    ComponentName mResolveComponentName;
704    PackageParser.Package mPlatformPackage;
705    ComponentName mCustomResolverComponentName;
706
707    boolean mResolverReplaced = false;
708
709    private final @Nullable ComponentName mIntentFilterVerifierComponent;
710    private final @Nullable IntentFilterVerifier<ActivityIntentInfo> mIntentFilterVerifier;
711
712    private int mIntentFilterVerificationToken = 0;
713
714    /** Component that knows whether or not an ephemeral application exists */
715    final ComponentName mEphemeralResolverComponent;
716    /** The service connection to the ephemeral resolver */
717    final EphemeralResolverConnection mEphemeralResolverConnection;
718
719    /** Component used to install ephemeral applications */
720    final ComponentName mEphemeralInstallerComponent;
721    final ActivityInfo mEphemeralInstallerActivity = new ActivityInfo();
722    final ResolveInfo mEphemeralInstallerInfo = new ResolveInfo();
723
724    final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates
725            = new SparseArray<IntentFilterVerificationState>();
726
727    final DefaultPermissionGrantPolicy mDefaultPermissionPolicy =
728            new DefaultPermissionGrantPolicy(this);
729
730    // List of packages names to keep cached, even if they are uninstalled for all users
731    private List<String> mKeepUninstalledPackages;
732
733    private static class IFVerificationParams {
734        PackageParser.Package pkg;
735        boolean replacing;
736        int userId;
737        int verifierUid;
738
739        public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing,
740                int _userId, int _verifierUid) {
741            pkg = _pkg;
742            replacing = _replacing;
743            userId = _userId;
744            replacing = _replacing;
745            verifierUid = _verifierUid;
746        }
747    }
748
749    private interface IntentFilterVerifier<T extends IntentFilter> {
750        boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId,
751                                               T filter, String packageName);
752        void startVerifications(int userId);
753        void receiveVerificationResponse(int verificationId);
754    }
755
756    private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> {
757        private Context mContext;
758        private ComponentName mIntentFilterVerifierComponent;
759        private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>();
760
761        public IntentVerifierProxy(Context context, ComponentName verifierComponent) {
762            mContext = context;
763            mIntentFilterVerifierComponent = verifierComponent;
764        }
765
766        private String getDefaultScheme() {
767            return IntentFilter.SCHEME_HTTPS;
768        }
769
770        @Override
771        public void startVerifications(int userId) {
772            // Launch verifications requests
773            int count = mCurrentIntentFilterVerifications.size();
774            for (int n=0; n<count; n++) {
775                int verificationId = mCurrentIntentFilterVerifications.get(n);
776                final IntentFilterVerificationState ivs =
777                        mIntentFilterVerificationStates.get(verificationId);
778
779                String packageName = ivs.getPackageName();
780
781                ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
782                final int filterCount = filters.size();
783                ArraySet<String> domainsSet = new ArraySet<>();
784                for (int m=0; m<filterCount; m++) {
785                    PackageParser.ActivityIntentInfo filter = filters.get(m);
786                    domainsSet.addAll(filter.getHostsList());
787                }
788                ArrayList<String> domainsList = new ArrayList<>(domainsSet);
789                synchronized (mPackages) {
790                    if (mSettings.createIntentFilterVerificationIfNeededLPw(
791                            packageName, domainsList) != null) {
792                        scheduleWriteSettingsLocked();
793                    }
794                }
795                sendVerificationRequest(userId, verificationId, ivs);
796            }
797            mCurrentIntentFilterVerifications.clear();
798        }
799
800        private void sendVerificationRequest(int userId, int verificationId,
801                IntentFilterVerificationState ivs) {
802
803            Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
804            verificationIntent.putExtra(
805                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID,
806                    verificationId);
807            verificationIntent.putExtra(
808                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME,
809                    getDefaultScheme());
810            verificationIntent.putExtra(
811                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS,
812                    ivs.getHostsString());
813            verificationIntent.putExtra(
814                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME,
815                    ivs.getPackageName());
816            verificationIntent.setComponent(mIntentFilterVerifierComponent);
817            verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
818
819            UserHandle user = new UserHandle(userId);
820            mContext.sendBroadcastAsUser(verificationIntent, user);
821            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
822                    "Sending IntentFilter verification broadcast");
823        }
824
825        public void receiveVerificationResponse(int verificationId) {
826            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
827
828            final boolean verified = ivs.isVerified();
829
830            ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
831            final int count = filters.size();
832            if (DEBUG_DOMAIN_VERIFICATION) {
833                Slog.i(TAG, "Received verification response " + verificationId
834                        + " for " + count + " filters, verified=" + verified);
835            }
836            for (int n=0; n<count; n++) {
837                PackageParser.ActivityIntentInfo filter = filters.get(n);
838                filter.setVerified(verified);
839
840                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString()
841                        + " verified with result:" + verified + " and hosts:"
842                        + ivs.getHostsString());
843            }
844
845            mIntentFilterVerificationStates.remove(verificationId);
846
847            final String packageName = ivs.getPackageName();
848            IntentFilterVerificationInfo ivi = null;
849
850            synchronized (mPackages) {
851                ivi = mSettings.getIntentFilterVerificationLPr(packageName);
852            }
853            if (ivi == null) {
854                Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:"
855                        + verificationId + " packageName:" + packageName);
856                return;
857            }
858            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
859                    "Updating IntentFilterVerificationInfo for package " + packageName
860                            +" verificationId:" + verificationId);
861
862            synchronized (mPackages) {
863                if (verified) {
864                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS);
865                } else {
866                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK);
867                }
868                scheduleWriteSettingsLocked();
869
870                final int userId = ivs.getUserId();
871                if (userId != UserHandle.USER_ALL) {
872                    final int userStatus =
873                            mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
874
875                    int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
876                    boolean needUpdate = false;
877
878                    // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have
879                    // already been set by the User thru the Disambiguation dialog
880                    switch (userStatus) {
881                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
882                            if (verified) {
883                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
884                            } else {
885                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
886                            }
887                            needUpdate = true;
888                            break;
889
890                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
891                            if (verified) {
892                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
893                                needUpdate = true;
894                            }
895                            break;
896
897                        default:
898                            // Nothing to do
899                    }
900
901                    if (needUpdate) {
902                        mSettings.updateIntentFilterVerificationStatusLPw(
903                                packageName, updatedStatus, userId);
904                        scheduleWritePackageRestrictionsLocked(userId);
905                    }
906                }
907            }
908        }
909
910        @Override
911        public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId,
912                    ActivityIntentInfo filter, String packageName) {
913            if (!hasValidDomains(filter)) {
914                return false;
915            }
916            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
917            if (ivs == null) {
918                ivs = createDomainVerificationState(verifierUid, userId, verificationId,
919                        packageName);
920            }
921            if (DEBUG_DOMAIN_VERIFICATION) {
922                Slog.d(TAG, "Adding verification filter for " + packageName + ": " + filter);
923            }
924            ivs.addFilter(filter);
925            return true;
926        }
927
928        private IntentFilterVerificationState createDomainVerificationState(int verifierUid,
929                int userId, int verificationId, String packageName) {
930            IntentFilterVerificationState ivs = new IntentFilterVerificationState(
931                    verifierUid, userId, packageName);
932            ivs.setPendingState();
933            synchronized (mPackages) {
934                mIntentFilterVerificationStates.append(verificationId, ivs);
935                mCurrentIntentFilterVerifications.add(verificationId);
936            }
937            return ivs;
938        }
939    }
940
941    private static boolean hasValidDomains(ActivityIntentInfo filter) {
942        return filter.hasCategory(Intent.CATEGORY_BROWSABLE)
943                && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
944                        filter.hasDataScheme(IntentFilter.SCHEME_HTTPS));
945    }
946
947    // Set of pending broadcasts for aggregating enable/disable of components.
948    static class PendingPackageBroadcasts {
949        // for each user id, a map of <package name -> components within that package>
950        final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap;
951
952        public PendingPackageBroadcasts() {
953            mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2);
954        }
955
956        public ArrayList<String> get(int userId, String packageName) {
957            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
958            return packages.get(packageName);
959        }
960
961        public void put(int userId, String packageName, ArrayList<String> components) {
962            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
963            packages.put(packageName, components);
964        }
965
966        public void remove(int userId, String packageName) {
967            ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId);
968            if (packages != null) {
969                packages.remove(packageName);
970            }
971        }
972
973        public void remove(int userId) {
974            mUidMap.remove(userId);
975        }
976
977        public int userIdCount() {
978            return mUidMap.size();
979        }
980
981        public int userIdAt(int n) {
982            return mUidMap.keyAt(n);
983        }
984
985        public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) {
986            return mUidMap.get(userId);
987        }
988
989        public int size() {
990            // total number of pending broadcast entries across all userIds
991            int num = 0;
992            for (int i = 0; i< mUidMap.size(); i++) {
993                num += mUidMap.valueAt(i).size();
994            }
995            return num;
996        }
997
998        public void clear() {
999            mUidMap.clear();
1000        }
1001
1002        private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) {
1003            ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId);
1004            if (map == null) {
1005                map = new ArrayMap<String, ArrayList<String>>();
1006                mUidMap.put(userId, map);
1007            }
1008            return map;
1009        }
1010    }
1011    final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts();
1012
1013    // Service Connection to remote media container service to copy
1014    // package uri's from external media onto secure containers
1015    // or internal storage.
1016    private IMediaContainerService mContainerService = null;
1017
1018    static final int SEND_PENDING_BROADCAST = 1;
1019    static final int MCS_BOUND = 3;
1020    static final int END_COPY = 4;
1021    static final int INIT_COPY = 5;
1022    static final int MCS_UNBIND = 6;
1023    static final int START_CLEANING_PACKAGE = 7;
1024    static final int FIND_INSTALL_LOC = 8;
1025    static final int POST_INSTALL = 9;
1026    static final int MCS_RECONNECT = 10;
1027    static final int MCS_GIVE_UP = 11;
1028    static final int UPDATED_MEDIA_STATUS = 12;
1029    static final int WRITE_SETTINGS = 13;
1030    static final int WRITE_PACKAGE_RESTRICTIONS = 14;
1031    static final int PACKAGE_VERIFIED = 15;
1032    static final int CHECK_PENDING_VERIFICATION = 16;
1033    static final int START_INTENT_FILTER_VERIFICATIONS = 17;
1034    static final int INTENT_FILTER_VERIFIED = 18;
1035
1036    static final int WRITE_SETTINGS_DELAY = 10*1000;  // 10 seconds
1037
1038    // Delay time in millisecs
1039    static final int BROADCAST_DELAY = 10 * 1000;
1040
1041    static UserManagerService sUserManager;
1042
1043    // Stores a list of users whose package restrictions file needs to be updated
1044    private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>();
1045
1046    final private DefaultContainerConnection mDefContainerConn =
1047            new DefaultContainerConnection();
1048    class DefaultContainerConnection implements ServiceConnection {
1049        public void onServiceConnected(ComponentName name, IBinder service) {
1050            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
1051            IMediaContainerService imcs =
1052                IMediaContainerService.Stub.asInterface(service);
1053            mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
1054        }
1055
1056        public void onServiceDisconnected(ComponentName name) {
1057            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
1058        }
1059    }
1060
1061    // Recordkeeping of restore-after-install operations that are currently in flight
1062    // between the Package Manager and the Backup Manager
1063    static class PostInstallData {
1064        public InstallArgs args;
1065        public PackageInstalledInfo res;
1066
1067        PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
1068            args = _a;
1069            res = _r;
1070        }
1071    }
1072
1073    final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
1074    int mNextInstallToken = 1;  // nonzero; will be wrapped back to 1 when ++ overflows
1075
1076    // XML tags for backup/restore of various bits of state
1077    private static final String TAG_PREFERRED_BACKUP = "pa";
1078    private static final String TAG_DEFAULT_APPS = "da";
1079    private static final String TAG_INTENT_FILTER_VERIFICATION = "iv";
1080
1081    private static final String TAG_PERMISSION_BACKUP = "perm-grant-backup";
1082    private static final String TAG_ALL_GRANTS = "rt-grants";
1083    private static final String TAG_GRANT = "grant";
1084    private static final String ATTR_PACKAGE_NAME = "pkg";
1085
1086    private static final String TAG_PERMISSION = "perm";
1087    private static final String ATTR_PERMISSION_NAME = "name";
1088    private static final String ATTR_IS_GRANTED = "g";
1089    private static final String ATTR_USER_SET = "set";
1090    private static final String ATTR_USER_FIXED = "fixed";
1091    private static final String ATTR_REVOKE_ON_UPGRADE = "rou";
1092
1093    // System/policy permission grants are not backed up
1094    private static final int SYSTEM_RUNTIME_GRANT_MASK =
1095            FLAG_PERMISSION_POLICY_FIXED
1096            | FLAG_PERMISSION_SYSTEM_FIXED
1097            | FLAG_PERMISSION_GRANTED_BY_DEFAULT;
1098
1099    // And we back up these user-adjusted states
1100    private static final int USER_RUNTIME_GRANT_MASK =
1101            FLAG_PERMISSION_USER_SET
1102            | FLAG_PERMISSION_USER_FIXED
1103            | FLAG_PERMISSION_REVOKE_ON_UPGRADE;
1104
1105    final @Nullable String mRequiredVerifierPackage;
1106    final @NonNull String mRequiredInstallerPackage;
1107    final @Nullable String mSetupWizardPackage;
1108    final @NonNull String mServicesSystemSharedLibraryPackageName;
1109    final @NonNull String mSharedSystemSharedLibraryPackageName;
1110
1111    private final PackageUsage mPackageUsage = new PackageUsage();
1112
1113    private class PackageUsage {
1114        private static final int WRITE_INTERVAL
1115            = (DEBUG_DEXOPT) ? 0 : 30*60*1000; // 30m in ms
1116
1117        private final Object mFileLock = new Object();
1118        private final AtomicLong mLastWritten = new AtomicLong(0);
1119        private final AtomicBoolean mBackgroundWriteRunning = new AtomicBoolean(false);
1120
1121        private boolean mIsHistoricalPackageUsageAvailable = true;
1122
1123        boolean isHistoricalPackageUsageAvailable() {
1124            return mIsHistoricalPackageUsageAvailable;
1125        }
1126
1127        void write(boolean force) {
1128            if (force) {
1129                writeInternal();
1130                return;
1131            }
1132            if (SystemClock.elapsedRealtime() - mLastWritten.get() < WRITE_INTERVAL
1133                && !DEBUG_DEXOPT) {
1134                return;
1135            }
1136            if (mBackgroundWriteRunning.compareAndSet(false, true)) {
1137                new Thread("PackageUsage_DiskWriter") {
1138                    @Override
1139                    public void run() {
1140                        try {
1141                            writeInternal();
1142                        } finally {
1143                            mBackgroundWriteRunning.set(false);
1144                        }
1145                    }
1146                }.start();
1147            }
1148        }
1149
1150        private void writeInternal() {
1151            synchronized (mPackages) {
1152                synchronized (mFileLock) {
1153                    AtomicFile file = getFile();
1154                    FileOutputStream f = null;
1155                    try {
1156                        f = file.startWrite();
1157                        BufferedOutputStream out = new BufferedOutputStream(f);
1158                        FileUtils.setPermissions(file.getBaseFile().getPath(),
1159                                0640, SYSTEM_UID, PACKAGE_INFO_GID);
1160                        StringBuilder sb = new StringBuilder();
1161
1162                        sb.append(USAGE_FILE_MAGIC_VERSION_1);
1163                        sb.append('\n');
1164                        out.write(sb.toString().getBytes(StandardCharsets.US_ASCII));
1165
1166                        for (PackageParser.Package pkg : mPackages.values()) {
1167                            if (pkg.getLatestPackageUseTimeInMills() == 0L) {
1168                                continue;
1169                            }
1170                            sb.setLength(0);
1171                            sb.append(pkg.packageName);
1172                            for (long usageTimeInMillis : pkg.mLastPackageUsageTimeInMills) {
1173                                sb.append(' ');
1174                                sb.append(usageTimeInMillis);
1175                            }
1176                            sb.append('\n');
1177                            out.write(sb.toString().getBytes(StandardCharsets.US_ASCII));
1178                        }
1179                        out.flush();
1180                        file.finishWrite(f);
1181                    } catch (IOException e) {
1182                        if (f != null) {
1183                            file.failWrite(f);
1184                        }
1185                        Log.e(TAG, "Failed to write package usage times", e);
1186                    }
1187                }
1188            }
1189            mLastWritten.set(SystemClock.elapsedRealtime());
1190        }
1191
1192        void readLP() {
1193            synchronized (mFileLock) {
1194                AtomicFile file = getFile();
1195                BufferedInputStream in = null;
1196                try {
1197                    in = new BufferedInputStream(file.openRead());
1198                    StringBuffer sb = new StringBuffer();
1199
1200                    String firstLine = readLine(in, sb);
1201                    if (firstLine.equals(USAGE_FILE_MAGIC_VERSION_1)) {
1202                        readVersion1LP(in, sb);
1203                    } else {
1204                        readVersion0LP(in, sb, firstLine);
1205                    }
1206                } catch (FileNotFoundException expected) {
1207                    mIsHistoricalPackageUsageAvailable = false;
1208                } catch (IOException e) {
1209                    Log.w(TAG, "Failed to read package usage times", e);
1210                } finally {
1211                    IoUtils.closeQuietly(in);
1212                }
1213            }
1214            mLastWritten.set(SystemClock.elapsedRealtime());
1215        }
1216
1217        private void readVersion0LP(InputStream in, StringBuffer sb, String firstLine)
1218                throws IOException {
1219            // Initial version of the file had no version number and stored one
1220            // package-timestamp pair per line.
1221            // Note that the first line has already been read from the InputStream.
1222            String line = firstLine;
1223            while (true) {
1224                if (line == null) {
1225                    break;
1226                }
1227
1228                String[] tokens = line.split(" ");
1229                if (tokens.length != 2) {
1230                    throw new IOException("Failed to parse " + line +
1231                            " as package-timestamp pair.");
1232                }
1233
1234                String packageName = tokens[0];
1235                PackageParser.Package pkg = mPackages.get(packageName);
1236                if (pkg == null) {
1237                    continue;
1238                }
1239
1240                long timestamp = parseAsLong(tokens[1]);
1241                for (int reason = 0;
1242                        reason < PackageManager.NOTIFY_PACKAGE_USE_REASONS_COUNT;
1243                        reason++) {
1244                    pkg.mLastPackageUsageTimeInMills[reason] = timestamp;
1245                }
1246
1247                line = readLine(in, sb);
1248            }
1249        }
1250
1251        private void readVersion1LP(InputStream in, StringBuffer sb) throws IOException {
1252            // Version 1 of the file started with the corresponding version
1253            // number and then stored a package name and eight timestamps per line.
1254            String line;
1255            while ((line = readLine(in, sb)) != null) {
1256                String[] tokens = line.split(" ");
1257                if (tokens.length != PackageManager.NOTIFY_PACKAGE_USE_REASONS_COUNT + 1) {
1258                    throw new IOException("Failed to parse " + line + " as a timestamp array.");
1259                }
1260
1261                String packageName = tokens[0];
1262                PackageParser.Package pkg = mPackages.get(packageName);
1263                if (pkg == null) {
1264                    continue;
1265                }
1266
1267                for (int reason = 0;
1268                        reason < PackageManager.NOTIFY_PACKAGE_USE_REASONS_COUNT;
1269                        reason++) {
1270                    pkg.mLastPackageUsageTimeInMills[reason] = parseAsLong(tokens[reason + 1]);
1271                }
1272            }
1273        }
1274
1275        private long parseAsLong(String token) throws IOException {
1276            try {
1277                return Long.parseLong(token);
1278            } catch (NumberFormatException e) {
1279                throw new IOException("Failed to parse " + token + " as a long.", e);
1280            }
1281        }
1282
1283        private String readLine(InputStream in, StringBuffer sb) throws IOException {
1284            return readToken(in, sb, '\n');
1285        }
1286
1287        private String readToken(InputStream in, StringBuffer sb, char endOfToken)
1288                throws IOException {
1289            sb.setLength(0);
1290            while (true) {
1291                int ch = in.read();
1292                if (ch == -1) {
1293                    if (sb.length() == 0) {
1294                        return null;
1295                    }
1296                    throw new IOException("Unexpected EOF");
1297                }
1298                if (ch == endOfToken) {
1299                    return sb.toString();
1300                }
1301                sb.append((char)ch);
1302            }
1303        }
1304
1305        private AtomicFile getFile() {
1306            File dataDir = Environment.getDataDirectory();
1307            File systemDir = new File(dataDir, "system");
1308            File fname = new File(systemDir, "package-usage.list");
1309            return new AtomicFile(fname);
1310        }
1311
1312        private static final String USAGE_FILE_MAGIC = "PACKAGE_USAGE__VERSION_";
1313        private static final String USAGE_FILE_MAGIC_VERSION_1 = USAGE_FILE_MAGIC + "1";
1314    }
1315
1316    class PackageHandler extends Handler {
1317        private boolean mBound = false;
1318        final ArrayList<HandlerParams> mPendingInstalls =
1319            new ArrayList<HandlerParams>();
1320
1321        private boolean connectToService() {
1322            if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
1323                    " DefaultContainerService");
1324            Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
1325            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1326            if (mContext.bindServiceAsUser(service, mDefContainerConn,
1327                    Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
1328                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1329                mBound = true;
1330                return true;
1331            }
1332            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1333            return false;
1334        }
1335
1336        private void disconnectService() {
1337            mContainerService = null;
1338            mBound = false;
1339            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1340            mContext.unbindService(mDefContainerConn);
1341            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1342        }
1343
1344        PackageHandler(Looper looper) {
1345            super(looper);
1346        }
1347
1348        public void handleMessage(Message msg) {
1349            try {
1350                doHandleMessage(msg);
1351            } finally {
1352                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1353            }
1354        }
1355
1356        void doHandleMessage(Message msg) {
1357            switch (msg.what) {
1358                case INIT_COPY: {
1359                    HandlerParams params = (HandlerParams) msg.obj;
1360                    int idx = mPendingInstalls.size();
1361                    if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params);
1362                    // If a bind was already initiated we dont really
1363                    // need to do anything. The pending install
1364                    // will be processed later on.
1365                    if (!mBound) {
1366                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1367                                System.identityHashCode(mHandler));
1368                        // If this is the only one pending we might
1369                        // have to bind to the service again.
1370                        if (!connectToService()) {
1371                            Slog.e(TAG, "Failed to bind to media container service");
1372                            params.serviceError();
1373                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1374                                    System.identityHashCode(mHandler));
1375                            if (params.traceMethod != null) {
1376                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod,
1377                                        params.traceCookie);
1378                            }
1379                            return;
1380                        } else {
1381                            // Once we bind to the service, the first
1382                            // pending request will be processed.
1383                            mPendingInstalls.add(idx, params);
1384                        }
1385                    } else {
1386                        mPendingInstalls.add(idx, params);
1387                        // Already bound to the service. Just make
1388                        // sure we trigger off processing the first request.
1389                        if (idx == 0) {
1390                            mHandler.sendEmptyMessage(MCS_BOUND);
1391                        }
1392                    }
1393                    break;
1394                }
1395                case MCS_BOUND: {
1396                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound");
1397                    if (msg.obj != null) {
1398                        mContainerService = (IMediaContainerService) msg.obj;
1399                        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1400                                System.identityHashCode(mHandler));
1401                    }
1402                    if (mContainerService == null) {
1403                        if (!mBound) {
1404                            // Something seriously wrong since we are not bound and we are not
1405                            // waiting for connection. Bail out.
1406                            Slog.e(TAG, "Cannot bind to media container service");
1407                            for (HandlerParams params : mPendingInstalls) {
1408                                // Indicate service bind error
1409                                params.serviceError();
1410                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1411                                        System.identityHashCode(params));
1412                                if (params.traceMethod != null) {
1413                                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER,
1414                                            params.traceMethod, params.traceCookie);
1415                                }
1416                                return;
1417                            }
1418                            mPendingInstalls.clear();
1419                        } else {
1420                            Slog.w(TAG, "Waiting to connect to media container service");
1421                        }
1422                    } else if (mPendingInstalls.size() > 0) {
1423                        HandlerParams params = mPendingInstalls.get(0);
1424                        if (params != null) {
1425                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1426                                    System.identityHashCode(params));
1427                            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy");
1428                            if (params.startCopy()) {
1429                                // We are done...  look for more work or to
1430                                // go idle.
1431                                if (DEBUG_SD_INSTALL) Log.i(TAG,
1432                                        "Checking for more work or unbind...");
1433                                // Delete pending install
1434                                if (mPendingInstalls.size() > 0) {
1435                                    mPendingInstalls.remove(0);
1436                                }
1437                                if (mPendingInstalls.size() == 0) {
1438                                    if (mBound) {
1439                                        if (DEBUG_SD_INSTALL) Log.i(TAG,
1440                                                "Posting delayed MCS_UNBIND");
1441                                        removeMessages(MCS_UNBIND);
1442                                        Message ubmsg = obtainMessage(MCS_UNBIND);
1443                                        // Unbind after a little delay, to avoid
1444                                        // continual thrashing.
1445                                        sendMessageDelayed(ubmsg, 10000);
1446                                    }
1447                                } else {
1448                                    // There are more pending requests in queue.
1449                                    // Just post MCS_BOUND message to trigger processing
1450                                    // of next pending install.
1451                                    if (DEBUG_SD_INSTALL) Log.i(TAG,
1452                                            "Posting MCS_BOUND for next work");
1453                                    mHandler.sendEmptyMessage(MCS_BOUND);
1454                                }
1455                            }
1456                            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
1457                        }
1458                    } else {
1459                        // Should never happen ideally.
1460                        Slog.w(TAG, "Empty queue");
1461                    }
1462                    break;
1463                }
1464                case MCS_RECONNECT: {
1465                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect");
1466                    if (mPendingInstalls.size() > 0) {
1467                        if (mBound) {
1468                            disconnectService();
1469                        }
1470                        if (!connectToService()) {
1471                            Slog.e(TAG, "Failed to bind to media container service");
1472                            for (HandlerParams params : mPendingInstalls) {
1473                                // Indicate service bind error
1474                                params.serviceError();
1475                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1476                                        System.identityHashCode(params));
1477                            }
1478                            mPendingInstalls.clear();
1479                        }
1480                    }
1481                    break;
1482                }
1483                case MCS_UNBIND: {
1484                    // If there is no actual work left, then time to unbind.
1485                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind");
1486
1487                    if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) {
1488                        if (mBound) {
1489                            if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()");
1490
1491                            disconnectService();
1492                        }
1493                    } else if (mPendingInstalls.size() > 0) {
1494                        // There are more pending requests in queue.
1495                        // Just post MCS_BOUND message to trigger processing
1496                        // of next pending install.
1497                        mHandler.sendEmptyMessage(MCS_BOUND);
1498                    }
1499
1500                    break;
1501                }
1502                case MCS_GIVE_UP: {
1503                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries");
1504                    HandlerParams params = mPendingInstalls.remove(0);
1505                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1506                            System.identityHashCode(params));
1507                    break;
1508                }
1509                case SEND_PENDING_BROADCAST: {
1510                    String packages[];
1511                    ArrayList<String> components[];
1512                    int size = 0;
1513                    int uids[];
1514                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1515                    synchronized (mPackages) {
1516                        if (mPendingBroadcasts == null) {
1517                            return;
1518                        }
1519                        size = mPendingBroadcasts.size();
1520                        if (size <= 0) {
1521                            // Nothing to be done. Just return
1522                            return;
1523                        }
1524                        packages = new String[size];
1525                        components = new ArrayList[size];
1526                        uids = new int[size];
1527                        int i = 0;  // filling out the above arrays
1528
1529                        for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) {
1530                            int packageUserId = mPendingBroadcasts.userIdAt(n);
1531                            Iterator<Map.Entry<String, ArrayList<String>>> it
1532                                    = mPendingBroadcasts.packagesForUserId(packageUserId)
1533                                            .entrySet().iterator();
1534                            while (it.hasNext() && i < size) {
1535                                Map.Entry<String, ArrayList<String>> ent = it.next();
1536                                packages[i] = ent.getKey();
1537                                components[i] = ent.getValue();
1538                                PackageSetting ps = mSettings.mPackages.get(ent.getKey());
1539                                uids[i] = (ps != null)
1540                                        ? UserHandle.getUid(packageUserId, ps.appId)
1541                                        : -1;
1542                                i++;
1543                            }
1544                        }
1545                        size = i;
1546                        mPendingBroadcasts.clear();
1547                    }
1548                    // Send broadcasts
1549                    for (int i = 0; i < size; i++) {
1550                        sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]);
1551                    }
1552                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1553                    break;
1554                }
1555                case START_CLEANING_PACKAGE: {
1556                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1557                    final String packageName = (String)msg.obj;
1558                    final int userId = msg.arg1;
1559                    final boolean andCode = msg.arg2 != 0;
1560                    synchronized (mPackages) {
1561                        if (userId == UserHandle.USER_ALL) {
1562                            int[] users = sUserManager.getUserIds();
1563                            for (int user : users) {
1564                                mSettings.addPackageToCleanLPw(
1565                                        new PackageCleanItem(user, packageName, andCode));
1566                            }
1567                        } else {
1568                            mSettings.addPackageToCleanLPw(
1569                                    new PackageCleanItem(userId, packageName, andCode));
1570                        }
1571                    }
1572                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1573                    startCleaningPackages();
1574                } break;
1575                case POST_INSTALL: {
1576                    if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
1577
1578                    PostInstallData data = mRunningInstalls.get(msg.arg1);
1579                    mRunningInstalls.delete(msg.arg1);
1580
1581                    if (data != null) {
1582                        InstallArgs args = data.args;
1583                        PackageInstalledInfo parentRes = data.res;
1584
1585                        final boolean grantPermissions = (args.installFlags
1586                                & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0;
1587                        final boolean killApp = (args.installFlags
1588                                & PackageManager.INSTALL_DONT_KILL_APP) == 0;
1589                        final String[] grantedPermissions = args.installGrantPermissions;
1590
1591                        // Handle the parent package
1592                        handlePackagePostInstall(parentRes, grantPermissions, killApp,
1593                                grantedPermissions, args.observer);
1594
1595                        // Handle the child packages
1596                        final int childCount = (parentRes.addedChildPackages != null)
1597                                ? parentRes.addedChildPackages.size() : 0;
1598                        for (int i = 0; i < childCount; i++) {
1599                            PackageInstalledInfo childRes = parentRes.addedChildPackages.valueAt(i);
1600                            handlePackagePostInstall(childRes, grantPermissions, killApp,
1601                                    grantedPermissions, args.observer);
1602                        }
1603
1604                        // Log tracing if needed
1605                        if (args.traceMethod != null) {
1606                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod,
1607                                    args.traceCookie);
1608                        }
1609                    } else {
1610                        Slog.e(TAG, "Bogus post-install token " + msg.arg1);
1611                    }
1612
1613                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1);
1614                } break;
1615                case UPDATED_MEDIA_STATUS: {
1616                    if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS");
1617                    boolean reportStatus = msg.arg1 == 1;
1618                    boolean doGc = msg.arg2 == 1;
1619                    if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc);
1620                    if (doGc) {
1621                        // Force a gc to clear up stale containers.
1622                        Runtime.getRuntime().gc();
1623                    }
1624                    if (msg.obj != null) {
1625                        @SuppressWarnings("unchecked")
1626                        Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj;
1627                        if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers");
1628                        // Unload containers
1629                        unloadAllContainers(args);
1630                    }
1631                    if (reportStatus) {
1632                        try {
1633                            if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back");
1634                            PackageHelper.getMountService().finishMediaUpdate();
1635                        } catch (RemoteException e) {
1636                            Log.e(TAG, "MountService not running?");
1637                        }
1638                    }
1639                } break;
1640                case WRITE_SETTINGS: {
1641                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1642                    synchronized (mPackages) {
1643                        removeMessages(WRITE_SETTINGS);
1644                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1645                        mSettings.writeLPr();
1646                        mDirtyUsers.clear();
1647                    }
1648                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1649                } break;
1650                case WRITE_PACKAGE_RESTRICTIONS: {
1651                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1652                    synchronized (mPackages) {
1653                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1654                        for (int userId : mDirtyUsers) {
1655                            mSettings.writePackageRestrictionsLPr(userId);
1656                        }
1657                        mDirtyUsers.clear();
1658                    }
1659                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1660                } break;
1661                case CHECK_PENDING_VERIFICATION: {
1662                    final int verificationId = msg.arg1;
1663                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1664
1665                    if ((state != null) && !state.timeoutExtended()) {
1666                        final InstallArgs args = state.getInstallArgs();
1667                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1668
1669                        Slog.i(TAG, "Verification timed out for " + originUri);
1670                        mPendingVerification.remove(verificationId);
1671
1672                        int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1673
1674                        if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) {
1675                            Slog.i(TAG, "Continuing with installation of " + originUri);
1676                            state.setVerifierResponse(Binder.getCallingUid(),
1677                                    PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT);
1678                            broadcastPackageVerified(verificationId, originUri,
1679                                    PackageManager.VERIFICATION_ALLOW,
1680                                    state.getInstallArgs().getUser());
1681                            try {
1682                                ret = args.copyApk(mContainerService, true);
1683                            } catch (RemoteException e) {
1684                                Slog.e(TAG, "Could not contact the ContainerService");
1685                            }
1686                        } else {
1687                            broadcastPackageVerified(verificationId, originUri,
1688                                    PackageManager.VERIFICATION_REJECT,
1689                                    state.getInstallArgs().getUser());
1690                        }
1691
1692                        Trace.asyncTraceEnd(
1693                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1694
1695                        processPendingInstall(args, ret);
1696                        mHandler.sendEmptyMessage(MCS_UNBIND);
1697                    }
1698                    break;
1699                }
1700                case PACKAGE_VERIFIED: {
1701                    final int verificationId = msg.arg1;
1702
1703                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1704                    if (state == null) {
1705                        Slog.w(TAG, "Invalid verification token " + verificationId + " received");
1706                        break;
1707                    }
1708
1709                    final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj;
1710
1711                    state.setVerifierResponse(response.callerUid, response.code);
1712
1713                    if (state.isVerificationComplete()) {
1714                        mPendingVerification.remove(verificationId);
1715
1716                        final InstallArgs args = state.getInstallArgs();
1717                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1718
1719                        int ret;
1720                        if (state.isInstallAllowed()) {
1721                            ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
1722                            broadcastPackageVerified(verificationId, originUri,
1723                                    response.code, state.getInstallArgs().getUser());
1724                            try {
1725                                ret = args.copyApk(mContainerService, true);
1726                            } catch (RemoteException e) {
1727                                Slog.e(TAG, "Could not contact the ContainerService");
1728                            }
1729                        } else {
1730                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1731                        }
1732
1733                        Trace.asyncTraceEnd(
1734                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1735
1736                        processPendingInstall(args, ret);
1737                        mHandler.sendEmptyMessage(MCS_UNBIND);
1738                    }
1739
1740                    break;
1741                }
1742                case START_INTENT_FILTER_VERIFICATIONS: {
1743                    IFVerificationParams params = (IFVerificationParams) msg.obj;
1744                    verifyIntentFiltersIfNeeded(params.userId, params.verifierUid,
1745                            params.replacing, params.pkg);
1746                    break;
1747                }
1748                case INTENT_FILTER_VERIFIED: {
1749                    final int verificationId = msg.arg1;
1750
1751                    final IntentFilterVerificationState state = mIntentFilterVerificationStates.get(
1752                            verificationId);
1753                    if (state == null) {
1754                        Slog.w(TAG, "Invalid IntentFilter verification token "
1755                                + verificationId + " received");
1756                        break;
1757                    }
1758
1759                    final int userId = state.getUserId();
1760
1761                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1762                            "Processing IntentFilter verification with token:"
1763                            + verificationId + " and userId:" + userId);
1764
1765                    final IntentFilterVerificationResponse response =
1766                            (IntentFilterVerificationResponse) msg.obj;
1767
1768                    state.setVerifierResponse(response.callerUid, response.code);
1769
1770                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1771                            "IntentFilter verification with token:" + verificationId
1772                            + " and userId:" + userId
1773                            + " is settings verifier response with response code:"
1774                            + response.code);
1775
1776                    if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) {
1777                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: "
1778                                + response.getFailedDomainsString());
1779                    }
1780
1781                    if (state.isVerificationComplete()) {
1782                        mIntentFilterVerifier.receiveVerificationResponse(verificationId);
1783                    } else {
1784                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1785                                "IntentFilter verification with token:" + verificationId
1786                                + " was not said to be complete");
1787                    }
1788
1789                    break;
1790                }
1791            }
1792        }
1793    }
1794
1795    private void handlePackagePostInstall(PackageInstalledInfo res, boolean grantPermissions,
1796            boolean killApp, String[] grantedPermissions,
1797            IPackageInstallObserver2 installObserver) {
1798        if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
1799            // Send the removed broadcasts
1800            if (res.removedInfo != null) {
1801                res.removedInfo.sendPackageRemovedBroadcasts(killApp);
1802            }
1803
1804            // Now that we successfully installed the package, grant runtime
1805            // permissions if requested before broadcasting the install.
1806            if (grantPermissions && res.pkg.applicationInfo.targetSdkVersion
1807                    >= Build.VERSION_CODES.M) {
1808                grantRequestedRuntimePermissions(res.pkg, res.newUsers, grantedPermissions);
1809            }
1810
1811            final boolean update = res.removedInfo != null
1812                    && res.removedInfo.removedPackage != null;
1813
1814            // If this is the first time we have child packages for a disabled privileged
1815            // app that had no children, we grant requested runtime permissions to the new
1816            // children if the parent on the system image had them already granted.
1817            if (res.pkg.parentPackage != null) {
1818                synchronized (mPackages) {
1819                    grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(res.pkg);
1820                }
1821            }
1822
1823            synchronized (mPackages) {
1824                mEphemeralApplicationRegistry.onPackageInstalledLPw(res.pkg);
1825            }
1826
1827            final String packageName = res.pkg.applicationInfo.packageName;
1828            Bundle extras = new Bundle(1);
1829            extras.putInt(Intent.EXTRA_UID, res.uid);
1830
1831            // Determine the set of users who are adding this package for
1832            // the first time vs. those who are seeing an update.
1833            int[] firstUsers = EMPTY_INT_ARRAY;
1834            int[] updateUsers = EMPTY_INT_ARRAY;
1835            if (res.origUsers == null || res.origUsers.length == 0) {
1836                firstUsers = res.newUsers;
1837            } else {
1838                for (int newUser : res.newUsers) {
1839                    boolean isNew = true;
1840                    for (int origUser : res.origUsers) {
1841                        if (origUser == newUser) {
1842                            isNew = false;
1843                            break;
1844                        }
1845                    }
1846                    if (isNew) {
1847                        firstUsers = ArrayUtils.appendInt(firstUsers, newUser);
1848                    } else {
1849                        updateUsers = ArrayUtils.appendInt(updateUsers, newUser);
1850                    }
1851                }
1852            }
1853
1854            // Send installed broadcasts if the install/update is not ephemeral
1855            if (!isEphemeral(res.pkg)) {
1856                mProcessLoggingHandler.invalidateProcessLoggingBaseApkHash(res.pkg.baseCodePath);
1857
1858                // Send added for users that see the package for the first time
1859                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
1860                        extras, 0 /*flags*/, null /*targetPackage*/,
1861                        null /*finishedReceiver*/, firstUsers);
1862
1863                // Send added for users that don't see the package for the first time
1864                if (update) {
1865                    extras.putBoolean(Intent.EXTRA_REPLACING, true);
1866                }
1867                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
1868                        extras, 0 /*flags*/, null /*targetPackage*/,
1869                        null /*finishedReceiver*/, updateUsers);
1870
1871                // Send replaced for users that don't see the package for the first time
1872                if (update) {
1873                    sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
1874                            packageName, extras, 0 /*flags*/,
1875                            null /*targetPackage*/, null /*finishedReceiver*/,
1876                            updateUsers);
1877                    sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
1878                            null /*package*/, null /*extras*/, 0 /*flags*/,
1879                            packageName /*targetPackage*/,
1880                            null /*finishedReceiver*/, updateUsers);
1881                }
1882
1883                // Send broadcast package appeared if forward locked/external for all users
1884                // treat asec-hosted packages like removable media on upgrade
1885                if (res.pkg.isForwardLocked() || isExternal(res.pkg)) {
1886                    if (DEBUG_INSTALL) {
1887                        Slog.i(TAG, "upgrading pkg " + res.pkg
1888                                + " is ASEC-hosted -> AVAILABLE");
1889                    }
1890                    final int[] uidArray = new int[]{res.pkg.applicationInfo.uid};
1891                    ArrayList<String> pkgList = new ArrayList<>(1);
1892                    pkgList.add(packageName);
1893                    sendResourcesChangedBroadcast(true, true, pkgList, uidArray, null);
1894                }
1895            }
1896
1897            // Work that needs to happen on first install within each user
1898            if (firstUsers != null && firstUsers.length > 0) {
1899                synchronized (mPackages) {
1900                    for (int userId : firstUsers) {
1901                        // If this app is a browser and it's newly-installed for some
1902                        // users, clear any default-browser state in those users. The
1903                        // app's nature doesn't depend on the user, so we can just check
1904                        // its browser nature in any user and generalize.
1905                        if (packageIsBrowser(packageName, userId)) {
1906                            mSettings.setDefaultBrowserPackageNameLPw(null, userId);
1907                        }
1908
1909                        // We may also need to apply pending (restored) runtime
1910                        // permission grants within these users.
1911                        mSettings.applyPendingPermissionGrantsLPw(packageName, userId);
1912                    }
1913                }
1914            }
1915
1916            // Log current value of "unknown sources" setting
1917            EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED,
1918                    getUnknownSourcesSettings());
1919
1920            // Force a gc to clear up things
1921            Runtime.getRuntime().gc();
1922
1923            // Remove the replaced package's older resources safely now
1924            // We delete after a gc for applications  on sdcard.
1925            if (res.removedInfo != null && res.removedInfo.args != null) {
1926                synchronized (mInstallLock) {
1927                    res.removedInfo.args.doPostDeleteLI(true);
1928                }
1929            }
1930        }
1931
1932        // If someone is watching installs - notify them
1933        if (installObserver != null) {
1934            try {
1935                Bundle extras = extrasForInstallResult(res);
1936                installObserver.onPackageInstalled(res.name, res.returnCode,
1937                        res.returnMsg, extras);
1938            } catch (RemoteException e) {
1939                Slog.i(TAG, "Observer no longer exists.");
1940            }
1941        }
1942    }
1943
1944    private void grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(
1945            PackageParser.Package pkg) {
1946        if (pkg.parentPackage == null) {
1947            return;
1948        }
1949        if (pkg.requestedPermissions == null) {
1950            return;
1951        }
1952        final PackageSetting disabledSysParentPs = mSettings
1953                .getDisabledSystemPkgLPr(pkg.parentPackage.packageName);
1954        if (disabledSysParentPs == null || disabledSysParentPs.pkg == null
1955                || !disabledSysParentPs.isPrivileged()
1956                || (disabledSysParentPs.childPackageNames != null
1957                        && !disabledSysParentPs.childPackageNames.isEmpty())) {
1958            return;
1959        }
1960        final int[] allUserIds = sUserManager.getUserIds();
1961        final int permCount = pkg.requestedPermissions.size();
1962        for (int i = 0; i < permCount; i++) {
1963            String permission = pkg.requestedPermissions.get(i);
1964            BasePermission bp = mSettings.mPermissions.get(permission);
1965            if (bp == null || !(bp.isRuntime() || bp.isDevelopment())) {
1966                continue;
1967            }
1968            for (int userId : allUserIds) {
1969                if (disabledSysParentPs.getPermissionsState().hasRuntimePermission(
1970                        permission, userId)) {
1971                    grantRuntimePermission(pkg.packageName, permission, userId);
1972                }
1973            }
1974        }
1975    }
1976
1977    private StorageEventListener mStorageListener = new StorageEventListener() {
1978        @Override
1979        public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) {
1980            if (vol.type == VolumeInfo.TYPE_PRIVATE) {
1981                if (vol.state == VolumeInfo.STATE_MOUNTED) {
1982                    final String volumeUuid = vol.getFsUuid();
1983
1984                    // Clean up any users or apps that were removed or recreated
1985                    // while this volume was missing
1986                    reconcileUsers(volumeUuid);
1987                    reconcileApps(volumeUuid);
1988
1989                    // Clean up any install sessions that expired or were
1990                    // cancelled while this volume was missing
1991                    mInstallerService.onPrivateVolumeMounted(volumeUuid);
1992
1993                    loadPrivatePackages(vol);
1994
1995                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
1996                    unloadPrivatePackages(vol);
1997                }
1998            }
1999
2000            if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) {
2001                if (vol.state == VolumeInfo.STATE_MOUNTED) {
2002                    updateExternalMediaStatus(true, false);
2003                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
2004                    updateExternalMediaStatus(false, false);
2005                }
2006            }
2007        }
2008
2009        @Override
2010        public void onVolumeForgotten(String fsUuid) {
2011            if (TextUtils.isEmpty(fsUuid)) {
2012                Slog.e(TAG, "Forgetting internal storage is probably a mistake; ignoring");
2013                return;
2014            }
2015
2016            // Remove any apps installed on the forgotten volume
2017            synchronized (mPackages) {
2018                final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid);
2019                for (PackageSetting ps : packages) {
2020                    Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten");
2021                    deletePackage(ps.name, new LegacyPackageDeleteObserver(null).getBinder(),
2022                            UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS);
2023                }
2024
2025                mSettings.onVolumeForgotten(fsUuid);
2026                mSettings.writeLPr();
2027            }
2028        }
2029    };
2030
2031    private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int[] userIds,
2032            String[] grantedPermissions) {
2033        for (int userId : userIds) {
2034            grantRequestedRuntimePermissionsForUser(pkg, userId, grantedPermissions);
2035        }
2036
2037        // We could have touched GID membership, so flush out packages.list
2038        synchronized (mPackages) {
2039            mSettings.writePackageListLPr();
2040        }
2041    }
2042
2043    private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId,
2044            String[] grantedPermissions) {
2045        SettingBase sb = (SettingBase) pkg.mExtras;
2046        if (sb == null) {
2047            return;
2048        }
2049
2050        PermissionsState permissionsState = sb.getPermissionsState();
2051
2052        final int immutableFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
2053                | PackageManager.FLAG_PERMISSION_POLICY_FIXED;
2054
2055        for (String permission : pkg.requestedPermissions) {
2056            final BasePermission bp;
2057            synchronized (mPackages) {
2058                bp = mSettings.mPermissions.get(permission);
2059            }
2060            if (bp != null && (bp.isRuntime() || bp.isDevelopment())
2061                    && (grantedPermissions == null
2062                           || ArrayUtils.contains(grantedPermissions, permission))) {
2063                final int flags = permissionsState.getPermissionFlags(permission, userId);
2064                // Installer cannot change immutable permissions.
2065                if ((flags & immutableFlags) == 0) {
2066                    grantRuntimePermission(pkg.packageName, permission, userId);
2067                }
2068            }
2069        }
2070    }
2071
2072    Bundle extrasForInstallResult(PackageInstalledInfo res) {
2073        Bundle extras = null;
2074        switch (res.returnCode) {
2075            case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: {
2076                extras = new Bundle();
2077                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION,
2078                        res.origPermission);
2079                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE,
2080                        res.origPackage);
2081                break;
2082            }
2083            case PackageManager.INSTALL_SUCCEEDED: {
2084                extras = new Bundle();
2085                extras.putBoolean(Intent.EXTRA_REPLACING,
2086                        res.removedInfo != null && res.removedInfo.removedPackage != null);
2087                break;
2088            }
2089        }
2090        return extras;
2091    }
2092
2093    void scheduleWriteSettingsLocked() {
2094        if (!mHandler.hasMessages(WRITE_SETTINGS)) {
2095            mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
2096        }
2097    }
2098
2099    void scheduleWritePackageRestrictionsLocked(UserHandle user) {
2100        final int userId = user == null ? UserHandle.USER_ALL : user.getIdentifier();
2101        scheduleWritePackageRestrictionsLocked(userId);
2102    }
2103
2104    void scheduleWritePackageRestrictionsLocked(int userId) {
2105        final int[] userIds = (userId == UserHandle.USER_ALL)
2106                ? sUserManager.getUserIds() : new int[]{userId};
2107        for (int nextUserId : userIds) {
2108            if (!sUserManager.exists(nextUserId)) return;
2109            mDirtyUsers.add(nextUserId);
2110            if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) {
2111                mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY);
2112            }
2113        }
2114    }
2115
2116    public static PackageManagerService main(Context context, Installer installer,
2117            boolean factoryTest, boolean onlyCore) {
2118        // Self-check for initial settings.
2119        PackageManagerServiceCompilerMapping.checkProperties();
2120
2121        PackageManagerService m = new PackageManagerService(context, installer,
2122                factoryTest, onlyCore);
2123        m.enableSystemUserPackages();
2124        // Disable any carrier apps. We do this very early in boot to prevent the apps from being
2125        // disabled after already being started.
2126        CarrierAppUtils.disableCarrierAppsUntilPrivileged(context.getOpPackageName(), m,
2127                UserHandle.USER_SYSTEM);
2128        ServiceManager.addService("package", m);
2129        return m;
2130    }
2131
2132    private void enableSystemUserPackages() {
2133        if (!UserManager.isSplitSystemUser()) {
2134            return;
2135        }
2136        // For system user, enable apps based on the following conditions:
2137        // - app is whitelisted or belong to one of these groups:
2138        //   -- system app which has no launcher icons
2139        //   -- system app which has INTERACT_ACROSS_USERS permission
2140        //   -- system IME app
2141        // - app is not in the blacklist
2142        AppsQueryHelper queryHelper = new AppsQueryHelper(this);
2143        Set<String> enableApps = new ArraySet<>();
2144        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS
2145                | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM
2146                | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM));
2147        ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps();
2148        enableApps.addAll(wlApps);
2149        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_REQUIRED_FOR_SYSTEM_USER,
2150                /* systemAppsOnly */ false, UserHandle.SYSTEM));
2151        ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps();
2152        enableApps.removeAll(blApps);
2153        Log.i(TAG, "Applications installed for system user: " + enableApps);
2154        List<String> allAps = queryHelper.queryApps(0, /* systemAppsOnly */ false,
2155                UserHandle.SYSTEM);
2156        final int allAppsSize = allAps.size();
2157        synchronized (mPackages) {
2158            for (int i = 0; i < allAppsSize; i++) {
2159                String pName = allAps.get(i);
2160                PackageSetting pkgSetting = mSettings.mPackages.get(pName);
2161                // Should not happen, but we shouldn't be failing if it does
2162                if (pkgSetting == null) {
2163                    continue;
2164                }
2165                boolean install = enableApps.contains(pName);
2166                if (pkgSetting.getInstalled(UserHandle.USER_SYSTEM) != install) {
2167                    Log.i(TAG, (install ? "Installing " : "Uninstalling ") + pName
2168                            + " for system user");
2169                    pkgSetting.setInstalled(install, UserHandle.USER_SYSTEM);
2170                }
2171            }
2172        }
2173    }
2174
2175    private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) {
2176        DisplayManager displayManager = (DisplayManager) context.getSystemService(
2177                Context.DISPLAY_SERVICE);
2178        displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics);
2179    }
2180
2181    public PackageManagerService(Context context, Installer installer,
2182            boolean factoryTest, boolean onlyCore) {
2183        EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
2184                SystemClock.uptimeMillis());
2185
2186        if (mSdkVersion <= 0) {
2187            Slog.w(TAG, "**** ro.build.version.sdk not set!");
2188        }
2189
2190        mContext = context;
2191        mFactoryTest = factoryTest;
2192        mOnlyCore = onlyCore;
2193        mMetrics = new DisplayMetrics();
2194        mSettings = new Settings(mPackages);
2195        mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID,
2196                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2197        mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID,
2198                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2199        mSettings.addSharedUserLPw("android.uid.log", LOG_UID,
2200                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2201        mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID,
2202                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2203        mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID,
2204                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2205        mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID,
2206                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2207
2208        String separateProcesses = SystemProperties.get("debug.separate_processes");
2209        if (separateProcesses != null && separateProcesses.length() > 0) {
2210            if ("*".equals(separateProcesses)) {
2211                mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
2212                mSeparateProcesses = null;
2213                Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
2214            } else {
2215                mDefParseFlags = 0;
2216                mSeparateProcesses = separateProcesses.split(",");
2217                Slog.w(TAG, "Running with debug.separate_processes: "
2218                        + separateProcesses);
2219            }
2220        } else {
2221            mDefParseFlags = 0;
2222            mSeparateProcesses = null;
2223        }
2224
2225        mInstaller = installer;
2226        mPackageDexOptimizer = new PackageDexOptimizer(installer, mInstallLock, context,
2227                "*dexopt*");
2228        mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper());
2229
2230        mOnPermissionChangeListeners = new OnPermissionChangeListeners(
2231                FgThread.get().getLooper());
2232
2233        getDefaultDisplayMetrics(context, mMetrics);
2234
2235        SystemConfig systemConfig = SystemConfig.getInstance();
2236        mGlobalGids = systemConfig.getGlobalGids();
2237        mSystemPermissions = systemConfig.getSystemPermissions();
2238        mAvailableFeatures = systemConfig.getAvailableFeatures();
2239
2240        synchronized (mInstallLock) {
2241        // writer
2242        synchronized (mPackages) {
2243            mHandlerThread = new ServiceThread(TAG,
2244                    Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/);
2245            mHandlerThread.start();
2246            mHandler = new PackageHandler(mHandlerThread.getLooper());
2247            mProcessLoggingHandler = new ProcessLoggingHandler();
2248            Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT);
2249
2250            File dataDir = Environment.getDataDirectory();
2251            mAppInstallDir = new File(dataDir, "app");
2252            mAppLib32InstallDir = new File(dataDir, "app-lib");
2253            mEphemeralInstallDir = new File(dataDir, "app-ephemeral");
2254            mAsecInternalPath = new File(dataDir, "app-asec").getPath();
2255            mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
2256
2257            sUserManager = new UserManagerService(context, this, mPackages);
2258
2259            // Propagate permission configuration in to package manager.
2260            ArrayMap<String, SystemConfig.PermissionEntry> permConfig
2261                    = systemConfig.getPermissions();
2262            for (int i=0; i<permConfig.size(); i++) {
2263                SystemConfig.PermissionEntry perm = permConfig.valueAt(i);
2264                BasePermission bp = mSettings.mPermissions.get(perm.name);
2265                if (bp == null) {
2266                    bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN);
2267                    mSettings.mPermissions.put(perm.name, bp);
2268                }
2269                if (perm.gids != null) {
2270                    bp.setGids(perm.gids, perm.perUser);
2271                }
2272            }
2273
2274            ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries();
2275            for (int i=0; i<libConfig.size(); i++) {
2276                mSharedLibraries.put(libConfig.keyAt(i),
2277                        new SharedLibraryEntry(libConfig.valueAt(i), null));
2278            }
2279
2280            mFoundPolicyFile = SELinuxMMAC.readInstallPolicy();
2281
2282            mRestoredSettings = mSettings.readLPw(sUserManager.getUsers(false));
2283
2284            String customResolverActivity = Resources.getSystem().getString(
2285                    R.string.config_customResolverActivity);
2286            if (TextUtils.isEmpty(customResolverActivity)) {
2287                customResolverActivity = null;
2288            } else {
2289                mCustomResolverComponentName = ComponentName.unflattenFromString(
2290                        customResolverActivity);
2291            }
2292
2293            long startTime = SystemClock.uptimeMillis();
2294
2295            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
2296                    startTime);
2297
2298            // Set flag to monitor and not change apk file paths when
2299            // scanning install directories.
2300            final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING | SCAN_INITIAL;
2301
2302            final String bootClassPath = System.getenv("BOOTCLASSPATH");
2303            final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH");
2304
2305            if (bootClassPath == null) {
2306                Slog.w(TAG, "No BOOTCLASSPATH found!");
2307            }
2308
2309            if (systemServerClassPath == null) {
2310                Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!");
2311            }
2312
2313            final List<String> allInstructionSets = InstructionSets.getAllInstructionSets();
2314            final String[] dexCodeInstructionSets =
2315                    getDexCodeInstructionSets(
2316                            allInstructionSets.toArray(new String[allInstructionSets.size()]));
2317
2318            /**
2319             * Ensure all external libraries have had dexopt run on them.
2320             */
2321            if (mSharedLibraries.size() > 0) {
2322                // NOTE: For now, we're compiling these system "shared libraries"
2323                // (and framework jars) into all available architectures. It's possible
2324                // to compile them only when we come across an app that uses them (there's
2325                // already logic for that in scanPackageLI) but that adds some complexity.
2326                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
2327                    for (SharedLibraryEntry libEntry : mSharedLibraries.values()) {
2328                        final String lib = libEntry.path;
2329                        if (lib == null) {
2330                            continue;
2331                        }
2332
2333                        try {
2334                            // Shared libraries do not have profiles so we perform a full
2335                            // AOT compilation (if needed).
2336                            int dexoptNeeded = DexFile.getDexOptNeeded(
2337                                    lib, dexCodeInstructionSet,
2338                                    getCompilerFilterForReason(REASON_SHARED_APK),
2339                                    false /* newProfile */);
2340                            if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) {
2341                                mInstaller.dexopt(lib, Process.SYSTEM_UID, dexCodeInstructionSet,
2342                                        dexoptNeeded, DEXOPT_PUBLIC /*dexFlags*/,
2343                                        getCompilerFilterForReason(REASON_SHARED_APK),
2344                                        StorageManager.UUID_PRIVATE_INTERNAL);
2345                            }
2346                        } catch (FileNotFoundException e) {
2347                            Slog.w(TAG, "Library not found: " + lib);
2348                        } catch (IOException | InstallerException e) {
2349                            Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? "
2350                                    + e.getMessage());
2351                        }
2352                    }
2353                }
2354            }
2355
2356            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
2357
2358            final VersionInfo ver = mSettings.getInternalVersion();
2359            mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint);
2360
2361            // when upgrading from pre-M, promote system app permissions from install to runtime
2362            mPromoteSystemApps =
2363                    mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1;
2364
2365            // save off the names of pre-existing system packages prior to scanning; we don't
2366            // want to automatically grant runtime permissions for new system apps
2367            if (mPromoteSystemApps) {
2368                Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator();
2369                while (pkgSettingIter.hasNext()) {
2370                    PackageSetting ps = pkgSettingIter.next();
2371                    if (isSystemApp(ps)) {
2372                        mExistingSystemPackages.add(ps.name);
2373                    }
2374                }
2375            }
2376
2377            // When upgrading from pre-N, we need to handle package extraction like first boot,
2378            // as there is no profiling data available.
2379            mIsPreNUpgrade = !mSettings.isNWorkDone();
2380            mSettings.setNWorkDone();
2381
2382            // Collect vendor overlay packages.
2383            // (Do this before scanning any apps.)
2384            // For security and version matching reason, only consider
2385            // overlay packages if they reside in VENDOR_OVERLAY_DIR.
2386            File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR);
2387            scanDirTracedLI(vendorOverlayDir, mDefParseFlags
2388                    | PackageParser.PARSE_IS_SYSTEM
2389                    | PackageParser.PARSE_IS_SYSTEM_DIR
2390                    | PackageParser.PARSE_TRUSTED_OVERLAY, scanFlags | SCAN_TRUSTED_OVERLAY, 0);
2391
2392            // Find base frameworks (resource packages without code).
2393            scanDirTracedLI(frameworkDir, mDefParseFlags
2394                    | PackageParser.PARSE_IS_SYSTEM
2395                    | PackageParser.PARSE_IS_SYSTEM_DIR
2396                    | PackageParser.PARSE_IS_PRIVILEGED,
2397                    scanFlags | SCAN_NO_DEX, 0);
2398
2399            // Collected privileged system packages.
2400            final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
2401            scanDirTracedLI(privilegedAppDir, mDefParseFlags
2402                    | PackageParser.PARSE_IS_SYSTEM
2403                    | PackageParser.PARSE_IS_SYSTEM_DIR
2404                    | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0);
2405
2406            // Collect ordinary system packages.
2407            final File systemAppDir = new File(Environment.getRootDirectory(), "app");
2408            scanDirTracedLI(systemAppDir, mDefParseFlags
2409                    | PackageParser.PARSE_IS_SYSTEM
2410                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2411
2412            // Collect all vendor packages.
2413            File vendorAppDir = new File("/vendor/app");
2414            try {
2415                vendorAppDir = vendorAppDir.getCanonicalFile();
2416            } catch (IOException e) {
2417                // failed to look up canonical path, continue with original one
2418            }
2419            scanDirTracedLI(vendorAppDir, mDefParseFlags
2420                    | PackageParser.PARSE_IS_SYSTEM
2421                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2422
2423            // Collect all OEM packages.
2424            final File oemAppDir = new File(Environment.getOemDirectory(), "app");
2425            scanDirTracedLI(oemAppDir, mDefParseFlags
2426                    | PackageParser.PARSE_IS_SYSTEM
2427                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2428
2429            // Prune any system packages that no longer exist.
2430            final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>();
2431            if (!mOnlyCore) {
2432                Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
2433                while (psit.hasNext()) {
2434                    PackageSetting ps = psit.next();
2435
2436                    /*
2437                     * If this is not a system app, it can't be a
2438                     * disable system app.
2439                     */
2440                    if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
2441                        continue;
2442                    }
2443
2444                    /*
2445                     * If the package is scanned, it's not erased.
2446                     */
2447                    final PackageParser.Package scannedPkg = mPackages.get(ps.name);
2448                    if (scannedPkg != null) {
2449                        /*
2450                         * If the system app is both scanned and in the
2451                         * disabled packages list, then it must have been
2452                         * added via OTA. Remove it from the currently
2453                         * scanned package so the previously user-installed
2454                         * application can be scanned.
2455                         */
2456                        if (mSettings.isDisabledSystemPackageLPr(ps.name)) {
2457                            logCriticalInfo(Log.WARN, "Expecting better updated system app for "
2458                                    + ps.name + "; removing system app.  Last known codePath="
2459                                    + ps.codePathString + ", installStatus=" + ps.installStatus
2460                                    + ", versionCode=" + ps.versionCode + "; scanned versionCode="
2461                                    + scannedPkg.mVersionCode);
2462                            removePackageLI(scannedPkg, true);
2463                            mExpectingBetter.put(ps.name, ps.codePath);
2464                        }
2465
2466                        continue;
2467                    }
2468
2469                    if (!mSettings.isDisabledSystemPackageLPr(ps.name)) {
2470                        psit.remove();
2471                        logCriticalInfo(Log.WARN, "System package " + ps.name
2472                                + " no longer exists; it's data will be wiped");
2473                        // Actual deletion of code and data will be handled by later
2474                        // reconciliation step
2475                    } else {
2476                        final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name);
2477                        if (disabledPs.codePath == null || !disabledPs.codePath.exists()) {
2478                            possiblyDeletedUpdatedSystemApps.add(ps.name);
2479                        }
2480                    }
2481                }
2482            }
2483
2484            //look for any incomplete package installations
2485            ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr();
2486            for (int i = 0; i < deletePkgsList.size(); i++) {
2487                // Actual deletion of code and data will be handled by later
2488                // reconciliation step
2489                final String packageName = deletePkgsList.get(i).name;
2490                logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + packageName);
2491                synchronized (mPackages) {
2492                    mSettings.removePackageLPw(packageName);
2493                }
2494            }
2495
2496            //delete tmp files
2497            deleteTempPackageFiles();
2498
2499            // Remove any shared userIDs that have no associated packages
2500            mSettings.pruneSharedUsersLPw();
2501
2502            if (!mOnlyCore) {
2503                EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
2504                        SystemClock.uptimeMillis());
2505                scanDirTracedLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0);
2506
2507                scanDirTracedLI(mDrmAppPrivateInstallDir, mDefParseFlags
2508                        | PackageParser.PARSE_FORWARD_LOCK,
2509                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2510
2511                scanDirLI(mEphemeralInstallDir, mDefParseFlags
2512                        | PackageParser.PARSE_IS_EPHEMERAL,
2513                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2514
2515                /**
2516                 * Remove disable package settings for any updated system
2517                 * apps that were removed via an OTA. If they're not a
2518                 * previously-updated app, remove them completely.
2519                 * Otherwise, just revoke their system-level permissions.
2520                 */
2521                for (String deletedAppName : possiblyDeletedUpdatedSystemApps) {
2522                    PackageParser.Package deletedPkg = mPackages.get(deletedAppName);
2523                    mSettings.removeDisabledSystemPackageLPw(deletedAppName);
2524
2525                    String msg;
2526                    if (deletedPkg == null) {
2527                        msg = "Updated system package " + deletedAppName
2528                                + " no longer exists; it's data will be wiped";
2529                        // Actual deletion of code and data will be handled by later
2530                        // reconciliation step
2531                    } else {
2532                        msg = "Updated system app + " + deletedAppName
2533                                + " no longer present; removing system privileges for "
2534                                + deletedAppName;
2535
2536                        deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM;
2537
2538                        PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName);
2539                        deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM;
2540                    }
2541                    logCriticalInfo(Log.WARN, msg);
2542                }
2543
2544                /**
2545                 * Make sure all system apps that we expected to appear on
2546                 * the userdata partition actually showed up. If they never
2547                 * appeared, crawl back and revive the system version.
2548                 */
2549                for (int i = 0; i < mExpectingBetter.size(); i++) {
2550                    final String packageName = mExpectingBetter.keyAt(i);
2551                    if (!mPackages.containsKey(packageName)) {
2552                        final File scanFile = mExpectingBetter.valueAt(i);
2553
2554                        logCriticalInfo(Log.WARN, "Expected better " + packageName
2555                                + " but never showed up; reverting to system");
2556
2557                        int reparseFlags = mDefParseFlags;
2558                        if (FileUtils.contains(privilegedAppDir, scanFile)) {
2559                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2560                                    | PackageParser.PARSE_IS_SYSTEM_DIR
2561                                    | PackageParser.PARSE_IS_PRIVILEGED;
2562                        } else if (FileUtils.contains(systemAppDir, scanFile)) {
2563                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2564                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2565                        } else if (FileUtils.contains(vendorAppDir, scanFile)) {
2566                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2567                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2568                        } else if (FileUtils.contains(oemAppDir, scanFile)) {
2569                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2570                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2571                        } else {
2572                            Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile);
2573                            continue;
2574                        }
2575
2576                        mSettings.enableSystemPackageLPw(packageName);
2577
2578                        try {
2579                            scanPackageTracedLI(scanFile, reparseFlags, scanFlags, 0, null);
2580                        } catch (PackageManagerException e) {
2581                            Slog.e(TAG, "Failed to parse original system package: "
2582                                    + e.getMessage());
2583                        }
2584                    }
2585                }
2586            }
2587            mExpectingBetter.clear();
2588
2589            // Resolve protected action filters. Only the setup wizard is allowed to
2590            // have a high priority filter for these actions.
2591            mSetupWizardPackage = getSetupWizardPackageName();
2592            if (mProtectedFilters.size() > 0) {
2593                if (DEBUG_FILTERS && mSetupWizardPackage == null) {
2594                    Slog.i(TAG, "No setup wizard;"
2595                        + " All protected intents capped to priority 0");
2596                }
2597                for (ActivityIntentInfo filter : mProtectedFilters) {
2598                    if (filter.activity.info.packageName.equals(mSetupWizardPackage)) {
2599                        if (DEBUG_FILTERS) {
2600                            Slog.i(TAG, "Found setup wizard;"
2601                                + " allow priority " + filter.getPriority() + ";"
2602                                + " package: " + filter.activity.info.packageName
2603                                + " activity: " + filter.activity.className
2604                                + " priority: " + filter.getPriority());
2605                        }
2606                        // skip setup wizard; allow it to keep the high priority filter
2607                        continue;
2608                    }
2609                    Slog.w(TAG, "Protected action; cap priority to 0;"
2610                            + " package: " + filter.activity.info.packageName
2611                            + " activity: " + filter.activity.className
2612                            + " origPrio: " + filter.getPriority());
2613                    filter.setPriority(0);
2614                }
2615            }
2616            mDeferProtectedFilters = false;
2617            mProtectedFilters.clear();
2618
2619            // Now that we know all of the shared libraries, update all clients to have
2620            // the correct library paths.
2621            updateAllSharedLibrariesLPw();
2622
2623            for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) {
2624                // NOTE: We ignore potential failures here during a system scan (like
2625                // the rest of the commands above) because there's precious little we
2626                // can do about it. A settings error is reported, though.
2627                adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */,
2628                        false /* boot complete */);
2629            }
2630
2631            // Now that we know all the packages we are keeping,
2632            // read and update their last usage times.
2633            mPackageUsage.readLP();
2634
2635            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
2636                    SystemClock.uptimeMillis());
2637            Slog.i(TAG, "Time to scan packages: "
2638                    + ((SystemClock.uptimeMillis()-startTime)/1000f)
2639                    + " seconds");
2640
2641            // If the platform SDK has changed since the last time we booted,
2642            // we need to re-grant app permission to catch any new ones that
2643            // appear.  This is really a hack, and means that apps can in some
2644            // cases get permissions that the user didn't initially explicitly
2645            // allow...  it would be nice to have some better way to handle
2646            // this situation.
2647            int updateFlags = UPDATE_PERMISSIONS_ALL;
2648            if (ver.sdkVersion != mSdkVersion) {
2649                Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to "
2650                        + mSdkVersion + "; regranting permissions for internal storage");
2651                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
2652            }
2653            updatePermissionsLPw(null, null, StorageManager.UUID_PRIVATE_INTERNAL, updateFlags);
2654            ver.sdkVersion = mSdkVersion;
2655
2656            // If this is the first boot or an update from pre-M, and it is a normal
2657            // boot, then we need to initialize the default preferred apps across
2658            // all defined users.
2659            if (!onlyCore && (mPromoteSystemApps || !mRestoredSettings)) {
2660                for (UserInfo user : sUserManager.getUsers(true)) {
2661                    mSettings.applyDefaultPreferredAppsLPw(this, user.id);
2662                    applyFactoryDefaultBrowserLPw(user.id);
2663                    primeDomainVerificationsLPw(user.id);
2664                }
2665            }
2666
2667            // Prepare storage for system user really early during boot,
2668            // since core system apps like SettingsProvider and SystemUI
2669            // can't wait for user to start
2670            final int storageFlags;
2671            if (StorageManager.isFileEncryptedNativeOrEmulated()) {
2672                storageFlags = StorageManager.FLAG_STORAGE_DE;
2673            } else {
2674                storageFlags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
2675            }
2676            reconcileAppsDataLI(StorageManager.UUID_PRIVATE_INTERNAL, UserHandle.USER_SYSTEM,
2677                    storageFlags);
2678
2679            // If this is first boot after an OTA, and a normal boot, then
2680            // we need to clear code cache directories.
2681            if (mIsUpgrade && !onlyCore) {
2682                Slog.i(TAG, "Build fingerprint changed; clearing code caches");
2683                for (int i = 0; i < mSettings.mPackages.size(); i++) {
2684                    final PackageSetting ps = mSettings.mPackages.valueAt(i);
2685                    if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) {
2686                        // No apps are running this early, so no need to freeze
2687                        clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
2688                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
2689                                        | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
2690                    }
2691                    clearAppProfilesLIF(ps.pkg);
2692                }
2693                ver.fingerprint = Build.FINGERPRINT;
2694            }
2695
2696            checkDefaultBrowser();
2697
2698            // clear only after permissions and other defaults have been updated
2699            mExistingSystemPackages.clear();
2700            mPromoteSystemApps = false;
2701
2702            // All the changes are done during package scanning.
2703            ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION;
2704
2705            // can downgrade to reader
2706            mSettings.writeLPr();
2707
2708            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
2709                    SystemClock.uptimeMillis());
2710
2711            if (!mOnlyCore) {
2712                mRequiredVerifierPackage = getRequiredButNotReallyRequiredVerifierLPr();
2713                mRequiredInstallerPackage = getRequiredInstallerLPr();
2714                mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr();
2715                mIntentFilterVerifier = new IntentVerifierProxy(mContext,
2716                        mIntentFilterVerifierComponent);
2717                mServicesSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
2718                        PackageManager.SYSTEM_SHARED_LIBRARY_SERVICES);
2719                mSharedSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
2720                        PackageManager.SYSTEM_SHARED_LIBRARY_SHARED);
2721            } else {
2722                mRequiredVerifierPackage = null;
2723                mRequiredInstallerPackage = null;
2724                mIntentFilterVerifierComponent = null;
2725                mIntentFilterVerifier = null;
2726                mServicesSystemSharedLibraryPackageName = null;
2727                mSharedSystemSharedLibraryPackageName = null;
2728            }
2729
2730            mInstallerService = new PackageInstallerService(context, this);
2731
2732            final ComponentName ephemeralResolverComponent = getEphemeralResolverLPr();
2733            final ComponentName ephemeralInstallerComponent = getEphemeralInstallerLPr();
2734            // both the installer and resolver must be present to enable ephemeral
2735            if (ephemeralInstallerComponent != null && ephemeralResolverComponent != null) {
2736                if (DEBUG_EPHEMERAL) {
2737                    Slog.i(TAG, "Ephemeral activated; resolver: " + ephemeralResolverComponent
2738                            + " installer:" + ephemeralInstallerComponent);
2739                }
2740                mEphemeralResolverComponent = ephemeralResolverComponent;
2741                mEphemeralInstallerComponent = ephemeralInstallerComponent;
2742                setUpEphemeralInstallerActivityLP(mEphemeralInstallerComponent);
2743                mEphemeralResolverConnection =
2744                        new EphemeralResolverConnection(mContext, mEphemeralResolverComponent);
2745            } else {
2746                if (DEBUG_EPHEMERAL) {
2747                    final String missingComponent =
2748                            (ephemeralResolverComponent == null)
2749                            ? (ephemeralInstallerComponent == null)
2750                                    ? "resolver and installer"
2751                                    : "resolver"
2752                            : "installer";
2753                    Slog.i(TAG, "Ephemeral deactivated; missing " + missingComponent);
2754                }
2755                mEphemeralResolverComponent = null;
2756                mEphemeralInstallerComponent = null;
2757                mEphemeralResolverConnection = null;
2758            }
2759
2760            mEphemeralApplicationRegistry = new EphemeralApplicationRegistry(this);
2761        } // synchronized (mPackages)
2762        } // synchronized (mInstallLock)
2763
2764        // Now after opening every single application zip, make sure they
2765        // are all flushed.  Not really needed, but keeps things nice and
2766        // tidy.
2767        Runtime.getRuntime().gc();
2768
2769        // The initial scanning above does many calls into installd while
2770        // holding the mPackages lock, but we're mostly interested in yelling
2771        // once we have a booted system.
2772        mInstaller.setWarnIfHeld(mPackages);
2773
2774        // Expose private service for system components to use.
2775        LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl());
2776    }
2777
2778    @Override
2779    public boolean isFirstBoot() {
2780        return !mRestoredSettings;
2781    }
2782
2783    @Override
2784    public boolean isOnlyCoreApps() {
2785        return mOnlyCore;
2786    }
2787
2788    @Override
2789    public boolean isUpgrade() {
2790        return mIsUpgrade;
2791    }
2792
2793    private @Nullable String getRequiredButNotReallyRequiredVerifierLPr() {
2794        final Intent intent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
2795
2796        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
2797                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
2798                UserHandle.USER_SYSTEM);
2799        if (matches.size() == 1) {
2800            return matches.get(0).getComponentInfo().packageName;
2801        } else {
2802            Log.e(TAG, "There should probably be exactly one verifier; found " + matches);
2803            return null;
2804        }
2805    }
2806
2807    private @NonNull String getRequiredSharedLibraryLPr(String libraryName) {
2808        synchronized (mPackages) {
2809            SharedLibraryEntry libraryEntry = mSharedLibraries.get(libraryName);
2810            if (libraryEntry == null) {
2811                throw new IllegalStateException("Missing required shared library:" + libraryName);
2812            }
2813            return libraryEntry.apk;
2814        }
2815    }
2816
2817    private @NonNull String getRequiredInstallerLPr() {
2818        final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
2819        intent.addCategory(Intent.CATEGORY_DEFAULT);
2820        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
2821
2822        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
2823                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
2824                UserHandle.USER_SYSTEM);
2825        if (matches.size() == 1) {
2826            ResolveInfo resolveInfo = matches.get(0);
2827            if (!resolveInfo.activityInfo.applicationInfo.isPrivilegedApp()) {
2828                throw new RuntimeException("The installer must be a privileged app");
2829            }
2830            return matches.get(0).getComponentInfo().packageName;
2831        } else {
2832            throw new RuntimeException("There must be exactly one installer; found " + matches);
2833        }
2834    }
2835
2836    private @NonNull ComponentName getIntentFilterVerifierComponentNameLPr() {
2837        final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
2838
2839        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
2840                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
2841                UserHandle.USER_SYSTEM);
2842        ResolveInfo best = null;
2843        final int N = matches.size();
2844        for (int i = 0; i < N; i++) {
2845            final ResolveInfo cur = matches.get(i);
2846            final String packageName = cur.getComponentInfo().packageName;
2847            if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
2848                    packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) {
2849                continue;
2850            }
2851
2852            if (best == null || cur.priority > best.priority) {
2853                best = cur;
2854            }
2855        }
2856
2857        if (best != null) {
2858            return best.getComponentInfo().getComponentName();
2859        } else {
2860            throw new RuntimeException("There must be at least one intent filter verifier");
2861        }
2862    }
2863
2864    private @Nullable ComponentName getEphemeralResolverLPr() {
2865        final String[] packageArray =
2866                mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage);
2867        if (packageArray.length == 0) {
2868            if (DEBUG_EPHEMERAL) {
2869                Slog.d(TAG, "Ephemeral resolver NOT found; empty package list");
2870            }
2871            return null;
2872        }
2873
2874        final Intent resolverIntent = new Intent(Intent.ACTION_RESOLVE_EPHEMERAL_PACKAGE);
2875        final List<ResolveInfo> resolvers = queryIntentServicesInternal(resolverIntent, null,
2876                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
2877                UserHandle.USER_SYSTEM);
2878
2879        final int N = resolvers.size();
2880        if (N == 0) {
2881            if (DEBUG_EPHEMERAL) {
2882                Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters");
2883            }
2884            return null;
2885        }
2886
2887        final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray));
2888        for (int i = 0; i < N; i++) {
2889            final ResolveInfo info = resolvers.get(i);
2890
2891            if (info.serviceInfo == null) {
2892                continue;
2893            }
2894
2895            final String packageName = info.serviceInfo.packageName;
2896            if (!possiblePackages.contains(packageName)) {
2897                if (DEBUG_EPHEMERAL) {
2898                    Slog.d(TAG, "Ephemeral resolver not in allowed package list;"
2899                            + " pkg: " + packageName + ", info:" + info);
2900                }
2901                continue;
2902            }
2903
2904            if (DEBUG_EPHEMERAL) {
2905                Slog.v(TAG, "Ephemeral resolver found;"
2906                        + " pkg: " + packageName + ", info:" + info);
2907            }
2908            return new ComponentName(packageName, info.serviceInfo.name);
2909        }
2910        if (DEBUG_EPHEMERAL) {
2911            Slog.v(TAG, "Ephemeral resolver NOT found");
2912        }
2913        return null;
2914    }
2915
2916    private @Nullable ComponentName getEphemeralInstallerLPr() {
2917        final Intent intent = new Intent(Intent.ACTION_INSTALL_EPHEMERAL_PACKAGE);
2918        intent.addCategory(Intent.CATEGORY_DEFAULT);
2919        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
2920
2921        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
2922                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
2923                UserHandle.USER_SYSTEM);
2924        if (matches.size() == 0) {
2925            return null;
2926        } else if (matches.size() == 1) {
2927            return matches.get(0).getComponentInfo().getComponentName();
2928        } else {
2929            throw new RuntimeException(
2930                    "There must be at most one ephemeral installer; found " + matches);
2931        }
2932    }
2933
2934    private void primeDomainVerificationsLPw(int userId) {
2935        if (DEBUG_DOMAIN_VERIFICATION) {
2936            Slog.d(TAG, "Priming domain verifications in user " + userId);
2937        }
2938
2939        SystemConfig systemConfig = SystemConfig.getInstance();
2940        ArraySet<String> packages = systemConfig.getLinkedApps();
2941        ArraySet<String> domains = new ArraySet<String>();
2942
2943        for (String packageName : packages) {
2944            PackageParser.Package pkg = mPackages.get(packageName);
2945            if (pkg != null) {
2946                if (!pkg.isSystemApp()) {
2947                    Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>");
2948                    continue;
2949                }
2950
2951                domains.clear();
2952                for (PackageParser.Activity a : pkg.activities) {
2953                    for (ActivityIntentInfo filter : a.intents) {
2954                        if (hasValidDomains(filter)) {
2955                            domains.addAll(filter.getHostsList());
2956                        }
2957                    }
2958                }
2959
2960                if (domains.size() > 0) {
2961                    if (DEBUG_DOMAIN_VERIFICATION) {
2962                        Slog.v(TAG, "      + " + packageName);
2963                    }
2964                    // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual
2965                    // state w.r.t. the formal app-linkage "no verification attempted" state;
2966                    // and then 'always' in the per-user state actually used for intent resolution.
2967                    final IntentFilterVerificationInfo ivi;
2968                    ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName,
2969                            new ArrayList<String>(domains));
2970                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED);
2971                    mSettings.updateIntentFilterVerificationStatusLPw(packageName,
2972                            INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId);
2973                } else {
2974                    Slog.w(TAG, "Sysconfig <app-link> package '" + packageName
2975                            + "' does not handle web links");
2976                }
2977            } else {
2978                Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>");
2979            }
2980        }
2981
2982        scheduleWritePackageRestrictionsLocked(userId);
2983        scheduleWriteSettingsLocked();
2984    }
2985
2986    private void applyFactoryDefaultBrowserLPw(int userId) {
2987        // The default browser app's package name is stored in a string resource,
2988        // with a product-specific overlay used for vendor customization.
2989        String browserPkg = mContext.getResources().getString(
2990                com.android.internal.R.string.default_browser);
2991        if (!TextUtils.isEmpty(browserPkg)) {
2992            // non-empty string => required to be a known package
2993            PackageSetting ps = mSettings.mPackages.get(browserPkg);
2994            if (ps == null) {
2995                Slog.e(TAG, "Product default browser app does not exist: " + browserPkg);
2996                browserPkg = null;
2997            } else {
2998                mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
2999            }
3000        }
3001
3002        // Nothing valid explicitly set? Make the factory-installed browser the explicit
3003        // default.  If there's more than one, just leave everything alone.
3004        if (browserPkg == null) {
3005            calculateDefaultBrowserLPw(userId);
3006        }
3007    }
3008
3009    private void calculateDefaultBrowserLPw(int userId) {
3010        List<String> allBrowsers = resolveAllBrowserApps(userId);
3011        final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null;
3012        mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
3013    }
3014
3015    private List<String> resolveAllBrowserApps(int userId) {
3016        // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set
3017        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
3018                PackageManager.MATCH_ALL, userId);
3019
3020        final int count = list.size();
3021        List<String> result = new ArrayList<String>(count);
3022        for (int i=0; i<count; i++) {
3023            ResolveInfo info = list.get(i);
3024            if (info.activityInfo == null
3025                    || !info.handleAllWebDataURI
3026                    || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0
3027                    || result.contains(info.activityInfo.packageName)) {
3028                continue;
3029            }
3030            result.add(info.activityInfo.packageName);
3031        }
3032
3033        return result;
3034    }
3035
3036    private boolean packageIsBrowser(String packageName, int userId) {
3037        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
3038                PackageManager.MATCH_ALL, userId);
3039        final int N = list.size();
3040        for (int i = 0; i < N; i++) {
3041            ResolveInfo info = list.get(i);
3042            if (packageName.equals(info.activityInfo.packageName)) {
3043                return true;
3044            }
3045        }
3046        return false;
3047    }
3048
3049    private void checkDefaultBrowser() {
3050        final int myUserId = UserHandle.myUserId();
3051        final String packageName = getDefaultBrowserPackageName(myUserId);
3052        if (packageName != null) {
3053            PackageInfo info = getPackageInfo(packageName, 0, myUserId);
3054            if (info == null) {
3055                Slog.w(TAG, "Default browser no longer installed: " + packageName);
3056                synchronized (mPackages) {
3057                    applyFactoryDefaultBrowserLPw(myUserId);    // leaves ambiguous when > 1
3058                }
3059            }
3060        }
3061    }
3062
3063    @Override
3064    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
3065            throws RemoteException {
3066        try {
3067            return super.onTransact(code, data, reply, flags);
3068        } catch (RuntimeException e) {
3069            if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
3070                Slog.wtf(TAG, "Package Manager Crash", e);
3071            }
3072            throw e;
3073        }
3074    }
3075
3076    static int[] appendInts(int[] cur, int[] add) {
3077        if (add == null) return cur;
3078        if (cur == null) return add;
3079        final int N = add.length;
3080        for (int i=0; i<N; i++) {
3081            cur = appendInt(cur, add[i]);
3082        }
3083        return cur;
3084    }
3085
3086    private PackageInfo generatePackageInfo(PackageSetting ps, int flags, int userId) {
3087        if (!sUserManager.exists(userId)) return null;
3088        if (ps == null) {
3089            return null;
3090        }
3091        final PackageParser.Package p = ps.pkg;
3092        if (p == null) {
3093            return null;
3094        }
3095
3096        final PermissionsState permissionsState = ps.getPermissionsState();
3097
3098        final int[] gids = permissionsState.computeGids(userId);
3099        final Set<String> permissions = permissionsState.getPermissions(userId);
3100        final PackageUserState state = ps.readUserState(userId);
3101
3102        return PackageParser.generatePackageInfo(p, gids, flags,
3103                ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId);
3104    }
3105
3106    @Override
3107    public void checkPackageStartable(String packageName, int userId) {
3108        final boolean userKeyUnlocked = isUserKeyUnlocked(userId);
3109
3110        synchronized (mPackages) {
3111            final PackageSetting ps = mSettings.mPackages.get(packageName);
3112            if (ps == null) {
3113                throw new SecurityException("Package " + packageName + " was not found!");
3114            }
3115
3116            if (!ps.getInstalled(userId)) {
3117                throw new SecurityException(
3118                        "Package " + packageName + " was not installed for user " + userId + "!");
3119            }
3120
3121            if (mSafeMode && !ps.isSystem()) {
3122                throw new SecurityException("Package " + packageName + " not a system app!");
3123            }
3124
3125            if (mFrozenPackages.contains(packageName)) {
3126                throw new SecurityException("Package " + packageName + " is currently frozen!");
3127            }
3128
3129            if (!userKeyUnlocked && !(ps.pkg.applicationInfo.isDirectBootAware()
3130                    || ps.pkg.applicationInfo.isPartiallyDirectBootAware())) {
3131                throw new SecurityException("Package " + packageName + " is not encryption aware!");
3132            }
3133        }
3134    }
3135
3136    @Override
3137    public boolean isPackageAvailable(String packageName, int userId) {
3138        if (!sUserManager.exists(userId)) return false;
3139        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3140                false /* requireFullPermission */, false /* checkShell */, "is package available");
3141        synchronized (mPackages) {
3142            PackageParser.Package p = mPackages.get(packageName);
3143            if (p != null) {
3144                final PackageSetting ps = (PackageSetting) p.mExtras;
3145                if (ps != null) {
3146                    final PackageUserState state = ps.readUserState(userId);
3147                    if (state != null) {
3148                        return PackageParser.isAvailable(state);
3149                    }
3150                }
3151            }
3152        }
3153        return false;
3154    }
3155
3156    @Override
3157    public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
3158        if (!sUserManager.exists(userId)) return null;
3159        flags = updateFlagsForPackage(flags, userId, packageName);
3160        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3161                false /* requireFullPermission */, false /* checkShell */, "get package info");
3162        // reader
3163        synchronized (mPackages) {
3164            final boolean matchFactoryOnly = (flags & MATCH_FACTORY_ONLY) != 0;
3165            PackageParser.Package p = null;
3166            if (matchFactoryOnly) {
3167                final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName);
3168                if (ps != null) {
3169                    return generatePackageInfo(ps, flags, userId);
3170                }
3171            }
3172            if (p == null) {
3173                p = mPackages.get(packageName);
3174                if (matchFactoryOnly && p != null && !isSystemApp(p)) {
3175                    return null;
3176                }
3177            }
3178            if (DEBUG_PACKAGE_INFO)
3179                Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
3180            if (p != null) {
3181                return generatePackageInfo((PackageSetting)p.mExtras, flags, userId);
3182            }
3183            if (!matchFactoryOnly && (flags & MATCH_UNINSTALLED_PACKAGES) != 0) {
3184                final PackageSetting ps = mSettings.mPackages.get(packageName);
3185                return generatePackageInfo(ps, flags, userId);
3186            }
3187        }
3188        return null;
3189    }
3190
3191    @Override
3192    public String[] currentToCanonicalPackageNames(String[] names) {
3193        String[] out = new String[names.length];
3194        // reader
3195        synchronized (mPackages) {
3196            for (int i=names.length-1; i>=0; i--) {
3197                PackageSetting ps = mSettings.mPackages.get(names[i]);
3198                out[i] = ps != null && ps.realName != null ? ps.realName : names[i];
3199            }
3200        }
3201        return out;
3202    }
3203
3204    @Override
3205    public String[] canonicalToCurrentPackageNames(String[] names) {
3206        String[] out = new String[names.length];
3207        // reader
3208        synchronized (mPackages) {
3209            for (int i=names.length-1; i>=0; i--) {
3210                String cur = mSettings.mRenamedPackages.get(names[i]);
3211                out[i] = cur != null ? cur : names[i];
3212            }
3213        }
3214        return out;
3215    }
3216
3217    @Override
3218    public int getPackageUid(String packageName, int flags, int userId) {
3219        if (!sUserManager.exists(userId)) return -1;
3220        flags = updateFlagsForPackage(flags, userId, packageName);
3221        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3222                false /* requireFullPermission */, false /* checkShell */, "get package uid");
3223
3224        // reader
3225        synchronized (mPackages) {
3226            final PackageParser.Package p = mPackages.get(packageName);
3227            if (p != null && p.isMatch(flags)) {
3228                return UserHandle.getUid(userId, p.applicationInfo.uid);
3229            }
3230            if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) {
3231                final PackageSetting ps = mSettings.mPackages.get(packageName);
3232                if (ps != null && ps.isMatch(flags)) {
3233                    return UserHandle.getUid(userId, ps.appId);
3234                }
3235            }
3236        }
3237
3238        return -1;
3239    }
3240
3241    @Override
3242    public int[] getPackageGids(String packageName, int flags, int userId) {
3243        if (!sUserManager.exists(userId)) return null;
3244        flags = updateFlagsForPackage(flags, userId, packageName);
3245        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3246                false /* requireFullPermission */, false /* checkShell */,
3247                "getPackageGids");
3248
3249        // reader
3250        synchronized (mPackages) {
3251            final PackageParser.Package p = mPackages.get(packageName);
3252            if (p != null && p.isMatch(flags)) {
3253                PackageSetting ps = (PackageSetting) p.mExtras;
3254                return ps.getPermissionsState().computeGids(userId);
3255            }
3256            if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) {
3257                final PackageSetting ps = mSettings.mPackages.get(packageName);
3258                if (ps != null && ps.isMatch(flags)) {
3259                    return ps.getPermissionsState().computeGids(userId);
3260                }
3261            }
3262        }
3263
3264        return null;
3265    }
3266
3267    static PermissionInfo generatePermissionInfo(BasePermission bp, int flags) {
3268        if (bp.perm != null) {
3269            return PackageParser.generatePermissionInfo(bp.perm, flags);
3270        }
3271        PermissionInfo pi = new PermissionInfo();
3272        pi.name = bp.name;
3273        pi.packageName = bp.sourcePackage;
3274        pi.nonLocalizedLabel = bp.name;
3275        pi.protectionLevel = bp.protectionLevel;
3276        return pi;
3277    }
3278
3279    @Override
3280    public PermissionInfo getPermissionInfo(String name, int flags) {
3281        // reader
3282        synchronized (mPackages) {
3283            final BasePermission p = mSettings.mPermissions.get(name);
3284            if (p != null) {
3285                return generatePermissionInfo(p, flags);
3286            }
3287            return null;
3288        }
3289    }
3290
3291    @Override
3292    public @Nullable ParceledListSlice<PermissionInfo> queryPermissionsByGroup(String group,
3293            int flags) {
3294        // reader
3295        synchronized (mPackages) {
3296            if (group != null && !mPermissionGroups.containsKey(group)) {
3297                // This is thrown as NameNotFoundException
3298                return null;
3299            }
3300
3301            ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
3302            for (BasePermission p : mSettings.mPermissions.values()) {
3303                if (group == null) {
3304                    if (p.perm == null || p.perm.info.group == null) {
3305                        out.add(generatePermissionInfo(p, flags));
3306                    }
3307                } else {
3308                    if (p.perm != null && group.equals(p.perm.info.group)) {
3309                        out.add(PackageParser.generatePermissionInfo(p.perm, flags));
3310                    }
3311                }
3312            }
3313            return new ParceledListSlice<>(out);
3314        }
3315    }
3316
3317    @Override
3318    public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
3319        // reader
3320        synchronized (mPackages) {
3321            return PackageParser.generatePermissionGroupInfo(
3322                    mPermissionGroups.get(name), flags);
3323        }
3324    }
3325
3326    @Override
3327    public @NonNull ParceledListSlice<PermissionGroupInfo> getAllPermissionGroups(int flags) {
3328        // reader
3329        synchronized (mPackages) {
3330            final int N = mPermissionGroups.size();
3331            ArrayList<PermissionGroupInfo> out
3332                    = new ArrayList<PermissionGroupInfo>(N);
3333            for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
3334                out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
3335            }
3336            return new ParceledListSlice<>(out);
3337        }
3338    }
3339
3340    private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
3341            int userId) {
3342        if (!sUserManager.exists(userId)) return null;
3343        PackageSetting ps = mSettings.mPackages.get(packageName);
3344        if (ps != null) {
3345            if (ps.pkg == null) {
3346                final PackageInfo pInfo = generatePackageInfo(ps, flags, userId);
3347                if (pInfo != null) {
3348                    return pInfo.applicationInfo;
3349                }
3350                return null;
3351            }
3352            return PackageParser.generateApplicationInfo(ps.pkg, flags,
3353                    ps.readUserState(userId), userId);
3354        }
3355        return null;
3356    }
3357
3358    @Override
3359    public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
3360        if (!sUserManager.exists(userId)) return null;
3361        flags = updateFlagsForApplication(flags, userId, packageName);
3362        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3363                false /* requireFullPermission */, false /* checkShell */, "get application info");
3364        // writer
3365        synchronized (mPackages) {
3366            PackageParser.Package p = mPackages.get(packageName);
3367            if (DEBUG_PACKAGE_INFO) Log.v(
3368                    TAG, "getApplicationInfo " + packageName
3369                    + ": " + p);
3370            if (p != null) {
3371                PackageSetting ps = mSettings.mPackages.get(packageName);
3372                if (ps == null) return null;
3373                // Note: isEnabledLP() does not apply here - always return info
3374                return PackageParser.generateApplicationInfo(
3375                        p, flags, ps.readUserState(userId), userId);
3376            }
3377            if ("android".equals(packageName)||"system".equals(packageName)) {
3378                return mAndroidApplication;
3379            }
3380            if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) {
3381                return generateApplicationInfoFromSettingsLPw(packageName, flags, userId);
3382            }
3383        }
3384        return null;
3385    }
3386
3387    @Override
3388    public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize,
3389            final IPackageDataObserver observer) {
3390        mContext.enforceCallingOrSelfPermission(
3391                android.Manifest.permission.CLEAR_APP_CACHE, null);
3392        // Queue up an async operation since clearing cache may take a little while.
3393        mHandler.post(new Runnable() {
3394            public void run() {
3395                mHandler.removeCallbacks(this);
3396                boolean success = true;
3397                synchronized (mInstallLock) {
3398                    try {
3399                        mInstaller.freeCache(volumeUuid, freeStorageSize);
3400                    } catch (InstallerException e) {
3401                        Slog.w(TAG, "Couldn't clear application caches: " + e);
3402                        success = false;
3403                    }
3404                }
3405                if (observer != null) {
3406                    try {
3407                        observer.onRemoveCompleted(null, success);
3408                    } catch (RemoteException e) {
3409                        Slog.w(TAG, "RemoveException when invoking call back");
3410                    }
3411                }
3412            }
3413        });
3414    }
3415
3416    @Override
3417    public void freeStorage(final String volumeUuid, final long freeStorageSize,
3418            final IntentSender pi) {
3419        mContext.enforceCallingOrSelfPermission(
3420                android.Manifest.permission.CLEAR_APP_CACHE, null);
3421        // Queue up an async operation since clearing cache may take a little while.
3422        mHandler.post(new Runnable() {
3423            public void run() {
3424                mHandler.removeCallbacks(this);
3425                boolean success = true;
3426                synchronized (mInstallLock) {
3427                    try {
3428                        mInstaller.freeCache(volumeUuid, freeStorageSize);
3429                    } catch (InstallerException e) {
3430                        Slog.w(TAG, "Couldn't clear application caches: " + e);
3431                        success = false;
3432                    }
3433                }
3434                if(pi != null) {
3435                    try {
3436                        // Callback via pending intent
3437                        int code = success ? 1 : 0;
3438                        pi.sendIntent(null, code, null,
3439                                null, null);
3440                    } catch (SendIntentException e1) {
3441                        Slog.i(TAG, "Failed to send pending intent");
3442                    }
3443                }
3444            }
3445        });
3446    }
3447
3448    void freeStorage(String volumeUuid, long freeStorageSize) throws IOException {
3449        synchronized (mInstallLock) {
3450            try {
3451                mInstaller.freeCache(volumeUuid, freeStorageSize);
3452            } catch (InstallerException e) {
3453                throw new IOException("Failed to free enough space", e);
3454            }
3455        }
3456    }
3457
3458    /**
3459     * Return if the user key is currently unlocked.
3460     */
3461    private boolean isUserKeyUnlocked(int userId) {
3462        if (StorageManager.isFileEncryptedNativeOrEmulated()) {
3463            final IMountService mount = IMountService.Stub
3464                    .asInterface(ServiceManager.getService("mount"));
3465            if (mount == null) {
3466                Slog.w(TAG, "Early during boot, assuming locked");
3467                return false;
3468            }
3469            final long token = Binder.clearCallingIdentity();
3470            try {
3471                return mount.isUserKeyUnlocked(userId);
3472            } catch (RemoteException e) {
3473                throw e.rethrowAsRuntimeException();
3474            } finally {
3475                Binder.restoreCallingIdentity(token);
3476            }
3477        } else {
3478            return true;
3479        }
3480    }
3481
3482    /**
3483     * Update given flags based on encryption status of current user.
3484     */
3485    private int updateFlags(int flags, int userId) {
3486        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
3487                | PackageManager.MATCH_DIRECT_BOOT_AWARE)) != 0) {
3488            // Caller expressed an explicit opinion about what encryption
3489            // aware/unaware components they want to see, so fall through and
3490            // give them what they want
3491        } else {
3492            // Caller expressed no opinion, so match based on user state
3493            if (isUserKeyUnlocked(userId)) {
3494                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE;
3495            } else {
3496                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE;
3497            }
3498        }
3499        return flags;
3500    }
3501
3502    /**
3503     * Update given flags when being used to request {@link PackageInfo}.
3504     */
3505    private int updateFlagsForPackage(int flags, int userId, Object cookie) {
3506        boolean triaged = true;
3507        if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS
3508                | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) {
3509            // Caller is asking for component details, so they'd better be
3510            // asking for specific encryption matching behavior, or be triaged
3511            if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
3512                    | PackageManager.MATCH_DIRECT_BOOT_AWARE
3513                    | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
3514                triaged = false;
3515            }
3516        }
3517        if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES
3518                | PackageManager.MATCH_SYSTEM_ONLY
3519                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
3520            triaged = false;
3521        }
3522        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
3523            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
3524                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
3525        }
3526        return updateFlags(flags, userId);
3527    }
3528
3529    /**
3530     * Update given flags when being used to request {@link ApplicationInfo}.
3531     */
3532    private int updateFlagsForApplication(int flags, int userId, Object cookie) {
3533        return updateFlagsForPackage(flags, userId, cookie);
3534    }
3535
3536    /**
3537     * Update given flags when being used to request {@link ComponentInfo}.
3538     */
3539    private int updateFlagsForComponent(int flags, int userId, Object cookie) {
3540        if (cookie instanceof Intent) {
3541            if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) {
3542                flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
3543            }
3544        }
3545
3546        boolean triaged = true;
3547        // Caller is asking for component details, so they'd better be
3548        // asking for specific encryption matching behavior, or be triaged
3549        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
3550                | PackageManager.MATCH_DIRECT_BOOT_AWARE
3551                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
3552            triaged = false;
3553        }
3554        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
3555            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
3556                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
3557        }
3558
3559        return updateFlags(flags, userId);
3560    }
3561
3562    /**
3563     * Update given flags when being used to request {@link ResolveInfo}.
3564     */
3565    int updateFlagsForResolve(int flags, int userId, Object cookie) {
3566        // Safe mode means we shouldn't match any third-party components
3567        if (mSafeMode) {
3568            flags |= PackageManager.MATCH_SYSTEM_ONLY;
3569        }
3570
3571        return updateFlagsForComponent(flags, userId, cookie);
3572    }
3573
3574    @Override
3575    public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
3576        if (!sUserManager.exists(userId)) return null;
3577        flags = updateFlagsForComponent(flags, userId, component);
3578        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3579                false /* requireFullPermission */, false /* checkShell */, "get activity info");
3580        synchronized (mPackages) {
3581            PackageParser.Activity a = mActivities.mActivities.get(component);
3582
3583            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
3584            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
3585                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3586                if (ps == null) return null;
3587                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
3588                        userId);
3589            }
3590            if (mResolveComponentName.equals(component)) {
3591                return PackageParser.generateActivityInfo(mResolveActivity, flags,
3592                        new PackageUserState(), userId);
3593            }
3594        }
3595        return null;
3596    }
3597
3598    @Override
3599    public boolean activitySupportsIntent(ComponentName component, Intent intent,
3600            String resolvedType) {
3601        synchronized (mPackages) {
3602            if (component.equals(mResolveComponentName)) {
3603                // The resolver supports EVERYTHING!
3604                return true;
3605            }
3606            PackageParser.Activity a = mActivities.mActivities.get(component);
3607            if (a == null) {
3608                return false;
3609            }
3610            for (int i=0; i<a.intents.size(); i++) {
3611                if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
3612                        intent.getData(), intent.getCategories(), TAG) >= 0) {
3613                    return true;
3614                }
3615            }
3616            return false;
3617        }
3618    }
3619
3620    @Override
3621    public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
3622        if (!sUserManager.exists(userId)) return null;
3623        flags = updateFlagsForComponent(flags, userId, component);
3624        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3625                false /* requireFullPermission */, false /* checkShell */, "get receiver info");
3626        synchronized (mPackages) {
3627            PackageParser.Activity a = mReceivers.mActivities.get(component);
3628            if (DEBUG_PACKAGE_INFO) Log.v(
3629                TAG, "getReceiverInfo " + component + ": " + a);
3630            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
3631                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3632                if (ps == null) return null;
3633                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
3634                        userId);
3635            }
3636        }
3637        return null;
3638    }
3639
3640    @Override
3641    public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
3642        if (!sUserManager.exists(userId)) return null;
3643        flags = updateFlagsForComponent(flags, userId, component);
3644        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3645                false /* requireFullPermission */, false /* checkShell */, "get service info");
3646        synchronized (mPackages) {
3647            PackageParser.Service s = mServices.mServices.get(component);
3648            if (DEBUG_PACKAGE_INFO) Log.v(
3649                TAG, "getServiceInfo " + component + ": " + s);
3650            if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) {
3651                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3652                if (ps == null) return null;
3653                return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId),
3654                        userId);
3655            }
3656        }
3657        return null;
3658    }
3659
3660    @Override
3661    public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
3662        if (!sUserManager.exists(userId)) return null;
3663        flags = updateFlagsForComponent(flags, userId, component);
3664        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3665                false /* requireFullPermission */, false /* checkShell */, "get provider info");
3666        synchronized (mPackages) {
3667            PackageParser.Provider p = mProviders.mProviders.get(component);
3668            if (DEBUG_PACKAGE_INFO) Log.v(
3669                TAG, "getProviderInfo " + component + ": " + p);
3670            if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
3671                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3672                if (ps == null) return null;
3673                return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId),
3674                        userId);
3675            }
3676        }
3677        return null;
3678    }
3679
3680    @Override
3681    public String[] getSystemSharedLibraryNames() {
3682        Set<String> libSet;
3683        synchronized (mPackages) {
3684            libSet = mSharedLibraries.keySet();
3685            int size = libSet.size();
3686            if (size > 0) {
3687                String[] libs = new String[size];
3688                libSet.toArray(libs);
3689                return libs;
3690            }
3691        }
3692        return null;
3693    }
3694
3695    @Override
3696    public @NonNull String getServicesSystemSharedLibraryPackageName() {
3697        synchronized (mPackages) {
3698            return mServicesSystemSharedLibraryPackageName;
3699        }
3700    }
3701
3702    @Override
3703    public @NonNull String getSharedSystemSharedLibraryPackageName() {
3704        synchronized (mPackages) {
3705            return mSharedSystemSharedLibraryPackageName;
3706        }
3707    }
3708
3709    @Override
3710    public @NonNull ParceledListSlice<FeatureInfo> getSystemAvailableFeatures() {
3711        synchronized (mPackages) {
3712            final ArrayList<FeatureInfo> res = new ArrayList<>(mAvailableFeatures.values());
3713
3714            final FeatureInfo fi = new FeatureInfo();
3715            fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
3716                    FeatureInfo.GL_ES_VERSION_UNDEFINED);
3717            res.add(fi);
3718
3719            return new ParceledListSlice<>(res);
3720        }
3721    }
3722
3723    @Override
3724    public boolean hasSystemFeature(String name, int version) {
3725        synchronized (mPackages) {
3726            final FeatureInfo feat = mAvailableFeatures.get(name);
3727            if (feat == null) {
3728                return false;
3729            } else {
3730                return feat.version >= version;
3731            }
3732        }
3733    }
3734
3735    @Override
3736    public int checkPermission(String permName, String pkgName, int userId) {
3737        if (!sUserManager.exists(userId)) {
3738            return PackageManager.PERMISSION_DENIED;
3739        }
3740
3741        synchronized (mPackages) {
3742            final PackageParser.Package p = mPackages.get(pkgName);
3743            if (p != null && p.mExtras != null) {
3744                final PackageSetting ps = (PackageSetting) p.mExtras;
3745                final PermissionsState permissionsState = ps.getPermissionsState();
3746                if (permissionsState.hasPermission(permName, userId)) {
3747                    return PackageManager.PERMISSION_GRANTED;
3748                }
3749                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
3750                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
3751                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
3752                    return PackageManager.PERMISSION_GRANTED;
3753                }
3754            }
3755        }
3756
3757        return PackageManager.PERMISSION_DENIED;
3758    }
3759
3760    @Override
3761    public int checkUidPermission(String permName, int uid) {
3762        final int userId = UserHandle.getUserId(uid);
3763
3764        if (!sUserManager.exists(userId)) {
3765            return PackageManager.PERMISSION_DENIED;
3766        }
3767
3768        synchronized (mPackages) {
3769            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
3770            if (obj != null) {
3771                final SettingBase ps = (SettingBase) obj;
3772                final PermissionsState permissionsState = ps.getPermissionsState();
3773                if (permissionsState.hasPermission(permName, userId)) {
3774                    return PackageManager.PERMISSION_GRANTED;
3775                }
3776                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
3777                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
3778                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
3779                    return PackageManager.PERMISSION_GRANTED;
3780                }
3781            } else {
3782                ArraySet<String> perms = mSystemPermissions.get(uid);
3783                if (perms != null) {
3784                    if (perms.contains(permName)) {
3785                        return PackageManager.PERMISSION_GRANTED;
3786                    }
3787                    if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms
3788                            .contains(Manifest.permission.ACCESS_FINE_LOCATION)) {
3789                        return PackageManager.PERMISSION_GRANTED;
3790                    }
3791                }
3792            }
3793        }
3794
3795        return PackageManager.PERMISSION_DENIED;
3796    }
3797
3798    @Override
3799    public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) {
3800        if (UserHandle.getCallingUserId() != userId) {
3801            mContext.enforceCallingPermission(
3802                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
3803                    "isPermissionRevokedByPolicy for user " + userId);
3804        }
3805
3806        if (checkPermission(permission, packageName, userId)
3807                == PackageManager.PERMISSION_GRANTED) {
3808            return false;
3809        }
3810
3811        final long identity = Binder.clearCallingIdentity();
3812        try {
3813            final int flags = getPermissionFlags(permission, packageName, userId);
3814            return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0;
3815        } finally {
3816            Binder.restoreCallingIdentity(identity);
3817        }
3818    }
3819
3820    @Override
3821    public String getPermissionControllerPackageName() {
3822        synchronized (mPackages) {
3823            return mRequiredInstallerPackage;
3824        }
3825    }
3826
3827    /**
3828     * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS
3829     * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller.
3830     * @param checkShell whether to prevent shell from access if there's a debugging restriction
3831     * @param message the message to log on security exception
3832     */
3833    void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission,
3834            boolean checkShell, String message) {
3835        if (userId < 0) {
3836            throw new IllegalArgumentException("Invalid userId " + userId);
3837        }
3838        if (checkShell) {
3839            enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId);
3840        }
3841        if (userId == UserHandle.getUserId(callingUid)) return;
3842        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
3843            if (requireFullPermission) {
3844                mContext.enforceCallingOrSelfPermission(
3845                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
3846            } else {
3847                try {
3848                    mContext.enforceCallingOrSelfPermission(
3849                            android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
3850                } catch (SecurityException se) {
3851                    mContext.enforceCallingOrSelfPermission(
3852                            android.Manifest.permission.INTERACT_ACROSS_USERS, message);
3853                }
3854            }
3855        }
3856    }
3857
3858    void enforceShellRestriction(String restriction, int callingUid, int userHandle) {
3859        if (callingUid == Process.SHELL_UID) {
3860            if (userHandle >= 0
3861                    && sUserManager.hasUserRestriction(restriction, userHandle)) {
3862                throw new SecurityException("Shell does not have permission to access user "
3863                        + userHandle);
3864            } else if (userHandle < 0) {
3865                Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t"
3866                        + Debug.getCallers(3));
3867            }
3868        }
3869    }
3870
3871    private BasePermission findPermissionTreeLP(String permName) {
3872        for(BasePermission bp : mSettings.mPermissionTrees.values()) {
3873            if (permName.startsWith(bp.name) &&
3874                    permName.length() > bp.name.length() &&
3875                    permName.charAt(bp.name.length()) == '.') {
3876                return bp;
3877            }
3878        }
3879        return null;
3880    }
3881
3882    private BasePermission checkPermissionTreeLP(String permName) {
3883        if (permName != null) {
3884            BasePermission bp = findPermissionTreeLP(permName);
3885            if (bp != null) {
3886                if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) {
3887                    return bp;
3888                }
3889                throw new SecurityException("Calling uid "
3890                        + Binder.getCallingUid()
3891                        + " is not allowed to add to permission tree "
3892                        + bp.name + " owned by uid " + bp.uid);
3893            }
3894        }
3895        throw new SecurityException("No permission tree found for " + permName);
3896    }
3897
3898    static boolean compareStrings(CharSequence s1, CharSequence s2) {
3899        if (s1 == null) {
3900            return s2 == null;
3901        }
3902        if (s2 == null) {
3903            return false;
3904        }
3905        if (s1.getClass() != s2.getClass()) {
3906            return false;
3907        }
3908        return s1.equals(s2);
3909    }
3910
3911    static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
3912        if (pi1.icon != pi2.icon) return false;
3913        if (pi1.logo != pi2.logo) return false;
3914        if (pi1.protectionLevel != pi2.protectionLevel) return false;
3915        if (!compareStrings(pi1.name, pi2.name)) return false;
3916        if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
3917        // We'll take care of setting this one.
3918        if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
3919        // These are not currently stored in settings.
3920        //if (!compareStrings(pi1.group, pi2.group)) return false;
3921        //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
3922        //if (pi1.labelRes != pi2.labelRes) return false;
3923        //if (pi1.descriptionRes != pi2.descriptionRes) return false;
3924        return true;
3925    }
3926
3927    int permissionInfoFootprint(PermissionInfo info) {
3928        int size = info.name.length();
3929        if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length();
3930        if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length();
3931        return size;
3932    }
3933
3934    int calculateCurrentPermissionFootprintLocked(BasePermission tree) {
3935        int size = 0;
3936        for (BasePermission perm : mSettings.mPermissions.values()) {
3937            if (perm.uid == tree.uid) {
3938                size += perm.name.length() + permissionInfoFootprint(perm.perm.info);
3939            }
3940        }
3941        return size;
3942    }
3943
3944    void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) {
3945        // We calculate the max size of permissions defined by this uid and throw
3946        // if that plus the size of 'info' would exceed our stated maximum.
3947        if (tree.uid != Process.SYSTEM_UID) {
3948            final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree);
3949            if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) {
3950                throw new SecurityException("Permission tree size cap exceeded");
3951            }
3952        }
3953    }
3954
3955    boolean addPermissionLocked(PermissionInfo info, boolean async) {
3956        if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
3957            throw new SecurityException("Label must be specified in permission");
3958        }
3959        BasePermission tree = checkPermissionTreeLP(info.name);
3960        BasePermission bp = mSettings.mPermissions.get(info.name);
3961        boolean added = bp == null;
3962        boolean changed = true;
3963        int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel);
3964        if (added) {
3965            enforcePermissionCapLocked(info, tree);
3966            bp = new BasePermission(info.name, tree.sourcePackage,
3967                    BasePermission.TYPE_DYNAMIC);
3968        } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
3969            throw new SecurityException(
3970                    "Not allowed to modify non-dynamic permission "
3971                    + info.name);
3972        } else {
3973            if (bp.protectionLevel == fixedLevel
3974                    && bp.perm.owner.equals(tree.perm.owner)
3975                    && bp.uid == tree.uid
3976                    && comparePermissionInfos(bp.perm.info, info)) {
3977                changed = false;
3978            }
3979        }
3980        bp.protectionLevel = fixedLevel;
3981        info = new PermissionInfo(info);
3982        info.protectionLevel = fixedLevel;
3983        bp.perm = new PackageParser.Permission(tree.perm.owner, info);
3984        bp.perm.info.packageName = tree.perm.info.packageName;
3985        bp.uid = tree.uid;
3986        if (added) {
3987            mSettings.mPermissions.put(info.name, bp);
3988        }
3989        if (changed) {
3990            if (!async) {
3991                mSettings.writeLPr();
3992            } else {
3993                scheduleWriteSettingsLocked();
3994            }
3995        }
3996        return added;
3997    }
3998
3999    @Override
4000    public boolean addPermission(PermissionInfo info) {
4001        synchronized (mPackages) {
4002            return addPermissionLocked(info, false);
4003        }
4004    }
4005
4006    @Override
4007    public boolean addPermissionAsync(PermissionInfo info) {
4008        synchronized (mPackages) {
4009            return addPermissionLocked(info, true);
4010        }
4011    }
4012
4013    @Override
4014    public void removePermission(String name) {
4015        synchronized (mPackages) {
4016            checkPermissionTreeLP(name);
4017            BasePermission bp = mSettings.mPermissions.get(name);
4018            if (bp != null) {
4019                if (bp.type != BasePermission.TYPE_DYNAMIC) {
4020                    throw new SecurityException(
4021                            "Not allowed to modify non-dynamic permission "
4022                            + name);
4023                }
4024                mSettings.mPermissions.remove(name);
4025                mSettings.writeLPr();
4026            }
4027        }
4028    }
4029
4030    private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(PackageParser.Package pkg,
4031            BasePermission bp) {
4032        int index = pkg.requestedPermissions.indexOf(bp.name);
4033        if (index == -1) {
4034            throw new SecurityException("Package " + pkg.packageName
4035                    + " has not requested permission " + bp.name);
4036        }
4037        if (!bp.isRuntime() && !bp.isDevelopment()) {
4038            throw new SecurityException("Permission " + bp.name
4039                    + " is not a changeable permission type");
4040        }
4041    }
4042
4043    @Override
4044    public void grantRuntimePermission(String packageName, String name, final int userId) {
4045        if (!sUserManager.exists(userId)) {
4046            Log.e(TAG, "No such user:" + userId);
4047            return;
4048        }
4049
4050        mContext.enforceCallingOrSelfPermission(
4051                android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
4052                "grantRuntimePermission");
4053
4054        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4055                true /* requireFullPermission */, true /* checkShell */,
4056                "grantRuntimePermission");
4057
4058        final int uid;
4059        final SettingBase sb;
4060
4061        synchronized (mPackages) {
4062            final PackageParser.Package pkg = mPackages.get(packageName);
4063            if (pkg == null) {
4064                throw new IllegalArgumentException("Unknown package: " + packageName);
4065            }
4066
4067            final BasePermission bp = mSettings.mPermissions.get(name);
4068            if (bp == null) {
4069                throw new IllegalArgumentException("Unknown permission: " + name);
4070            }
4071
4072            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
4073
4074            // If a permission review is required for legacy apps we represent
4075            // their permissions as always granted runtime ones since we need
4076            // to keep the review required permission flag per user while an
4077            // install permission's state is shared across all users.
4078            if (Build.PERMISSIONS_REVIEW_REQUIRED
4079                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
4080                    && bp.isRuntime()) {
4081                return;
4082            }
4083
4084            uid = UserHandle.getUid(userId, pkg.applicationInfo.uid);
4085            sb = (SettingBase) pkg.mExtras;
4086            if (sb == null) {
4087                throw new IllegalArgumentException("Unknown package: " + packageName);
4088            }
4089
4090            final PermissionsState permissionsState = sb.getPermissionsState();
4091
4092            final int flags = permissionsState.getPermissionFlags(name, userId);
4093            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
4094                throw new SecurityException("Cannot grant system fixed permission "
4095                        + name + " for package " + packageName);
4096            }
4097
4098            if (bp.isDevelopment()) {
4099                // Development permissions must be handled specially, since they are not
4100                // normal runtime permissions.  For now they apply to all users.
4101                if (permissionsState.grantInstallPermission(bp) !=
4102                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
4103                    scheduleWriteSettingsLocked();
4104                }
4105                return;
4106            }
4107
4108            if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
4109                Slog.w(TAG, "Cannot grant runtime permission to a legacy app");
4110                return;
4111            }
4112
4113            final int result = permissionsState.grantRuntimePermission(bp, userId);
4114            switch (result) {
4115                case PermissionsState.PERMISSION_OPERATION_FAILURE: {
4116                    return;
4117                }
4118
4119                case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
4120                    final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
4121                    mHandler.post(new Runnable() {
4122                        @Override
4123                        public void run() {
4124                            killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED);
4125                        }
4126                    });
4127                }
4128                break;
4129            }
4130
4131            mOnPermissionChangeListeners.onPermissionsChanged(uid);
4132
4133            // Not critical if that is lost - app has to request again.
4134            mSettings.writeRuntimePermissionsForUserLPr(userId, false);
4135        }
4136
4137        // Only need to do this if user is initialized. Otherwise it's a new user
4138        // and there are no processes running as the user yet and there's no need
4139        // to make an expensive call to remount processes for the changed permissions.
4140        if (READ_EXTERNAL_STORAGE.equals(name)
4141                || WRITE_EXTERNAL_STORAGE.equals(name)) {
4142            final long token = Binder.clearCallingIdentity();
4143            try {
4144                if (sUserManager.isInitialized(userId)) {
4145                    MountServiceInternal mountServiceInternal = LocalServices.getService(
4146                            MountServiceInternal.class);
4147                    mountServiceInternal.onExternalStoragePolicyChanged(uid, packageName);
4148                }
4149            } finally {
4150                Binder.restoreCallingIdentity(token);
4151            }
4152        }
4153    }
4154
4155    @Override
4156    public void revokeRuntimePermission(String packageName, String name, int userId) {
4157        if (!sUserManager.exists(userId)) {
4158            Log.e(TAG, "No such user:" + userId);
4159            return;
4160        }
4161
4162        mContext.enforceCallingOrSelfPermission(
4163                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
4164                "revokeRuntimePermission");
4165
4166        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4167                true /* requireFullPermission */, true /* checkShell */,
4168                "revokeRuntimePermission");
4169
4170        final int appId;
4171
4172        synchronized (mPackages) {
4173            final PackageParser.Package pkg = mPackages.get(packageName);
4174            if (pkg == null) {
4175                throw new IllegalArgumentException("Unknown package: " + packageName);
4176            }
4177
4178            final BasePermission bp = mSettings.mPermissions.get(name);
4179            if (bp == null) {
4180                throw new IllegalArgumentException("Unknown permission: " + name);
4181            }
4182
4183            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
4184
4185            // If a permission review is required for legacy apps we represent
4186            // their permissions as always granted runtime ones since we need
4187            // to keep the review required permission flag per user while an
4188            // install permission's state is shared across all users.
4189            if (Build.PERMISSIONS_REVIEW_REQUIRED
4190                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
4191                    && bp.isRuntime()) {
4192                return;
4193            }
4194
4195            SettingBase sb = (SettingBase) pkg.mExtras;
4196            if (sb == null) {
4197                throw new IllegalArgumentException("Unknown package: " + packageName);
4198            }
4199
4200            final PermissionsState permissionsState = sb.getPermissionsState();
4201
4202            final int flags = permissionsState.getPermissionFlags(name, userId);
4203            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
4204                throw new SecurityException("Cannot revoke system fixed permission "
4205                        + name + " for package " + packageName);
4206            }
4207
4208            if (bp.isDevelopment()) {
4209                // Development permissions must be handled specially, since they are not
4210                // normal runtime permissions.  For now they apply to all users.
4211                if (permissionsState.revokeInstallPermission(bp) !=
4212                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
4213                    scheduleWriteSettingsLocked();
4214                }
4215                return;
4216            }
4217
4218            if (permissionsState.revokeRuntimePermission(bp, userId) ==
4219                    PermissionsState.PERMISSION_OPERATION_FAILURE) {
4220                return;
4221            }
4222
4223            mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid);
4224
4225            // Critical, after this call app should never have the permission.
4226            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
4227
4228            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
4229        }
4230
4231        killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
4232    }
4233
4234    @Override
4235    public void resetRuntimePermissions() {
4236        mContext.enforceCallingOrSelfPermission(
4237                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
4238                "revokeRuntimePermission");
4239
4240        int callingUid = Binder.getCallingUid();
4241        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
4242            mContext.enforceCallingOrSelfPermission(
4243                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
4244                    "resetRuntimePermissions");
4245        }
4246
4247        synchronized (mPackages) {
4248            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL);
4249            for (int userId : UserManagerService.getInstance().getUserIds()) {
4250                final int packageCount = mPackages.size();
4251                for (int i = 0; i < packageCount; i++) {
4252                    PackageParser.Package pkg = mPackages.valueAt(i);
4253                    if (!(pkg.mExtras instanceof PackageSetting)) {
4254                        continue;
4255                    }
4256                    PackageSetting ps = (PackageSetting) pkg.mExtras;
4257                    resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
4258                }
4259            }
4260        }
4261    }
4262
4263    @Override
4264    public int getPermissionFlags(String name, String packageName, int userId) {
4265        if (!sUserManager.exists(userId)) {
4266            return 0;
4267        }
4268
4269        enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags");
4270
4271        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4272                true /* requireFullPermission */, false /* checkShell */,
4273                "getPermissionFlags");
4274
4275        synchronized (mPackages) {
4276            final PackageParser.Package pkg = mPackages.get(packageName);
4277            if (pkg == null) {
4278                throw new IllegalArgumentException("Unknown package: " + packageName);
4279            }
4280
4281            final BasePermission bp = mSettings.mPermissions.get(name);
4282            if (bp == null) {
4283                throw new IllegalArgumentException("Unknown permission: " + name);
4284            }
4285
4286            SettingBase sb = (SettingBase) pkg.mExtras;
4287            if (sb == null) {
4288                throw new IllegalArgumentException("Unknown package: " + packageName);
4289            }
4290
4291            PermissionsState permissionsState = sb.getPermissionsState();
4292            return permissionsState.getPermissionFlags(name, userId);
4293        }
4294    }
4295
4296    @Override
4297    public void updatePermissionFlags(String name, String packageName, int flagMask,
4298            int flagValues, int userId) {
4299        if (!sUserManager.exists(userId)) {
4300            return;
4301        }
4302
4303        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags");
4304
4305        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4306                true /* requireFullPermission */, true /* checkShell */,
4307                "updatePermissionFlags");
4308
4309        // Only the system can change these flags and nothing else.
4310        if (getCallingUid() != Process.SYSTEM_UID) {
4311            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4312            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4313            flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
4314            flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
4315            flagValues &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
4316        }
4317
4318        synchronized (mPackages) {
4319            final PackageParser.Package pkg = mPackages.get(packageName);
4320            if (pkg == null) {
4321                throw new IllegalArgumentException("Unknown package: " + packageName);
4322            }
4323
4324            final BasePermission bp = mSettings.mPermissions.get(name);
4325            if (bp == null) {
4326                throw new IllegalArgumentException("Unknown permission: " + name);
4327            }
4328
4329            SettingBase sb = (SettingBase) pkg.mExtras;
4330            if (sb == null) {
4331                throw new IllegalArgumentException("Unknown package: " + packageName);
4332            }
4333
4334            PermissionsState permissionsState = sb.getPermissionsState();
4335
4336            boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null;
4337
4338            if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) {
4339                // Install and runtime permissions are stored in different places,
4340                // so figure out what permission changed and persist the change.
4341                if (permissionsState.getInstallPermissionState(name) != null) {
4342                    scheduleWriteSettingsLocked();
4343                } else if (permissionsState.getRuntimePermissionState(name, userId) != null
4344                        || hadState) {
4345                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
4346                }
4347            }
4348        }
4349    }
4350
4351    /**
4352     * Update the permission flags for all packages and runtime permissions of a user in order
4353     * to allow device or profile owner to remove POLICY_FIXED.
4354     */
4355    @Override
4356    public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) {
4357        if (!sUserManager.exists(userId)) {
4358            return;
4359        }
4360
4361        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps");
4362
4363        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4364                true /* requireFullPermission */, true /* checkShell */,
4365                "updatePermissionFlagsForAllApps");
4366
4367        // Only the system can change system fixed flags.
4368        if (getCallingUid() != Process.SYSTEM_UID) {
4369            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4370            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4371        }
4372
4373        synchronized (mPackages) {
4374            boolean changed = false;
4375            final int packageCount = mPackages.size();
4376            for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) {
4377                final PackageParser.Package pkg = mPackages.valueAt(pkgIndex);
4378                SettingBase sb = (SettingBase) pkg.mExtras;
4379                if (sb == null) {
4380                    continue;
4381                }
4382                PermissionsState permissionsState = sb.getPermissionsState();
4383                changed |= permissionsState.updatePermissionFlagsForAllPermissions(
4384                        userId, flagMask, flagValues);
4385            }
4386            if (changed) {
4387                mSettings.writeRuntimePermissionsForUserLPr(userId, false);
4388            }
4389        }
4390    }
4391
4392    private void enforceGrantRevokeRuntimePermissionPermissions(String message) {
4393        if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS)
4394                != PackageManager.PERMISSION_GRANTED
4395            && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS)
4396                != PackageManager.PERMISSION_GRANTED) {
4397            throw new SecurityException(message + " requires "
4398                    + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or "
4399                    + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS);
4400        }
4401    }
4402
4403    @Override
4404    public boolean shouldShowRequestPermissionRationale(String permissionName,
4405            String packageName, int userId) {
4406        if (UserHandle.getCallingUserId() != userId) {
4407            mContext.enforceCallingPermission(
4408                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
4409                    "canShowRequestPermissionRationale for user " + userId);
4410        }
4411
4412        final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId);
4413        if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) {
4414            return false;
4415        }
4416
4417        if (checkPermission(permissionName, packageName, userId)
4418                == PackageManager.PERMISSION_GRANTED) {
4419            return false;
4420        }
4421
4422        final int flags;
4423
4424        final long identity = Binder.clearCallingIdentity();
4425        try {
4426            flags = getPermissionFlags(permissionName,
4427                    packageName, userId);
4428        } finally {
4429            Binder.restoreCallingIdentity(identity);
4430        }
4431
4432        final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
4433                | PackageManager.FLAG_PERMISSION_POLICY_FIXED
4434                | PackageManager.FLAG_PERMISSION_USER_FIXED;
4435
4436        if ((flags & fixedFlags) != 0) {
4437            return false;
4438        }
4439
4440        return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0;
4441    }
4442
4443    @Override
4444    public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
4445        mContext.enforceCallingOrSelfPermission(
4446                Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS,
4447                "addOnPermissionsChangeListener");
4448
4449        synchronized (mPackages) {
4450            mOnPermissionChangeListeners.addListenerLocked(listener);
4451        }
4452    }
4453
4454    @Override
4455    public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
4456        synchronized (mPackages) {
4457            mOnPermissionChangeListeners.removeListenerLocked(listener);
4458        }
4459    }
4460
4461    @Override
4462    public boolean isProtectedBroadcast(String actionName) {
4463        synchronized (mPackages) {
4464            if (mProtectedBroadcasts.contains(actionName)) {
4465                return true;
4466            } else if (actionName != null) {
4467                // TODO: remove these terrible hacks
4468                if (actionName.startsWith("android.net.netmon.lingerExpired")
4469                        || actionName.startsWith("com.android.server.sip.SipWakeupTimer")
4470                        || actionName.startsWith("com.android.internal.telephony.data-reconnect")
4471                        || actionName.startsWith("android.net.netmon.launchCaptivePortalApp")) {
4472                    return true;
4473                }
4474            }
4475        }
4476        return false;
4477    }
4478
4479    @Override
4480    public int checkSignatures(String pkg1, String pkg2) {
4481        synchronized (mPackages) {
4482            final PackageParser.Package p1 = mPackages.get(pkg1);
4483            final PackageParser.Package p2 = mPackages.get(pkg2);
4484            if (p1 == null || p1.mExtras == null
4485                    || p2 == null || p2.mExtras == null) {
4486                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4487            }
4488            return compareSignatures(p1.mSignatures, p2.mSignatures);
4489        }
4490    }
4491
4492    @Override
4493    public int checkUidSignatures(int uid1, int uid2) {
4494        // Map to base uids.
4495        uid1 = UserHandle.getAppId(uid1);
4496        uid2 = UserHandle.getAppId(uid2);
4497        // reader
4498        synchronized (mPackages) {
4499            Signature[] s1;
4500            Signature[] s2;
4501            Object obj = mSettings.getUserIdLPr(uid1);
4502            if (obj != null) {
4503                if (obj instanceof SharedUserSetting) {
4504                    s1 = ((SharedUserSetting)obj).signatures.mSignatures;
4505                } else if (obj instanceof PackageSetting) {
4506                    s1 = ((PackageSetting)obj).signatures.mSignatures;
4507                } else {
4508                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4509                }
4510            } else {
4511                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4512            }
4513            obj = mSettings.getUserIdLPr(uid2);
4514            if (obj != null) {
4515                if (obj instanceof SharedUserSetting) {
4516                    s2 = ((SharedUserSetting)obj).signatures.mSignatures;
4517                } else if (obj instanceof PackageSetting) {
4518                    s2 = ((PackageSetting)obj).signatures.mSignatures;
4519                } else {
4520                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4521                }
4522            } else {
4523                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4524            }
4525            return compareSignatures(s1, s2);
4526        }
4527    }
4528
4529    /**
4530     * This method should typically only be used when granting or revoking
4531     * permissions, since the app may immediately restart after this call.
4532     * <p>
4533     * If you're doing surgery on app code/data, use {@link PackageFreezer} to
4534     * guard your work against the app being relaunched.
4535     */
4536    private void killUid(int appId, int userId, String reason) {
4537        final long identity = Binder.clearCallingIdentity();
4538        try {
4539            IActivityManager am = ActivityManagerNative.getDefault();
4540            if (am != null) {
4541                try {
4542                    am.killUid(appId, userId, reason);
4543                } catch (RemoteException e) {
4544                    /* ignore - same process */
4545                }
4546            }
4547        } finally {
4548            Binder.restoreCallingIdentity(identity);
4549        }
4550    }
4551
4552    /**
4553     * Compares two sets of signatures. Returns:
4554     * <br />
4555     * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null,
4556     * <br />
4557     * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null,
4558     * <br />
4559     * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null,
4560     * <br />
4561     * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical,
4562     * <br />
4563     * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ.
4564     */
4565    static int compareSignatures(Signature[] s1, Signature[] s2) {
4566        if (s1 == null) {
4567            return s2 == null
4568                    ? PackageManager.SIGNATURE_NEITHER_SIGNED
4569                    : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
4570        }
4571
4572        if (s2 == null) {
4573            return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
4574        }
4575
4576        if (s1.length != s2.length) {
4577            return PackageManager.SIGNATURE_NO_MATCH;
4578        }
4579
4580        // Since both signature sets are of size 1, we can compare without HashSets.
4581        if (s1.length == 1) {
4582            return s1[0].equals(s2[0]) ?
4583                    PackageManager.SIGNATURE_MATCH :
4584                    PackageManager.SIGNATURE_NO_MATCH;
4585        }
4586
4587        ArraySet<Signature> set1 = new ArraySet<Signature>();
4588        for (Signature sig : s1) {
4589            set1.add(sig);
4590        }
4591        ArraySet<Signature> set2 = new ArraySet<Signature>();
4592        for (Signature sig : s2) {
4593            set2.add(sig);
4594        }
4595        // Make sure s2 contains all signatures in s1.
4596        if (set1.equals(set2)) {
4597            return PackageManager.SIGNATURE_MATCH;
4598        }
4599        return PackageManager.SIGNATURE_NO_MATCH;
4600    }
4601
4602    /**
4603     * If the database version for this type of package (internal storage or
4604     * external storage) is less than the version where package signatures
4605     * were updated, return true.
4606     */
4607    private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
4608        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
4609        return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY;
4610    }
4611
4612    /**
4613     * Used for backward compatibility to make sure any packages with
4614     * certificate chains get upgraded to the new style. {@code existingSigs}
4615     * will be in the old format (since they were stored on disk from before the
4616     * system upgrade) and {@code scannedSigs} will be in the newer format.
4617     */
4618    private int compareSignaturesCompat(PackageSignatures existingSigs,
4619            PackageParser.Package scannedPkg) {
4620        if (!isCompatSignatureUpdateNeeded(scannedPkg)) {
4621            return PackageManager.SIGNATURE_NO_MATCH;
4622        }
4623
4624        ArraySet<Signature> existingSet = new ArraySet<Signature>();
4625        for (Signature sig : existingSigs.mSignatures) {
4626            existingSet.add(sig);
4627        }
4628        ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>();
4629        for (Signature sig : scannedPkg.mSignatures) {
4630            try {
4631                Signature[] chainSignatures = sig.getChainSignatures();
4632                for (Signature chainSig : chainSignatures) {
4633                    scannedCompatSet.add(chainSig);
4634                }
4635            } catch (CertificateEncodingException e) {
4636                scannedCompatSet.add(sig);
4637            }
4638        }
4639        /*
4640         * Make sure the expanded scanned set contains all signatures in the
4641         * existing one.
4642         */
4643        if (scannedCompatSet.equals(existingSet)) {
4644            // Migrate the old signatures to the new scheme.
4645            existingSigs.assignSignatures(scannedPkg.mSignatures);
4646            // The new KeySets will be re-added later in the scanning process.
4647            synchronized (mPackages) {
4648                mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName);
4649            }
4650            return PackageManager.SIGNATURE_MATCH;
4651        }
4652        return PackageManager.SIGNATURE_NO_MATCH;
4653    }
4654
4655    private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
4656        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
4657        return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER;
4658    }
4659
4660    private int compareSignaturesRecover(PackageSignatures existingSigs,
4661            PackageParser.Package scannedPkg) {
4662        if (!isRecoverSignatureUpdateNeeded(scannedPkg)) {
4663            return PackageManager.SIGNATURE_NO_MATCH;
4664        }
4665
4666        String msg = null;
4667        try {
4668            if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) {
4669                logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for "
4670                        + scannedPkg.packageName);
4671                return PackageManager.SIGNATURE_MATCH;
4672            }
4673        } catch (CertificateException e) {
4674            msg = e.getMessage();
4675        }
4676
4677        logCriticalInfo(Log.INFO,
4678                "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg);
4679        return PackageManager.SIGNATURE_NO_MATCH;
4680    }
4681
4682    @Override
4683    public List<String> getAllPackages() {
4684        synchronized (mPackages) {
4685            return new ArrayList<String>(mPackages.keySet());
4686        }
4687    }
4688
4689    @Override
4690    public String[] getPackagesForUid(int uid) {
4691        uid = UserHandle.getAppId(uid);
4692        // reader
4693        synchronized (mPackages) {
4694            Object obj = mSettings.getUserIdLPr(uid);
4695            if (obj instanceof SharedUserSetting) {
4696                final SharedUserSetting sus = (SharedUserSetting) obj;
4697                final int N = sus.packages.size();
4698                final String[] res = new String[N];
4699                final Iterator<PackageSetting> it = sus.packages.iterator();
4700                int i = 0;
4701                while (it.hasNext()) {
4702                    res[i++] = it.next().name;
4703                }
4704                return res;
4705            } else if (obj instanceof PackageSetting) {
4706                final PackageSetting ps = (PackageSetting) obj;
4707                return new String[] { ps.name };
4708            }
4709        }
4710        return null;
4711    }
4712
4713    @Override
4714    public String getNameForUid(int uid) {
4715        // reader
4716        synchronized (mPackages) {
4717            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4718            if (obj instanceof SharedUserSetting) {
4719                final SharedUserSetting sus = (SharedUserSetting) obj;
4720                return sus.name + ":" + sus.userId;
4721            } else if (obj instanceof PackageSetting) {
4722                final PackageSetting ps = (PackageSetting) obj;
4723                return ps.name;
4724            }
4725        }
4726        return null;
4727    }
4728
4729    @Override
4730    public int getUidForSharedUser(String sharedUserName) {
4731        if(sharedUserName == null) {
4732            return -1;
4733        }
4734        // reader
4735        synchronized (mPackages) {
4736            final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false);
4737            if (suid == null) {
4738                return -1;
4739            }
4740            return suid.userId;
4741        }
4742    }
4743
4744    @Override
4745    public int getFlagsForUid(int uid) {
4746        synchronized (mPackages) {
4747            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4748            if (obj instanceof SharedUserSetting) {
4749                final SharedUserSetting sus = (SharedUserSetting) obj;
4750                return sus.pkgFlags;
4751            } else if (obj instanceof PackageSetting) {
4752                final PackageSetting ps = (PackageSetting) obj;
4753                return ps.pkgFlags;
4754            }
4755        }
4756        return 0;
4757    }
4758
4759    @Override
4760    public int getPrivateFlagsForUid(int uid) {
4761        synchronized (mPackages) {
4762            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4763            if (obj instanceof SharedUserSetting) {
4764                final SharedUserSetting sus = (SharedUserSetting) obj;
4765                return sus.pkgPrivateFlags;
4766            } else if (obj instanceof PackageSetting) {
4767                final PackageSetting ps = (PackageSetting) obj;
4768                return ps.pkgPrivateFlags;
4769            }
4770        }
4771        return 0;
4772    }
4773
4774    @Override
4775    public boolean isUidPrivileged(int uid) {
4776        uid = UserHandle.getAppId(uid);
4777        // reader
4778        synchronized (mPackages) {
4779            Object obj = mSettings.getUserIdLPr(uid);
4780            if (obj instanceof SharedUserSetting) {
4781                final SharedUserSetting sus = (SharedUserSetting) obj;
4782                final Iterator<PackageSetting> it = sus.packages.iterator();
4783                while (it.hasNext()) {
4784                    if (it.next().isPrivileged()) {
4785                        return true;
4786                    }
4787                }
4788            } else if (obj instanceof PackageSetting) {
4789                final PackageSetting ps = (PackageSetting) obj;
4790                return ps.isPrivileged();
4791            }
4792        }
4793        return false;
4794    }
4795
4796    @Override
4797    public String[] getAppOpPermissionPackages(String permissionName) {
4798        synchronized (mPackages) {
4799            ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName);
4800            if (pkgs == null) {
4801                return null;
4802            }
4803            return pkgs.toArray(new String[pkgs.size()]);
4804        }
4805    }
4806
4807    @Override
4808    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
4809            int flags, int userId) {
4810        try {
4811            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveIntent");
4812
4813            if (!sUserManager.exists(userId)) return null;
4814            flags = updateFlagsForResolve(flags, userId, intent);
4815            enforceCrossUserPermission(Binder.getCallingUid(), userId,
4816                    false /*requireFullPermission*/, false /*checkShell*/, "resolve intent");
4817
4818            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
4819            final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType,
4820                    flags, userId);
4821            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
4822
4823            final ResolveInfo bestChoice =
4824                    chooseBestActivity(intent, resolvedType, flags, query, userId);
4825
4826            if (isEphemeralAllowed(intent, query, userId)) {
4827                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveEphemeral");
4828                final EphemeralResolveInfo ai =
4829                        getEphemeralResolveInfo(intent, resolvedType, userId);
4830                if (ai != null) {
4831                    if (DEBUG_EPHEMERAL) {
4832                        Slog.v(TAG, "Returning an EphemeralResolveInfo");
4833                    }
4834                    bestChoice.ephemeralInstaller = mEphemeralInstallerInfo;
4835                    bestChoice.ephemeralResolveInfo = ai;
4836                }
4837                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
4838            }
4839            return bestChoice;
4840        } finally {
4841            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
4842        }
4843    }
4844
4845    @Override
4846    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
4847            IntentFilter filter, int match, ComponentName activity) {
4848        final int userId = UserHandle.getCallingUserId();
4849        if (DEBUG_PREFERRED) {
4850            Log.v(TAG, "setLastChosenActivity intent=" + intent
4851                + " resolvedType=" + resolvedType
4852                + " flags=" + flags
4853                + " filter=" + filter
4854                + " match=" + match
4855                + " activity=" + activity);
4856            filter.dump(new PrintStreamPrinter(System.out), "    ");
4857        }
4858        intent.setComponent(null);
4859        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
4860                userId);
4861        // Find any earlier preferred or last chosen entries and nuke them
4862        findPreferredActivity(intent, resolvedType,
4863                flags, query, 0, false, true, false, userId);
4864        // Add the new activity as the last chosen for this filter
4865        addPreferredActivityInternal(filter, match, null, activity, false, userId,
4866                "Setting last chosen");
4867    }
4868
4869    @Override
4870    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
4871        final int userId = UserHandle.getCallingUserId();
4872        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
4873        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
4874                userId);
4875        return findPreferredActivity(intent, resolvedType, flags, query, 0,
4876                false, false, false, userId);
4877    }
4878
4879
4880    private boolean isEphemeralAllowed(
4881            Intent intent, List<ResolveInfo> resolvedActivites, int userId) {
4882        // Short circuit and return early if possible.
4883        if (DISABLE_EPHEMERAL_APPS) {
4884            return false;
4885        }
4886        final int callingUser = UserHandle.getCallingUserId();
4887        if (callingUser != UserHandle.USER_SYSTEM) {
4888            return false;
4889        }
4890        if (mEphemeralResolverConnection == null) {
4891            return false;
4892        }
4893        if (intent.getComponent() != null) {
4894            return false;
4895        }
4896        if (intent.getPackage() != null) {
4897            return false;
4898        }
4899        final boolean isWebUri = hasWebURI(intent);
4900        if (!isWebUri) {
4901            return false;
4902        }
4903        // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution.
4904        synchronized (mPackages) {
4905            final int count = resolvedActivites.size();
4906            for (int n = 0; n < count; n++) {
4907                ResolveInfo info = resolvedActivites.get(n);
4908                String packageName = info.activityInfo.packageName;
4909                PackageSetting ps = mSettings.mPackages.get(packageName);
4910                if (ps != null) {
4911                    // Try to get the status from User settings first
4912                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
4913                    int status = (int) (packedStatus >> 32);
4914                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS
4915                            || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
4916                        if (DEBUG_EPHEMERAL) {
4917                            Slog.v(TAG, "DENY ephemeral apps;"
4918                                + " pkg: " + packageName + ", status: " + status);
4919                        }
4920                        return false;
4921                    }
4922                }
4923            }
4924        }
4925        // We've exhausted all ways to deny ephemeral application; let the system look for them.
4926        return true;
4927    }
4928
4929    private EphemeralResolveInfo getEphemeralResolveInfo(Intent intent, String resolvedType,
4930            int userId) {
4931        MessageDigest digest = null;
4932        try {
4933            digest = MessageDigest.getInstance(EphemeralResolveInfo.SHA_ALGORITHM);
4934        } catch (NoSuchAlgorithmException e) {
4935            // If we can't create a digest, ignore ephemeral apps.
4936            return null;
4937        }
4938
4939        final byte[] hostBytes = intent.getData().getHost().getBytes();
4940        final byte[] digestBytes = digest.digest(hostBytes);
4941        int shaPrefix =
4942                digestBytes[0] << 24
4943                | digestBytes[1] << 16
4944                | digestBytes[2] << 8
4945                | digestBytes[3] << 0;
4946        final List<EphemeralResolveInfo> ephemeralResolveInfoList =
4947                mEphemeralResolverConnection.getEphemeralResolveInfoList(shaPrefix);
4948        if (ephemeralResolveInfoList == null || ephemeralResolveInfoList.size() == 0) {
4949            // No hash prefix match; there are no ephemeral apps for this domain.
4950            return null;
4951        }
4952        for (int i = ephemeralResolveInfoList.size() - 1; i >= 0; --i) {
4953            EphemeralResolveInfo ephemeralApplication = ephemeralResolveInfoList.get(i);
4954            if (!Arrays.equals(digestBytes, ephemeralApplication.getDigestBytes())) {
4955                continue;
4956            }
4957            final List<IntentFilter> filters = ephemeralApplication.getFilters();
4958            // No filters; this should never happen.
4959            if (filters.isEmpty()) {
4960                continue;
4961            }
4962            // We have a domain match; resolve the filters to see if anything matches.
4963            final EphemeralIntentResolver ephemeralResolver = new EphemeralIntentResolver();
4964            for (int j = filters.size() - 1; j >= 0; --j) {
4965                final EphemeralResolveIntentInfo intentInfo =
4966                        new EphemeralResolveIntentInfo(filters.get(j), ephemeralApplication);
4967                ephemeralResolver.addFilter(intentInfo);
4968            }
4969            List<EphemeralResolveInfo> matchedResolveInfoList = ephemeralResolver.queryIntent(
4970                    intent, resolvedType, false /*defaultOnly*/, userId);
4971            if (!matchedResolveInfoList.isEmpty()) {
4972                return matchedResolveInfoList.get(0);
4973            }
4974        }
4975        // Hash or filter mis-match; no ephemeral apps for this domain.
4976        return null;
4977    }
4978
4979    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
4980            int flags, List<ResolveInfo> query, int userId) {
4981        if (query != null) {
4982            final int N = query.size();
4983            if (N == 1) {
4984                return query.get(0);
4985            } else if (N > 1) {
4986                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
4987                // If there is more than one activity with the same priority,
4988                // then let the user decide between them.
4989                ResolveInfo r0 = query.get(0);
4990                ResolveInfo r1 = query.get(1);
4991                if (DEBUG_INTENT_MATCHING || debug) {
4992                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
4993                            + r1.activityInfo.name + "=" + r1.priority);
4994                }
4995                // If the first activity has a higher priority, or a different
4996                // default, then it is always desirable to pick it.
4997                if (r0.priority != r1.priority
4998                        || r0.preferredOrder != r1.preferredOrder
4999                        || r0.isDefault != r1.isDefault) {
5000                    return query.get(0);
5001                }
5002                // If we have saved a preference for a preferred activity for
5003                // this Intent, use that.
5004                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
5005                        flags, query, r0.priority, true, false, debug, userId);
5006                if (ri != null) {
5007                    return ri;
5008                }
5009                ri = new ResolveInfo(mResolveInfo);
5010                ri.activityInfo = new ActivityInfo(ri.activityInfo);
5011                ri.activityInfo.labelRes = ResolverActivity.getLabelRes(intent.getAction());
5012                ri.activityInfo.applicationInfo = new ApplicationInfo(
5013                        ri.activityInfo.applicationInfo);
5014                if (userId != 0) {
5015                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
5016                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
5017                }
5018                // Make sure that the resolver is displayable in car mode
5019                if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle();
5020                ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true);
5021                return ri;
5022            }
5023        }
5024        return null;
5025    }
5026
5027    private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
5028            int flags, List<ResolveInfo> query, boolean debug, int userId) {
5029        final int N = query.size();
5030        PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
5031                .get(userId);
5032        // Get the list of persistent preferred activities that handle the intent
5033        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
5034        List<PersistentPreferredActivity> pprefs = ppir != null
5035                ? ppir.queryIntent(intent, resolvedType,
5036                        (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
5037                : null;
5038        if (pprefs != null && pprefs.size() > 0) {
5039            final int M = pprefs.size();
5040            for (int i=0; i<M; i++) {
5041                final PersistentPreferredActivity ppa = pprefs.get(i);
5042                if (DEBUG_PREFERRED || debug) {
5043                    Slog.v(TAG, "Checking PersistentPreferredActivity ds="
5044                            + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
5045                            + "\n  component=" + ppa.mComponent);
5046                    ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
5047                }
5048                final ActivityInfo ai = getActivityInfo(ppa.mComponent,
5049                        flags | MATCH_DISABLED_COMPONENTS, userId);
5050                if (DEBUG_PREFERRED || debug) {
5051                    Slog.v(TAG, "Found persistent preferred activity:");
5052                    if (ai != null) {
5053                        ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
5054                    } else {
5055                        Slog.v(TAG, "  null");
5056                    }
5057                }
5058                if (ai == null) {
5059                    // This previously registered persistent preferred activity
5060                    // component is no longer known. Ignore it and do NOT remove it.
5061                    continue;
5062                }
5063                for (int j=0; j<N; j++) {
5064                    final ResolveInfo ri = query.get(j);
5065                    if (!ri.activityInfo.applicationInfo.packageName
5066                            .equals(ai.applicationInfo.packageName)) {
5067                        continue;
5068                    }
5069                    if (!ri.activityInfo.name.equals(ai.name)) {
5070                        continue;
5071                    }
5072                    //  Found a persistent preference that can handle the intent.
5073                    if (DEBUG_PREFERRED || debug) {
5074                        Slog.v(TAG, "Returning persistent preferred activity: " +
5075                                ri.activityInfo.packageName + "/" + ri.activityInfo.name);
5076                    }
5077                    return ri;
5078                }
5079            }
5080        }
5081        return null;
5082    }
5083
5084    // TODO: handle preferred activities missing while user has amnesia
5085    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
5086            List<ResolveInfo> query, int priority, boolean always,
5087            boolean removeMatches, boolean debug, int userId) {
5088        if (!sUserManager.exists(userId)) return null;
5089        flags = updateFlagsForResolve(flags, userId, intent);
5090        // writer
5091        synchronized (mPackages) {
5092            if (intent.getSelector() != null) {
5093                intent = intent.getSelector();
5094            }
5095            if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
5096
5097            // Try to find a matching persistent preferred activity.
5098            ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
5099                    debug, userId);
5100
5101            // If a persistent preferred activity matched, use it.
5102            if (pri != null) {
5103                return pri;
5104            }
5105
5106            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
5107            // Get the list of preferred activities that handle the intent
5108            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
5109            List<PreferredActivity> prefs = pir != null
5110                    ? pir.queryIntent(intent, resolvedType,
5111                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
5112                    : null;
5113            if (prefs != null && prefs.size() > 0) {
5114                boolean changed = false;
5115                try {
5116                    // First figure out how good the original match set is.
5117                    // We will only allow preferred activities that came
5118                    // from the same match quality.
5119                    int match = 0;
5120
5121                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
5122
5123                    final int N = query.size();
5124                    for (int j=0; j<N; j++) {
5125                        final ResolveInfo ri = query.get(j);
5126                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
5127                                + ": 0x" + Integer.toHexString(match));
5128                        if (ri.match > match) {
5129                            match = ri.match;
5130                        }
5131                    }
5132
5133                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
5134                            + Integer.toHexString(match));
5135
5136                    match &= IntentFilter.MATCH_CATEGORY_MASK;
5137                    final int M = prefs.size();
5138                    for (int i=0; i<M; i++) {
5139                        final PreferredActivity pa = prefs.get(i);
5140                        if (DEBUG_PREFERRED || debug) {
5141                            Slog.v(TAG, "Checking PreferredActivity ds="
5142                                    + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
5143                                    + "\n  component=" + pa.mPref.mComponent);
5144                            pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
5145                        }
5146                        if (pa.mPref.mMatch != match) {
5147                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
5148                                    + Integer.toHexString(pa.mPref.mMatch));
5149                            continue;
5150                        }
5151                        // If it's not an "always" type preferred activity and that's what we're
5152                        // looking for, skip it.
5153                        if (always && !pa.mPref.mAlways) {
5154                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
5155                            continue;
5156                        }
5157                        final ActivityInfo ai = getActivityInfo(
5158                                pa.mPref.mComponent, flags | MATCH_DISABLED_COMPONENTS
5159                                        | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
5160                                userId);
5161                        if (DEBUG_PREFERRED || debug) {
5162                            Slog.v(TAG, "Found preferred activity:");
5163                            if (ai != null) {
5164                                ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
5165                            } else {
5166                                Slog.v(TAG, "  null");
5167                            }
5168                        }
5169                        if (ai == null) {
5170                            // This previously registered preferred activity
5171                            // component is no longer known.  Most likely an update
5172                            // to the app was installed and in the new version this
5173                            // component no longer exists.  Clean it up by removing
5174                            // it from the preferred activities list, and skip it.
5175                            Slog.w(TAG, "Removing dangling preferred activity: "
5176                                    + pa.mPref.mComponent);
5177                            pir.removeFilter(pa);
5178                            changed = true;
5179                            continue;
5180                        }
5181                        for (int j=0; j<N; j++) {
5182                            final ResolveInfo ri = query.get(j);
5183                            if (!ri.activityInfo.applicationInfo.packageName
5184                                    .equals(ai.applicationInfo.packageName)) {
5185                                continue;
5186                            }
5187                            if (!ri.activityInfo.name.equals(ai.name)) {
5188                                continue;
5189                            }
5190
5191                            if (removeMatches) {
5192                                pir.removeFilter(pa);
5193                                changed = true;
5194                                if (DEBUG_PREFERRED) {
5195                                    Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
5196                                }
5197                                break;
5198                            }
5199
5200                            // Okay we found a previously set preferred or last chosen app.
5201                            // If the result set is different from when this
5202                            // was created, we need to clear it and re-ask the
5203                            // user their preference, if we're looking for an "always" type entry.
5204                            if (always && !pa.mPref.sameSet(query)) {
5205                                Slog.i(TAG, "Result set changed, dropping preferred activity for "
5206                                        + intent + " type " + resolvedType);
5207                                if (DEBUG_PREFERRED) {
5208                                    Slog.v(TAG, "Removing preferred activity since set changed "
5209                                            + pa.mPref.mComponent);
5210                                }
5211                                pir.removeFilter(pa);
5212                                // Re-add the filter as a "last chosen" entry (!always)
5213                                PreferredActivity lastChosen = new PreferredActivity(
5214                                        pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
5215                                pir.addFilter(lastChosen);
5216                                changed = true;
5217                                return null;
5218                            }
5219
5220                            // Yay! Either the set matched or we're looking for the last chosen
5221                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
5222                                    + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
5223                            return ri;
5224                        }
5225                    }
5226                } finally {
5227                    if (changed) {
5228                        if (DEBUG_PREFERRED) {
5229                            Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions");
5230                        }
5231                        scheduleWritePackageRestrictionsLocked(userId);
5232                    }
5233                }
5234            }
5235        }
5236        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
5237        return null;
5238    }
5239
5240    /*
5241     * Returns if intent can be forwarded from the sourceUserId to the targetUserId
5242     */
5243    @Override
5244    public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
5245            int targetUserId) {
5246        mContext.enforceCallingOrSelfPermission(
5247                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
5248        List<CrossProfileIntentFilter> matches =
5249                getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
5250        if (matches != null) {
5251            int size = matches.size();
5252            for (int i = 0; i < size; i++) {
5253                if (matches.get(i).getTargetUserId() == targetUserId) return true;
5254            }
5255        }
5256        if (hasWebURI(intent)) {
5257            // cross-profile app linking works only towards the parent.
5258            final UserInfo parent = getProfileParent(sourceUserId);
5259            synchronized(mPackages) {
5260                int flags = updateFlagsForResolve(0, parent.id, intent);
5261                CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr(
5262                        intent, resolvedType, flags, sourceUserId, parent.id);
5263                return xpDomainInfo != null;
5264            }
5265        }
5266        return false;
5267    }
5268
5269    private UserInfo getProfileParent(int userId) {
5270        final long identity = Binder.clearCallingIdentity();
5271        try {
5272            return sUserManager.getProfileParent(userId);
5273        } finally {
5274            Binder.restoreCallingIdentity(identity);
5275        }
5276    }
5277
5278    private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
5279            String resolvedType, int userId) {
5280        CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
5281        if (resolver != null) {
5282            return resolver.queryIntent(intent, resolvedType, false, userId);
5283        }
5284        return null;
5285    }
5286
5287    @Override
5288    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivities(Intent intent,
5289            String resolvedType, int flags, int userId) {
5290        try {
5291            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
5292
5293            return new ParceledListSlice<>(
5294                    queryIntentActivitiesInternal(intent, resolvedType, flags, userId));
5295        } finally {
5296            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
5297        }
5298    }
5299
5300    private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent,
5301            String resolvedType, int flags, int userId) {
5302        if (!sUserManager.exists(userId)) return Collections.emptyList();
5303        flags = updateFlagsForResolve(flags, userId, intent);
5304        enforceCrossUserPermission(Binder.getCallingUid(), userId,
5305                false /* requireFullPermission */, false /* checkShell */,
5306                "query intent activities");
5307        ComponentName comp = intent.getComponent();
5308        if (comp == null) {
5309            if (intent.getSelector() != null) {
5310                intent = intent.getSelector();
5311                comp = intent.getComponent();
5312            }
5313        }
5314
5315        if (comp != null) {
5316            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5317            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
5318            if (ai != null) {
5319                final ResolveInfo ri = new ResolveInfo();
5320                ri.activityInfo = ai;
5321                list.add(ri);
5322            }
5323            return list;
5324        }
5325
5326        // reader
5327        synchronized (mPackages) {
5328            final String pkgName = intent.getPackage();
5329            if (pkgName == null) {
5330                List<CrossProfileIntentFilter> matchingFilters =
5331                        getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
5332                // Check for results that need to skip the current profile.
5333                ResolveInfo xpResolveInfo  = querySkipCurrentProfileIntents(matchingFilters, intent,
5334                        resolvedType, flags, userId);
5335                if (xpResolveInfo != null) {
5336                    List<ResolveInfo> result = new ArrayList<ResolveInfo>(1);
5337                    result.add(xpResolveInfo);
5338                    return filterIfNotSystemUser(result, userId);
5339                }
5340
5341                // Check for results in the current profile.
5342                List<ResolveInfo> result = mActivities.queryIntent(
5343                        intent, resolvedType, flags, userId);
5344                result = filterIfNotSystemUser(result, userId);
5345
5346                // Check for cross profile results.
5347                boolean hasNonNegativePriorityResult = hasNonNegativePriority(result);
5348                xpResolveInfo = queryCrossProfileIntents(
5349                        matchingFilters, intent, resolvedType, flags, userId,
5350                        hasNonNegativePriorityResult);
5351                if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
5352                    boolean isVisibleToUser = filterIfNotSystemUser(
5353                            Collections.singletonList(xpResolveInfo), userId).size() > 0;
5354                    if (isVisibleToUser) {
5355                        result.add(xpResolveInfo);
5356                        Collections.sort(result, mResolvePrioritySorter);
5357                    }
5358                }
5359                if (hasWebURI(intent)) {
5360                    CrossProfileDomainInfo xpDomainInfo = null;
5361                    final UserInfo parent = getProfileParent(userId);
5362                    if (parent != null) {
5363                        xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType,
5364                                flags, userId, parent.id);
5365                    }
5366                    if (xpDomainInfo != null) {
5367                        if (xpResolveInfo != null) {
5368                            // If we didn't remove it, the cross-profile ResolveInfo would be twice
5369                            // in the result.
5370                            result.remove(xpResolveInfo);
5371                        }
5372                        if (result.size() == 0) {
5373                            result.add(xpDomainInfo.resolveInfo);
5374                            return result;
5375                        }
5376                    } else if (result.size() <= 1) {
5377                        return result;
5378                    }
5379                    result = filterCandidatesWithDomainPreferredActivitiesLPr(intent, flags, result,
5380                            xpDomainInfo, userId);
5381                    Collections.sort(result, mResolvePrioritySorter);
5382                }
5383                return result;
5384            }
5385            final PackageParser.Package pkg = mPackages.get(pkgName);
5386            if (pkg != null) {
5387                return filterIfNotSystemUser(
5388                        mActivities.queryIntentForPackage(
5389                                intent, resolvedType, flags, pkg.activities, userId),
5390                        userId);
5391            }
5392            return new ArrayList<ResolveInfo>();
5393        }
5394    }
5395
5396    private static class CrossProfileDomainInfo {
5397        /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */
5398        ResolveInfo resolveInfo;
5399        /* Best domain verification status of the activities found in the other profile */
5400        int bestDomainVerificationStatus;
5401    }
5402
5403    private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent,
5404            String resolvedType, int flags, int sourceUserId, int parentUserId) {
5405        if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING,
5406                sourceUserId)) {
5407            return null;
5408        }
5409        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
5410                resolvedType, flags, parentUserId);
5411
5412        if (resultTargetUser == null || resultTargetUser.isEmpty()) {
5413            return null;
5414        }
5415        CrossProfileDomainInfo result = null;
5416        int size = resultTargetUser.size();
5417        for (int i = 0; i < size; i++) {
5418            ResolveInfo riTargetUser = resultTargetUser.get(i);
5419            // Intent filter verification is only for filters that specify a host. So don't return
5420            // those that handle all web uris.
5421            if (riTargetUser.handleAllWebDataURI) {
5422                continue;
5423            }
5424            String packageName = riTargetUser.activityInfo.packageName;
5425            PackageSetting ps = mSettings.mPackages.get(packageName);
5426            if (ps == null) {
5427                continue;
5428            }
5429            long verificationState = getDomainVerificationStatusLPr(ps, parentUserId);
5430            int status = (int)(verificationState >> 32);
5431            if (result == null) {
5432                result = new CrossProfileDomainInfo();
5433                result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(),
5434                        sourceUserId, parentUserId);
5435                result.bestDomainVerificationStatus = status;
5436            } else {
5437                result.bestDomainVerificationStatus = bestDomainVerificationStatus(status,
5438                        result.bestDomainVerificationStatus);
5439            }
5440        }
5441        // Don't consider matches with status NEVER across profiles.
5442        if (result != null && result.bestDomainVerificationStatus
5443                == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5444            return null;
5445        }
5446        return result;
5447    }
5448
5449    /**
5450     * Verification statuses are ordered from the worse to the best, except for
5451     * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse.
5452     */
5453    private int bestDomainVerificationStatus(int status1, int status2) {
5454        if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5455            return status2;
5456        }
5457        if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5458            return status1;
5459        }
5460        return (int) MathUtils.max(status1, status2);
5461    }
5462
5463    private boolean isUserEnabled(int userId) {
5464        long callingId = Binder.clearCallingIdentity();
5465        try {
5466            UserInfo userInfo = sUserManager.getUserInfo(userId);
5467            return userInfo != null && userInfo.isEnabled();
5468        } finally {
5469            Binder.restoreCallingIdentity(callingId);
5470        }
5471    }
5472
5473    /**
5474     * Filter out activities with systemUserOnly flag set, when current user is not System.
5475     *
5476     * @return filtered list
5477     */
5478    private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) {
5479        if (userId == UserHandle.USER_SYSTEM) {
5480            return resolveInfos;
5481        }
5482        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
5483            ResolveInfo info = resolveInfos.get(i);
5484            if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) {
5485                resolveInfos.remove(i);
5486            }
5487        }
5488        return resolveInfos;
5489    }
5490
5491    /**
5492     * @param resolveInfos list of resolve infos in descending priority order
5493     * @return if the list contains a resolve info with non-negative priority
5494     */
5495    private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) {
5496        return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0;
5497    }
5498
5499    private static boolean hasWebURI(Intent intent) {
5500        if (intent.getData() == null) {
5501            return false;
5502        }
5503        final String scheme = intent.getScheme();
5504        if (TextUtils.isEmpty(scheme)) {
5505            return false;
5506        }
5507        return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS);
5508    }
5509
5510    private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent,
5511            int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo,
5512            int userId) {
5513        final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0;
5514
5515        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
5516            Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " +
5517                    candidates.size());
5518        }
5519
5520        ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>();
5521        ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>();
5522        ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>();
5523        ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>();
5524        ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>();
5525        ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>();
5526
5527        synchronized (mPackages) {
5528            final int count = candidates.size();
5529            // First, try to use linked apps. Partition the candidates into four lists:
5530            // one for the final results, one for the "do not use ever", one for "undefined status"
5531            // and finally one for "browser app type".
5532            for (int n=0; n<count; n++) {
5533                ResolveInfo info = candidates.get(n);
5534                String packageName = info.activityInfo.packageName;
5535                PackageSetting ps = mSettings.mPackages.get(packageName);
5536                if (ps != null) {
5537                    // Add to the special match all list (Browser use case)
5538                    if (info.handleAllWebDataURI) {
5539                        matchAllList.add(info);
5540                        continue;
5541                    }
5542                    // Try to get the status from User settings first
5543                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
5544                    int status = (int)(packedStatus >> 32);
5545                    int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
5546                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
5547                        if (DEBUG_DOMAIN_VERIFICATION) {
5548                            Slog.i(TAG, "  + always: " + info.activityInfo.packageName
5549                                    + " : linkgen=" + linkGeneration);
5550                        }
5551                        // Use link-enabled generation as preferredOrder, i.e.
5552                        // prefer newly-enabled over earlier-enabled.
5553                        info.preferredOrder = linkGeneration;
5554                        alwaysList.add(info);
5555                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5556                        if (DEBUG_DOMAIN_VERIFICATION) {
5557                            Slog.i(TAG, "  + never: " + info.activityInfo.packageName);
5558                        }
5559                        neverList.add(info);
5560                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
5561                        if (DEBUG_DOMAIN_VERIFICATION) {
5562                            Slog.i(TAG, "  + always-ask: " + info.activityInfo.packageName);
5563                        }
5564                        alwaysAskList.add(info);
5565                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED ||
5566                            status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) {
5567                        if (DEBUG_DOMAIN_VERIFICATION) {
5568                            Slog.i(TAG, "  + ask: " + info.activityInfo.packageName);
5569                        }
5570                        undefinedList.add(info);
5571                    }
5572                }
5573            }
5574
5575            // We'll want to include browser possibilities in a few cases
5576            boolean includeBrowser = false;
5577
5578            // First try to add the "always" resolution(s) for the current user, if any
5579            if (alwaysList.size() > 0) {
5580                result.addAll(alwaysList);
5581            } else {
5582                // Add all undefined apps as we want them to appear in the disambiguation dialog.
5583                result.addAll(undefinedList);
5584                // Maybe add one for the other profile.
5585                if (xpDomainInfo != null && (
5586                        xpDomainInfo.bestDomainVerificationStatus
5587                        != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) {
5588                    result.add(xpDomainInfo.resolveInfo);
5589                }
5590                includeBrowser = true;
5591            }
5592
5593            // The presence of any 'always ask' alternatives means we'll also offer browsers.
5594            // If there were 'always' entries their preferred order has been set, so we also
5595            // back that off to make the alternatives equivalent
5596            if (alwaysAskList.size() > 0) {
5597                for (ResolveInfo i : result) {
5598                    i.preferredOrder = 0;
5599                }
5600                result.addAll(alwaysAskList);
5601                includeBrowser = true;
5602            }
5603
5604            if (includeBrowser) {
5605                // Also add browsers (all of them or only the default one)
5606                if (DEBUG_DOMAIN_VERIFICATION) {
5607                    Slog.v(TAG, "   ...including browsers in candidate set");
5608                }
5609                if ((matchFlags & MATCH_ALL) != 0) {
5610                    result.addAll(matchAllList);
5611                } else {
5612                    // Browser/generic handling case.  If there's a default browser, go straight
5613                    // to that (but only if there is no other higher-priority match).
5614                    final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
5615                    int maxMatchPrio = 0;
5616                    ResolveInfo defaultBrowserMatch = null;
5617                    final int numCandidates = matchAllList.size();
5618                    for (int n = 0; n < numCandidates; n++) {
5619                        ResolveInfo info = matchAllList.get(n);
5620                        // track the highest overall match priority...
5621                        if (info.priority > maxMatchPrio) {
5622                            maxMatchPrio = info.priority;
5623                        }
5624                        // ...and the highest-priority default browser match
5625                        if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) {
5626                            if (defaultBrowserMatch == null
5627                                    || (defaultBrowserMatch.priority < info.priority)) {
5628                                if (debug) {
5629                                    Slog.v(TAG, "Considering default browser match " + info);
5630                                }
5631                                defaultBrowserMatch = info;
5632                            }
5633                        }
5634                    }
5635                    if (defaultBrowserMatch != null
5636                            && defaultBrowserMatch.priority >= maxMatchPrio
5637                            && !TextUtils.isEmpty(defaultBrowserPackageName))
5638                    {
5639                        if (debug) {
5640                            Slog.v(TAG, "Default browser match " + defaultBrowserMatch);
5641                        }
5642                        result.add(defaultBrowserMatch);
5643                    } else {
5644                        result.addAll(matchAllList);
5645                    }
5646                }
5647
5648                // If there is nothing selected, add all candidates and remove the ones that the user
5649                // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state
5650                if (result.size() == 0) {
5651                    result.addAll(candidates);
5652                    result.removeAll(neverList);
5653                }
5654            }
5655        }
5656        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
5657            Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " +
5658                    result.size());
5659            for (ResolveInfo info : result) {
5660                Slog.v(TAG, "  + " + info.activityInfo);
5661            }
5662        }
5663        return result;
5664    }
5665
5666    // Returns a packed value as a long:
5667    //
5668    // high 'int'-sized word: link status: undefined/ask/never/always.
5669    // low 'int'-sized word: relative priority among 'always' results.
5670    private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) {
5671        long result = ps.getDomainVerificationStatusForUser(userId);
5672        // if none available, get the master status
5673        if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
5674            if (ps.getIntentFilterVerificationInfo() != null) {
5675                result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32;
5676            }
5677        }
5678        return result;
5679    }
5680
5681    private ResolveInfo querySkipCurrentProfileIntents(
5682            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
5683            int flags, int sourceUserId) {
5684        if (matchingFilters != null) {
5685            int size = matchingFilters.size();
5686            for (int i = 0; i < size; i ++) {
5687                CrossProfileIntentFilter filter = matchingFilters.get(i);
5688                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
5689                    // Checking if there are activities in the target user that can handle the
5690                    // intent.
5691                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
5692                            resolvedType, flags, sourceUserId);
5693                    if (resolveInfo != null) {
5694                        return resolveInfo;
5695                    }
5696                }
5697            }
5698        }
5699        return null;
5700    }
5701
5702    // Return matching ResolveInfo in target user if any.
5703    private ResolveInfo queryCrossProfileIntents(
5704            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
5705            int flags, int sourceUserId, boolean matchInCurrentProfile) {
5706        if (matchingFilters != null) {
5707            // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
5708            // match the same intent. For performance reasons, it is better not to
5709            // run queryIntent twice for the same userId
5710            SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
5711            int size = matchingFilters.size();
5712            for (int i = 0; i < size; i++) {
5713                CrossProfileIntentFilter filter = matchingFilters.get(i);
5714                int targetUserId = filter.getTargetUserId();
5715                boolean skipCurrentProfile =
5716                        (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0;
5717                boolean skipCurrentProfileIfNoMatchFound =
5718                        (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0;
5719                if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId)
5720                        && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) {
5721                    // Checking if there are activities in the target user that can handle the
5722                    // intent.
5723                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
5724                            resolvedType, flags, sourceUserId);
5725                    if (resolveInfo != null) return resolveInfo;
5726                    alreadyTriedUserIds.put(targetUserId, true);
5727                }
5728            }
5729        }
5730        return null;
5731    }
5732
5733    /**
5734     * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that
5735     * will forward the intent to the filter's target user.
5736     * Otherwise, returns null.
5737     */
5738    private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent,
5739            String resolvedType, int flags, int sourceUserId) {
5740        int targetUserId = filter.getTargetUserId();
5741        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
5742                resolvedType, flags, targetUserId);
5743        if (resultTargetUser != null && isUserEnabled(targetUserId)) {
5744            // If all the matches in the target profile are suspended, return null.
5745            for (int i = resultTargetUser.size() - 1; i >= 0; i--) {
5746                if ((resultTargetUser.get(i).activityInfo.applicationInfo.flags
5747                        & ApplicationInfo.FLAG_SUSPENDED) == 0) {
5748                    return createForwardingResolveInfoUnchecked(filter, sourceUserId,
5749                            targetUserId);
5750                }
5751            }
5752        }
5753        return null;
5754    }
5755
5756    private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter,
5757            int sourceUserId, int targetUserId) {
5758        ResolveInfo forwardingResolveInfo = new ResolveInfo();
5759        long ident = Binder.clearCallingIdentity();
5760        boolean targetIsProfile;
5761        try {
5762            targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile();
5763        } finally {
5764            Binder.restoreCallingIdentity(ident);
5765        }
5766        String className;
5767        if (targetIsProfile) {
5768            className = FORWARD_INTENT_TO_MANAGED_PROFILE;
5769        } else {
5770            className = FORWARD_INTENT_TO_PARENT;
5771        }
5772        ComponentName forwardingActivityComponentName = new ComponentName(
5773                mAndroidApplication.packageName, className);
5774        ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
5775                sourceUserId);
5776        if (!targetIsProfile) {
5777            forwardingActivityInfo.showUserIcon = targetUserId;
5778            forwardingResolveInfo.noResourceId = true;
5779        }
5780        forwardingResolveInfo.activityInfo = forwardingActivityInfo;
5781        forwardingResolveInfo.priority = 0;
5782        forwardingResolveInfo.preferredOrder = 0;
5783        forwardingResolveInfo.match = 0;
5784        forwardingResolveInfo.isDefault = true;
5785        forwardingResolveInfo.filter = filter;
5786        forwardingResolveInfo.targetUserId = targetUserId;
5787        return forwardingResolveInfo;
5788    }
5789
5790    @Override
5791    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
5792            Intent[] specifics, String[] specificTypes, Intent intent,
5793            String resolvedType, int flags, int userId) {
5794        return new ParceledListSlice<>(queryIntentActivityOptionsInternal(caller, specifics,
5795                specificTypes, intent, resolvedType, flags, userId));
5796    }
5797
5798    private @NonNull List<ResolveInfo> queryIntentActivityOptionsInternal(ComponentName caller,
5799            Intent[] specifics, String[] specificTypes, Intent intent,
5800            String resolvedType, int flags, int userId) {
5801        if (!sUserManager.exists(userId)) return Collections.emptyList();
5802        flags = updateFlagsForResolve(flags, userId, intent);
5803        enforceCrossUserPermission(Binder.getCallingUid(), userId,
5804                false /* requireFullPermission */, false /* checkShell */,
5805                "query intent activity options");
5806        final String resultsAction = intent.getAction();
5807
5808        final List<ResolveInfo> results = queryIntentActivitiesInternal(intent, resolvedType, flags
5809                | PackageManager.GET_RESOLVED_FILTER, userId);
5810
5811        if (DEBUG_INTENT_MATCHING) {
5812            Log.v(TAG, "Query " + intent + ": " + results);
5813        }
5814
5815        int specificsPos = 0;
5816        int N;
5817
5818        // todo: note that the algorithm used here is O(N^2).  This
5819        // isn't a problem in our current environment, but if we start running
5820        // into situations where we have more than 5 or 10 matches then this
5821        // should probably be changed to something smarter...
5822
5823        // First we go through and resolve each of the specific items
5824        // that were supplied, taking care of removing any corresponding
5825        // duplicate items in the generic resolve list.
5826        if (specifics != null) {
5827            for (int i=0; i<specifics.length; i++) {
5828                final Intent sintent = specifics[i];
5829                if (sintent == null) {
5830                    continue;
5831                }
5832
5833                if (DEBUG_INTENT_MATCHING) {
5834                    Log.v(TAG, "Specific #" + i + ": " + sintent);
5835                }
5836
5837                String action = sintent.getAction();
5838                if (resultsAction != null && resultsAction.equals(action)) {
5839                    // If this action was explicitly requested, then don't
5840                    // remove things that have it.
5841                    action = null;
5842                }
5843
5844                ResolveInfo ri = null;
5845                ActivityInfo ai = null;
5846
5847                ComponentName comp = sintent.getComponent();
5848                if (comp == null) {
5849                    ri = resolveIntent(
5850                        sintent,
5851                        specificTypes != null ? specificTypes[i] : null,
5852                            flags, userId);
5853                    if (ri == null) {
5854                        continue;
5855                    }
5856                    if (ri == mResolveInfo) {
5857                        // ACK!  Must do something better with this.
5858                    }
5859                    ai = ri.activityInfo;
5860                    comp = new ComponentName(ai.applicationInfo.packageName,
5861                            ai.name);
5862                } else {
5863                    ai = getActivityInfo(comp, flags, userId);
5864                    if (ai == null) {
5865                        continue;
5866                    }
5867                }
5868
5869                // Look for any generic query activities that are duplicates
5870                // of this specific one, and remove them from the results.
5871                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
5872                N = results.size();
5873                int j;
5874                for (j=specificsPos; j<N; j++) {
5875                    ResolveInfo sri = results.get(j);
5876                    if ((sri.activityInfo.name.equals(comp.getClassName())
5877                            && sri.activityInfo.applicationInfo.packageName.equals(
5878                                    comp.getPackageName()))
5879                        || (action != null && sri.filter.matchAction(action))) {
5880                        results.remove(j);
5881                        if (DEBUG_INTENT_MATCHING) Log.v(
5882                            TAG, "Removing duplicate item from " + j
5883                            + " due to specific " + specificsPos);
5884                        if (ri == null) {
5885                            ri = sri;
5886                        }
5887                        j--;
5888                        N--;
5889                    }
5890                }
5891
5892                // Add this specific item to its proper place.
5893                if (ri == null) {
5894                    ri = new ResolveInfo();
5895                    ri.activityInfo = ai;
5896                }
5897                results.add(specificsPos, ri);
5898                ri.specificIndex = i;
5899                specificsPos++;
5900            }
5901        }
5902
5903        // Now we go through the remaining generic results and remove any
5904        // duplicate actions that are found here.
5905        N = results.size();
5906        for (int i=specificsPos; i<N-1; i++) {
5907            final ResolveInfo rii = results.get(i);
5908            if (rii.filter == null) {
5909                continue;
5910            }
5911
5912            // Iterate over all of the actions of this result's intent
5913            // filter...  typically this should be just one.
5914            final Iterator<String> it = rii.filter.actionsIterator();
5915            if (it == null) {
5916                continue;
5917            }
5918            while (it.hasNext()) {
5919                final String action = it.next();
5920                if (resultsAction != null && resultsAction.equals(action)) {
5921                    // If this action was explicitly requested, then don't
5922                    // remove things that have it.
5923                    continue;
5924                }
5925                for (int j=i+1; j<N; j++) {
5926                    final ResolveInfo rij = results.get(j);
5927                    if (rij.filter != null && rij.filter.hasAction(action)) {
5928                        results.remove(j);
5929                        if (DEBUG_INTENT_MATCHING) Log.v(
5930                            TAG, "Removing duplicate item from " + j
5931                            + " due to action " + action + " at " + i);
5932                        j--;
5933                        N--;
5934                    }
5935                }
5936            }
5937
5938            // If the caller didn't request filter information, drop it now
5939            // so we don't have to marshall/unmarshall it.
5940            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
5941                rii.filter = null;
5942            }
5943        }
5944
5945        // Filter out the caller activity if so requested.
5946        if (caller != null) {
5947            N = results.size();
5948            for (int i=0; i<N; i++) {
5949                ActivityInfo ainfo = results.get(i).activityInfo;
5950                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
5951                        && caller.getClassName().equals(ainfo.name)) {
5952                    results.remove(i);
5953                    break;
5954                }
5955            }
5956        }
5957
5958        // If the caller didn't request filter information,
5959        // drop them now so we don't have to
5960        // marshall/unmarshall it.
5961        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
5962            N = results.size();
5963            for (int i=0; i<N; i++) {
5964                results.get(i).filter = null;
5965            }
5966        }
5967
5968        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
5969        return results;
5970    }
5971
5972    @Override
5973    public @NonNull ParceledListSlice<ResolveInfo> queryIntentReceivers(Intent intent,
5974            String resolvedType, int flags, int userId) {
5975        return new ParceledListSlice<>(
5976                queryIntentReceiversInternal(intent, resolvedType, flags, userId));
5977    }
5978
5979    private @NonNull List<ResolveInfo> queryIntentReceiversInternal(Intent intent,
5980            String resolvedType, int flags, int userId) {
5981        if (!sUserManager.exists(userId)) return Collections.emptyList();
5982        flags = updateFlagsForResolve(flags, userId, intent);
5983        ComponentName comp = intent.getComponent();
5984        if (comp == null) {
5985            if (intent.getSelector() != null) {
5986                intent = intent.getSelector();
5987                comp = intent.getComponent();
5988            }
5989        }
5990        if (comp != null) {
5991            List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5992            ActivityInfo ai = getReceiverInfo(comp, flags, userId);
5993            if (ai != null) {
5994                ResolveInfo ri = new ResolveInfo();
5995                ri.activityInfo = ai;
5996                list.add(ri);
5997            }
5998            return list;
5999        }
6000
6001        // reader
6002        synchronized (mPackages) {
6003            String pkgName = intent.getPackage();
6004            if (pkgName == null) {
6005                return mReceivers.queryIntent(intent, resolvedType, flags, userId);
6006            }
6007            final PackageParser.Package pkg = mPackages.get(pkgName);
6008            if (pkg != null) {
6009                return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers,
6010                        userId);
6011            }
6012            return Collections.emptyList();
6013        }
6014    }
6015
6016    @Override
6017    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
6018        if (!sUserManager.exists(userId)) return null;
6019        flags = updateFlagsForResolve(flags, userId, intent);
6020        List<ResolveInfo> query = queryIntentServicesInternal(intent, resolvedType, flags, userId);
6021        if (query != null) {
6022            if (query.size() >= 1) {
6023                // If there is more than one service with the same priority,
6024                // just arbitrarily pick the first one.
6025                return query.get(0);
6026            }
6027        }
6028        return null;
6029    }
6030
6031    @Override
6032    public @NonNull ParceledListSlice<ResolveInfo> queryIntentServices(Intent intent,
6033            String resolvedType, int flags, int userId) {
6034        return new ParceledListSlice<>(
6035                queryIntentServicesInternal(intent, resolvedType, flags, userId));
6036    }
6037
6038    private @NonNull List<ResolveInfo> queryIntentServicesInternal(Intent intent,
6039            String resolvedType, int flags, int userId) {
6040        if (!sUserManager.exists(userId)) return Collections.emptyList();
6041        flags = updateFlagsForResolve(flags, userId, intent);
6042        ComponentName comp = intent.getComponent();
6043        if (comp == null) {
6044            if (intent.getSelector() != null) {
6045                intent = intent.getSelector();
6046                comp = intent.getComponent();
6047            }
6048        }
6049        if (comp != null) {
6050            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
6051            final ServiceInfo si = getServiceInfo(comp, flags, userId);
6052            if (si != null) {
6053                final ResolveInfo ri = new ResolveInfo();
6054                ri.serviceInfo = si;
6055                list.add(ri);
6056            }
6057            return list;
6058        }
6059
6060        // reader
6061        synchronized (mPackages) {
6062            String pkgName = intent.getPackage();
6063            if (pkgName == null) {
6064                return mServices.queryIntent(intent, resolvedType, flags, userId);
6065            }
6066            final PackageParser.Package pkg = mPackages.get(pkgName);
6067            if (pkg != null) {
6068                return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
6069                        userId);
6070            }
6071            return Collections.emptyList();
6072        }
6073    }
6074
6075    @Override
6076    public @NonNull ParceledListSlice<ResolveInfo> queryIntentContentProviders(Intent intent,
6077            String resolvedType, int flags, int userId) {
6078        return new ParceledListSlice<>(
6079                queryIntentContentProvidersInternal(intent, resolvedType, flags, userId));
6080    }
6081
6082    private @NonNull List<ResolveInfo> queryIntentContentProvidersInternal(
6083            Intent intent, String resolvedType, int flags, int userId) {
6084        if (!sUserManager.exists(userId)) return Collections.emptyList();
6085        flags = updateFlagsForResolve(flags, userId, intent);
6086        ComponentName comp = intent.getComponent();
6087        if (comp == null) {
6088            if (intent.getSelector() != null) {
6089                intent = intent.getSelector();
6090                comp = intent.getComponent();
6091            }
6092        }
6093        if (comp != null) {
6094            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
6095            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
6096            if (pi != null) {
6097                final ResolveInfo ri = new ResolveInfo();
6098                ri.providerInfo = pi;
6099                list.add(ri);
6100            }
6101            return list;
6102        }
6103
6104        // reader
6105        synchronized (mPackages) {
6106            String pkgName = intent.getPackage();
6107            if (pkgName == null) {
6108                return mProviders.queryIntent(intent, resolvedType, flags, userId);
6109            }
6110            final PackageParser.Package pkg = mPackages.get(pkgName);
6111            if (pkg != null) {
6112                return mProviders.queryIntentForPackage(
6113                        intent, resolvedType, flags, pkg.providers, userId);
6114            }
6115            return Collections.emptyList();
6116        }
6117    }
6118
6119    @Override
6120    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
6121        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
6122        flags = updateFlagsForPackage(flags, userId, null);
6123        final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0;
6124        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6125                true /* requireFullPermission */, false /* checkShell */,
6126                "get installed packages");
6127
6128        // writer
6129        synchronized (mPackages) {
6130            ArrayList<PackageInfo> list;
6131            if (listUninstalled) {
6132                list = new ArrayList<PackageInfo>(mSettings.mPackages.size());
6133                for (PackageSetting ps : mSettings.mPackages.values()) {
6134                    final PackageInfo pi;
6135                    if (ps.pkg != null) {
6136                        pi = generatePackageInfo(ps, flags, userId);
6137                    } else {
6138                        pi = generatePackageInfo(ps, flags, userId);
6139                    }
6140                    if (pi != null) {
6141                        list.add(pi);
6142                    }
6143                }
6144            } else {
6145                list = new ArrayList<PackageInfo>(mPackages.size());
6146                for (PackageParser.Package p : mPackages.values()) {
6147                    final PackageInfo pi =
6148                            generatePackageInfo((PackageSetting)p.mExtras, flags, userId);
6149                    if (pi != null) {
6150                        list.add(pi);
6151                    }
6152                }
6153            }
6154
6155            return new ParceledListSlice<PackageInfo>(list);
6156        }
6157    }
6158
6159    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
6160            String[] permissions, boolean[] tmp, int flags, int userId) {
6161        int numMatch = 0;
6162        final PermissionsState permissionsState = ps.getPermissionsState();
6163        for (int i=0; i<permissions.length; i++) {
6164            final String permission = permissions[i];
6165            if (permissionsState.hasPermission(permission, userId)) {
6166                tmp[i] = true;
6167                numMatch++;
6168            } else {
6169                tmp[i] = false;
6170            }
6171        }
6172        if (numMatch == 0) {
6173            return;
6174        }
6175        final PackageInfo pi;
6176        if (ps.pkg != null) {
6177            pi = generatePackageInfo(ps, flags, userId);
6178        } else {
6179            pi = generatePackageInfo(ps, flags, userId);
6180        }
6181        // The above might return null in cases of uninstalled apps or install-state
6182        // skew across users/profiles.
6183        if (pi != null) {
6184            if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
6185                if (numMatch == permissions.length) {
6186                    pi.requestedPermissions = permissions;
6187                } else {
6188                    pi.requestedPermissions = new String[numMatch];
6189                    numMatch = 0;
6190                    for (int i=0; i<permissions.length; i++) {
6191                        if (tmp[i]) {
6192                            pi.requestedPermissions[numMatch] = permissions[i];
6193                            numMatch++;
6194                        }
6195                    }
6196                }
6197            }
6198            list.add(pi);
6199        }
6200    }
6201
6202    @Override
6203    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
6204            String[] permissions, int flags, int userId) {
6205        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
6206        flags = updateFlagsForPackage(flags, userId, permissions);
6207        final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0;
6208
6209        // writer
6210        synchronized (mPackages) {
6211            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
6212            boolean[] tmpBools = new boolean[permissions.length];
6213            if (listUninstalled) {
6214                for (PackageSetting ps : mSettings.mPackages.values()) {
6215                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId);
6216                }
6217            } else {
6218                for (PackageParser.Package pkg : mPackages.values()) {
6219                    PackageSetting ps = (PackageSetting)pkg.mExtras;
6220                    if (ps != null) {
6221                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
6222                                userId);
6223                    }
6224                }
6225            }
6226
6227            return new ParceledListSlice<PackageInfo>(list);
6228        }
6229    }
6230
6231    @Override
6232    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
6233        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
6234        flags = updateFlagsForApplication(flags, userId, null);
6235        final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0;
6236
6237        // writer
6238        synchronized (mPackages) {
6239            ArrayList<ApplicationInfo> list;
6240            if (listUninstalled) {
6241                list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size());
6242                for (PackageSetting ps : mSettings.mPackages.values()) {
6243                    ApplicationInfo ai;
6244                    if (ps.pkg != null) {
6245                        ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
6246                                ps.readUserState(userId), userId);
6247                    } else {
6248                        ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId);
6249                    }
6250                    if (ai != null) {
6251                        list.add(ai);
6252                    }
6253                }
6254            } else {
6255                list = new ArrayList<ApplicationInfo>(mPackages.size());
6256                for (PackageParser.Package p : mPackages.values()) {
6257                    if (p.mExtras != null) {
6258                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
6259                                ((PackageSetting)p.mExtras).readUserState(userId), userId);
6260                        if (ai != null) {
6261                            list.add(ai);
6262                        }
6263                    }
6264                }
6265            }
6266
6267            return new ParceledListSlice<ApplicationInfo>(list);
6268        }
6269    }
6270
6271    @Override
6272    public ParceledListSlice<EphemeralApplicationInfo> getEphemeralApplications(int userId) {
6273        if (DISABLE_EPHEMERAL_APPS) {
6274            return null;
6275        }
6276
6277        mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS,
6278                "getEphemeralApplications");
6279        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6280                true /* requireFullPermission */, false /* checkShell */,
6281                "getEphemeralApplications");
6282        synchronized (mPackages) {
6283            List<EphemeralApplicationInfo> ephemeralApps = mEphemeralApplicationRegistry
6284                    .getEphemeralApplicationsLPw(userId);
6285            if (ephemeralApps != null) {
6286                return new ParceledListSlice<>(ephemeralApps);
6287            }
6288        }
6289        return null;
6290    }
6291
6292    @Override
6293    public boolean isEphemeralApplication(String packageName, int userId) {
6294        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6295                true /* requireFullPermission */, false /* checkShell */,
6296                "isEphemeral");
6297        if (DISABLE_EPHEMERAL_APPS) {
6298            return false;
6299        }
6300
6301        if (!isCallerSameApp(packageName)) {
6302            return false;
6303        }
6304        synchronized (mPackages) {
6305            PackageParser.Package pkg = mPackages.get(packageName);
6306            if (pkg != null) {
6307                return pkg.applicationInfo.isEphemeralApp();
6308            }
6309        }
6310        return false;
6311    }
6312
6313    @Override
6314    public byte[] getEphemeralApplicationCookie(String packageName, int userId) {
6315        if (DISABLE_EPHEMERAL_APPS) {
6316            return null;
6317        }
6318
6319        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6320                true /* requireFullPermission */, false /* checkShell */,
6321                "getCookie");
6322        if (!isCallerSameApp(packageName)) {
6323            return null;
6324        }
6325        synchronized (mPackages) {
6326            return mEphemeralApplicationRegistry.getEphemeralApplicationCookieLPw(
6327                    packageName, userId);
6328        }
6329    }
6330
6331    @Override
6332    public boolean setEphemeralApplicationCookie(String packageName, byte[] cookie, int userId) {
6333        if (DISABLE_EPHEMERAL_APPS) {
6334            return true;
6335        }
6336
6337        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6338                true /* requireFullPermission */, true /* checkShell */,
6339                "setCookie");
6340        if (!isCallerSameApp(packageName)) {
6341            return false;
6342        }
6343        synchronized (mPackages) {
6344            return mEphemeralApplicationRegistry.setEphemeralApplicationCookieLPw(
6345                    packageName, cookie, userId);
6346        }
6347    }
6348
6349    @Override
6350    public Bitmap getEphemeralApplicationIcon(String packageName, int userId) {
6351        if (DISABLE_EPHEMERAL_APPS) {
6352            return null;
6353        }
6354
6355        mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS,
6356                "getEphemeralApplicationIcon");
6357        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6358                true /* requireFullPermission */, false /* checkShell */,
6359                "getEphemeralApplicationIcon");
6360        synchronized (mPackages) {
6361            return mEphemeralApplicationRegistry.getEphemeralApplicationIconLPw(
6362                    packageName, userId);
6363        }
6364    }
6365
6366    private boolean isCallerSameApp(String packageName) {
6367        PackageParser.Package pkg = mPackages.get(packageName);
6368        return pkg != null
6369                && UserHandle.getAppId(Binder.getCallingUid()) == pkg.applicationInfo.uid;
6370    }
6371
6372    @Override
6373    public @NonNull ParceledListSlice<ApplicationInfo> getPersistentApplications(int flags) {
6374        return new ParceledListSlice<>(getPersistentApplicationsInternal(flags));
6375    }
6376
6377    private @NonNull List<ApplicationInfo> getPersistentApplicationsInternal(int flags) {
6378        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
6379
6380        // reader
6381        synchronized (mPackages) {
6382            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
6383            final int userId = UserHandle.getCallingUserId();
6384            while (i.hasNext()) {
6385                final PackageParser.Package p = i.next();
6386                if (p.applicationInfo == null) continue;
6387
6388                final boolean matchesUnaware = ((flags & MATCH_DIRECT_BOOT_UNAWARE) != 0)
6389                        && !p.applicationInfo.isDirectBootAware();
6390                final boolean matchesAware = ((flags & MATCH_DIRECT_BOOT_AWARE) != 0)
6391                        && p.applicationInfo.isDirectBootAware();
6392
6393                if ((p.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0
6394                        && (!mSafeMode || isSystemApp(p))
6395                        && (matchesUnaware || matchesAware)) {
6396                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
6397                    if (ps != null) {
6398                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
6399                                ps.readUserState(userId), userId);
6400                        if (ai != null) {
6401                            finalList.add(ai);
6402                        }
6403                    }
6404                }
6405            }
6406        }
6407
6408        return finalList;
6409    }
6410
6411    @Override
6412    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
6413        if (!sUserManager.exists(userId)) return null;
6414        flags = updateFlagsForComponent(flags, userId, name);
6415        // reader
6416        synchronized (mPackages) {
6417            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
6418            PackageSetting ps = provider != null
6419                    ? mSettings.mPackages.get(provider.owner.packageName)
6420                    : null;
6421            return ps != null
6422                    && mSettings.isEnabledAndMatchLPr(provider.info, flags, userId)
6423                    ? PackageParser.generateProviderInfo(provider, flags,
6424                            ps.readUserState(userId), userId)
6425                    : null;
6426        }
6427    }
6428
6429    /**
6430     * @deprecated
6431     */
6432    @Deprecated
6433    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
6434        // reader
6435        synchronized (mPackages) {
6436            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
6437                    .entrySet().iterator();
6438            final int userId = UserHandle.getCallingUserId();
6439            while (i.hasNext()) {
6440                Map.Entry<String, PackageParser.Provider> entry = i.next();
6441                PackageParser.Provider p = entry.getValue();
6442                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
6443
6444                if (ps != null && p.syncable
6445                        && (!mSafeMode || (p.info.applicationInfo.flags
6446                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
6447                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
6448                            ps.readUserState(userId), userId);
6449                    if (info != null) {
6450                        outNames.add(entry.getKey());
6451                        outInfo.add(info);
6452                    }
6453                }
6454            }
6455        }
6456    }
6457
6458    @Override
6459    public @NonNull ParceledListSlice<ProviderInfo> queryContentProviders(String processName,
6460            int uid, int flags) {
6461        final int userId = processName != null ? UserHandle.getUserId(uid)
6462                : UserHandle.getCallingUserId();
6463        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
6464        flags = updateFlagsForComponent(flags, userId, processName);
6465
6466        ArrayList<ProviderInfo> finalList = null;
6467        // reader
6468        synchronized (mPackages) {
6469            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
6470            while (i.hasNext()) {
6471                final PackageParser.Provider p = i.next();
6472                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
6473                if (ps != null && p.info.authority != null
6474                        && (processName == null
6475                                || (p.info.processName.equals(processName)
6476                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
6477                        && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
6478                    if (finalList == null) {
6479                        finalList = new ArrayList<ProviderInfo>(3);
6480                    }
6481                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
6482                            ps.readUserState(userId), userId);
6483                    if (info != null) {
6484                        finalList.add(info);
6485                    }
6486                }
6487            }
6488        }
6489
6490        if (finalList != null) {
6491            Collections.sort(finalList, mProviderInitOrderSorter);
6492            return new ParceledListSlice<ProviderInfo>(finalList);
6493        }
6494
6495        return ParceledListSlice.emptyList();
6496    }
6497
6498    @Override
6499    public InstrumentationInfo getInstrumentationInfo(ComponentName name, int flags) {
6500        // reader
6501        synchronized (mPackages) {
6502            final PackageParser.Instrumentation i = mInstrumentation.get(name);
6503            return PackageParser.generateInstrumentationInfo(i, flags);
6504        }
6505    }
6506
6507    @Override
6508    public @NonNull ParceledListSlice<InstrumentationInfo> queryInstrumentation(
6509            String targetPackage, int flags) {
6510        return new ParceledListSlice<>(queryInstrumentationInternal(targetPackage, flags));
6511    }
6512
6513    private @NonNull List<InstrumentationInfo> queryInstrumentationInternal(String targetPackage,
6514            int flags) {
6515        ArrayList<InstrumentationInfo> finalList = new ArrayList<InstrumentationInfo>();
6516
6517        // reader
6518        synchronized (mPackages) {
6519            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
6520            while (i.hasNext()) {
6521                final PackageParser.Instrumentation p = i.next();
6522                if (targetPackage == null
6523                        || targetPackage.equals(p.info.targetPackage)) {
6524                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
6525                            flags);
6526                    if (ii != null) {
6527                        finalList.add(ii);
6528                    }
6529                }
6530            }
6531        }
6532
6533        return finalList;
6534    }
6535
6536    private void createIdmapsForPackageLI(PackageParser.Package pkg) {
6537        ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName);
6538        if (overlays == null) {
6539            Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages");
6540            return;
6541        }
6542        for (PackageParser.Package opkg : overlays.values()) {
6543            // Not much to do if idmap fails: we already logged the error
6544            // and we certainly don't want to abort installation of pkg simply
6545            // because an overlay didn't fit properly. For these reasons,
6546            // ignore the return value of createIdmapForPackagePairLI.
6547            createIdmapForPackagePairLI(pkg, opkg);
6548        }
6549    }
6550
6551    private boolean createIdmapForPackagePairLI(PackageParser.Package pkg,
6552            PackageParser.Package opkg) {
6553        if (!opkg.mTrustedOverlay) {
6554            Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " +
6555                    opkg.baseCodePath + ": overlay not trusted");
6556            return false;
6557        }
6558        ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName);
6559        if (overlaySet == null) {
6560            Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " +
6561                    opkg.baseCodePath + " but target package has no known overlays");
6562            return false;
6563        }
6564        final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
6565        // TODO: generate idmap for split APKs
6566        try {
6567            mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid);
6568        } catch (InstallerException e) {
6569            Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and "
6570                    + opkg.baseCodePath);
6571            return false;
6572        }
6573        PackageParser.Package[] overlayArray =
6574            overlaySet.values().toArray(new PackageParser.Package[0]);
6575        Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() {
6576            public int compare(PackageParser.Package p1, PackageParser.Package p2) {
6577                return p1.mOverlayPriority - p2.mOverlayPriority;
6578            }
6579        };
6580        Arrays.sort(overlayArray, cmp);
6581
6582        pkg.applicationInfo.resourceDirs = new String[overlayArray.length];
6583        int i = 0;
6584        for (PackageParser.Package p : overlayArray) {
6585            pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath;
6586        }
6587        return true;
6588    }
6589
6590    private void scanDirTracedLI(File dir, final int parseFlags, int scanFlags, long currentTime) {
6591        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir");
6592        try {
6593            scanDirLI(dir, parseFlags, scanFlags, currentTime);
6594        } finally {
6595            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6596        }
6597    }
6598
6599    private void scanDirLI(File dir, final int parseFlags, int scanFlags, long currentTime) {
6600        final File[] files = dir.listFiles();
6601        if (ArrayUtils.isEmpty(files)) {
6602            Log.d(TAG, "No files in app dir " + dir);
6603            return;
6604        }
6605
6606        if (DEBUG_PACKAGE_SCANNING) {
6607            Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags
6608                    + " flags=0x" + Integer.toHexString(parseFlags));
6609        }
6610
6611        for (File file : files) {
6612            final boolean isPackage = (isApkFile(file) || file.isDirectory())
6613                    && !PackageInstallerService.isStageName(file.getName());
6614            if (!isPackage) {
6615                // Ignore entries which are not packages
6616                continue;
6617            }
6618            try {
6619                scanPackageTracedLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK,
6620                        scanFlags, currentTime, null);
6621            } catch (PackageManagerException e) {
6622                Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage());
6623
6624                // Delete invalid userdata apps
6625                if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
6626                        e.error == PackageManager.INSTALL_FAILED_INVALID_APK) {
6627                    logCriticalInfo(Log.WARN, "Deleting invalid package at " + file);
6628                    removeCodePathLI(file);
6629                }
6630            }
6631        }
6632    }
6633
6634    private static File getSettingsProblemFile() {
6635        File dataDir = Environment.getDataDirectory();
6636        File systemDir = new File(dataDir, "system");
6637        File fname = new File(systemDir, "uiderrors.txt");
6638        return fname;
6639    }
6640
6641    static void reportSettingsProblem(int priority, String msg) {
6642        logCriticalInfo(priority, msg);
6643    }
6644
6645    static void logCriticalInfo(int priority, String msg) {
6646        Slog.println(priority, TAG, msg);
6647        EventLogTags.writePmCriticalInfo(msg);
6648        try {
6649            File fname = getSettingsProblemFile();
6650            FileOutputStream out = new FileOutputStream(fname, true);
6651            PrintWriter pw = new FastPrintWriter(out);
6652            SimpleDateFormat formatter = new SimpleDateFormat();
6653            String dateString = formatter.format(new Date(System.currentTimeMillis()));
6654            pw.println(dateString + ": " + msg);
6655            pw.close();
6656            FileUtils.setPermissions(
6657                    fname.toString(),
6658                    FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
6659                    -1, -1);
6660        } catch (java.io.IOException e) {
6661        }
6662    }
6663
6664    private void collectCertificatesLI(PackageSetting ps, PackageParser.Package pkg, File srcFile,
6665            final int policyFlags) throws PackageManagerException {
6666        if (ps != null
6667                && ps.codePath.equals(srcFile)
6668                && ps.timeStamp == srcFile.lastModified()
6669                && !isCompatSignatureUpdateNeeded(pkg)
6670                && !isRecoverSignatureUpdateNeeded(pkg)) {
6671            long mSigningKeySetId = ps.keySetData.getProperSigningKeySet();
6672            KeySetManagerService ksms = mSettings.mKeySetManagerService;
6673            ArraySet<PublicKey> signingKs;
6674            synchronized (mPackages) {
6675                signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId);
6676            }
6677            if (ps.signatures.mSignatures != null
6678                    && ps.signatures.mSignatures.length != 0
6679                    && signingKs != null) {
6680                // Optimization: reuse the existing cached certificates
6681                // if the package appears to be unchanged.
6682                pkg.mSignatures = ps.signatures.mSignatures;
6683                pkg.mSigningKeys = signingKs;
6684                return;
6685            }
6686
6687            Slog.w(TAG, "PackageSetting for " + ps.name
6688                    + " is missing signatures.  Collecting certs again to recover them.");
6689        } else {
6690            Log.i(TAG, srcFile.toString() + " changed; collecting certs");
6691        }
6692
6693        try {
6694            PackageParser.collectCertificates(pkg, policyFlags);
6695        } catch (PackageParserException e) {
6696            throw PackageManagerException.from(e);
6697        }
6698    }
6699
6700    /**
6701     *  Traces a package scan.
6702     *  @see #scanPackageLI(File, int, int, long, UserHandle)
6703     */
6704    private PackageParser.Package scanPackageTracedLI(File scanFile, final int parseFlags,
6705            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
6706        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage");
6707        try {
6708            return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user);
6709        } finally {
6710            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6711        }
6712    }
6713
6714    /**
6715     *  Scans a package and returns the newly parsed package.
6716     *  Returns {@code null} in case of errors and the error code is stored in mLastScanError
6717     */
6718    private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags,
6719            long currentTime, UserHandle user) throws PackageManagerException {
6720        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
6721        PackageParser pp = new PackageParser();
6722        pp.setSeparateProcesses(mSeparateProcesses);
6723        pp.setOnlyCoreApps(mOnlyCore);
6724        pp.setDisplayMetrics(mMetrics);
6725
6726        if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) {
6727            parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY;
6728        }
6729
6730        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
6731        final PackageParser.Package pkg;
6732        try {
6733            pkg = pp.parsePackage(scanFile, parseFlags);
6734        } catch (PackageParserException e) {
6735            throw PackageManagerException.from(e);
6736        } finally {
6737            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6738        }
6739
6740        return scanPackageLI(pkg, scanFile, parseFlags, scanFlags, currentTime, user);
6741    }
6742
6743    /**
6744     *  Scans a package and returns the newly parsed package.
6745     *  @throws PackageManagerException on a parse error.
6746     */
6747    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, File scanFile,
6748            final int policyFlags, int scanFlags, long currentTime, UserHandle user)
6749            throws PackageManagerException {
6750        // If the package has children and this is the first dive in the function
6751        // we scan the package with the SCAN_CHECK_ONLY flag set to see whether all
6752        // packages (parent and children) would be successfully scanned before the
6753        // actual scan since scanning mutates internal state and we want to atomically
6754        // install the package and its children.
6755        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
6756            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
6757                scanFlags |= SCAN_CHECK_ONLY;
6758            }
6759        } else {
6760            scanFlags &= ~SCAN_CHECK_ONLY;
6761        }
6762
6763        // Scan the parent
6764        PackageParser.Package scannedPkg = scanPackageInternalLI(pkg, scanFile, policyFlags,
6765                scanFlags, currentTime, user);
6766
6767        // Scan the children
6768        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
6769        for (int i = 0; i < childCount; i++) {
6770            PackageParser.Package childPackage = pkg.childPackages.get(i);
6771            scanPackageInternalLI(childPackage, scanFile, policyFlags, scanFlags,
6772                    currentTime, user);
6773        }
6774
6775
6776        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
6777            return scanPackageLI(pkg, scanFile, policyFlags, scanFlags, currentTime, user);
6778        }
6779
6780        return scannedPkg;
6781    }
6782
6783    /**
6784     *  Scans a package and returns the newly parsed package.
6785     *  @throws PackageManagerException on a parse error.
6786     */
6787    private PackageParser.Package scanPackageInternalLI(PackageParser.Package pkg, File scanFile,
6788            int policyFlags, int scanFlags, long currentTime, UserHandle user)
6789            throws PackageManagerException {
6790        PackageSetting ps = null;
6791        PackageSetting updatedPkg;
6792        // reader
6793        synchronized (mPackages) {
6794            // Look to see if we already know about this package.
6795            String oldName = mSettings.mRenamedPackages.get(pkg.packageName);
6796            if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
6797                // This package has been renamed to its original name.  Let's
6798                // use that.
6799                ps = mSettings.peekPackageLPr(oldName);
6800            }
6801            // If there was no original package, see one for the real package name.
6802            if (ps == null) {
6803                ps = mSettings.peekPackageLPr(pkg.packageName);
6804            }
6805            // Check to see if this package could be hiding/updating a system
6806            // package.  Must look for it either under the original or real
6807            // package name depending on our state.
6808            updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName);
6809            if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg);
6810
6811            // If this is a package we don't know about on the system partition, we
6812            // may need to remove disabled child packages on the system partition
6813            // or may need to not add child packages if the parent apk is updated
6814            // on the data partition and no longer defines this child package.
6815            if ((policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) {
6816                // If this is a parent package for an updated system app and this system
6817                // app got an OTA update which no longer defines some of the child packages
6818                // we have to prune them from the disabled system packages.
6819                PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName);
6820                if (disabledPs != null) {
6821                    final int scannedChildCount = (pkg.childPackages != null)
6822                            ? pkg.childPackages.size() : 0;
6823                    final int disabledChildCount = disabledPs.childPackageNames != null
6824                            ? disabledPs.childPackageNames.size() : 0;
6825                    for (int i = 0; i < disabledChildCount; i++) {
6826                        String disabledChildPackageName = disabledPs.childPackageNames.get(i);
6827                        boolean disabledPackageAvailable = false;
6828                        for (int j = 0; j < scannedChildCount; j++) {
6829                            PackageParser.Package childPkg = pkg.childPackages.get(j);
6830                            if (childPkg.packageName.equals(disabledChildPackageName)) {
6831                                disabledPackageAvailable = true;
6832                                break;
6833                            }
6834                         }
6835                         if (!disabledPackageAvailable) {
6836                             mSettings.removeDisabledSystemPackageLPw(disabledChildPackageName);
6837                         }
6838                    }
6839                }
6840            }
6841        }
6842
6843        boolean updatedPkgBetter = false;
6844        // First check if this is a system package that may involve an update
6845        if (updatedPkg != null && (policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) {
6846            // If new package is not located in "/system/priv-app" (e.g. due to an OTA),
6847            // it needs to drop FLAG_PRIVILEGED.
6848            if (locationIsPrivileged(scanFile)) {
6849                updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
6850            } else {
6851                updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
6852            }
6853
6854            if (ps != null && !ps.codePath.equals(scanFile)) {
6855                // The path has changed from what was last scanned...  check the
6856                // version of the new path against what we have stored to determine
6857                // what to do.
6858                if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath);
6859                if (pkg.mVersionCode <= ps.versionCode) {
6860                    // The system package has been updated and the code path does not match
6861                    // Ignore entry. Skip it.
6862                    if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile
6863                            + " ignored: updated version " + ps.versionCode
6864                            + " better than this " + pkg.mVersionCode);
6865                    if (!updatedPkg.codePath.equals(scanFile)) {
6866                        Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg "
6867                                + ps.name + " changing from " + updatedPkg.codePathString
6868                                + " to " + scanFile);
6869                        updatedPkg.codePath = scanFile;
6870                        updatedPkg.codePathString = scanFile.toString();
6871                        updatedPkg.resourcePath = scanFile;
6872                        updatedPkg.resourcePathString = scanFile.toString();
6873                    }
6874                    updatedPkg.pkg = pkg;
6875                    updatedPkg.versionCode = pkg.mVersionCode;
6876
6877                    // Update the disabled system child packages to point to the package too.
6878                    final int childCount = updatedPkg.childPackageNames != null
6879                            ? updatedPkg.childPackageNames.size() : 0;
6880                    for (int i = 0; i < childCount; i++) {
6881                        String childPackageName = updatedPkg.childPackageNames.get(i);
6882                        PackageSetting updatedChildPkg = mSettings.getDisabledSystemPkgLPr(
6883                                childPackageName);
6884                        if (updatedChildPkg != null) {
6885                            updatedChildPkg.pkg = pkg;
6886                            updatedChildPkg.versionCode = pkg.mVersionCode;
6887                        }
6888                    }
6889
6890                    throw new PackageManagerException(Log.WARN, "Package " + ps.name + " at "
6891                            + scanFile + " ignored: updated version " + ps.versionCode
6892                            + " better than this " + pkg.mVersionCode);
6893                } else {
6894                    // The current app on the system partition is better than
6895                    // what we have updated to on the data partition; switch
6896                    // back to the system partition version.
6897                    // At this point, its safely assumed that package installation for
6898                    // apps in system partition will go through. If not there won't be a working
6899                    // version of the app
6900                    // writer
6901                    synchronized (mPackages) {
6902                        // Just remove the loaded entries from package lists.
6903                        mPackages.remove(ps.name);
6904                    }
6905
6906                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
6907                            + " reverting from " + ps.codePathString
6908                            + ": new version " + pkg.mVersionCode
6909                            + " better than installed " + ps.versionCode);
6910
6911                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
6912                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
6913                    synchronized (mInstallLock) {
6914                        args.cleanUpResourcesLI();
6915                    }
6916                    synchronized (mPackages) {
6917                        mSettings.enableSystemPackageLPw(ps.name);
6918                    }
6919                    updatedPkgBetter = true;
6920                }
6921            }
6922        }
6923
6924        if (updatedPkg != null) {
6925            // An updated system app will not have the PARSE_IS_SYSTEM flag set
6926            // initially
6927            policyFlags |= PackageParser.PARSE_IS_SYSTEM;
6928
6929            // An updated privileged app will not have the PARSE_IS_PRIVILEGED
6930            // flag set initially
6931            if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
6932                policyFlags |= PackageParser.PARSE_IS_PRIVILEGED;
6933            }
6934        }
6935
6936        // Verify certificates against what was last scanned
6937        collectCertificatesLI(ps, pkg, scanFile, policyFlags);
6938
6939        /*
6940         * A new system app appeared, but we already had a non-system one of the
6941         * same name installed earlier.
6942         */
6943        boolean shouldHideSystemApp = false;
6944        if (updatedPkg == null && ps != null
6945                && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) {
6946            /*
6947             * Check to make sure the signatures match first. If they don't,
6948             * wipe the installed application and its data.
6949             */
6950            if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures)
6951                    != PackageManager.SIGNATURE_MATCH) {
6952                logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but"
6953                        + " signatures don't match existing userdata copy; removing");
6954                try (PackageFreezer freezer = freezePackage(pkg.packageName,
6955                        "scanPackageInternalLI")) {
6956                    deletePackageLIF(pkg.packageName, null, true, null, 0, null, false, null);
6957                }
6958                ps = null;
6959            } else {
6960                /*
6961                 * If the newly-added system app is an older version than the
6962                 * already installed version, hide it. It will be scanned later
6963                 * and re-added like an update.
6964                 */
6965                if (pkg.mVersionCode <= ps.versionCode) {
6966                    shouldHideSystemApp = true;
6967                    logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile
6968                            + " but new version " + pkg.mVersionCode + " better than installed "
6969                            + ps.versionCode + "; hiding system");
6970                } else {
6971                    /*
6972                     * The newly found system app is a newer version that the
6973                     * one previously installed. Simply remove the
6974                     * already-installed application and replace it with our own
6975                     * while keeping the application data.
6976                     */
6977                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
6978                            + " reverting from " + ps.codePathString + ": new version "
6979                            + pkg.mVersionCode + " better than installed " + ps.versionCode);
6980                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
6981                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
6982                    synchronized (mInstallLock) {
6983                        args.cleanUpResourcesLI();
6984                    }
6985                }
6986            }
6987        }
6988
6989        // The apk is forward locked (not public) if its code and resources
6990        // are kept in different files. (except for app in either system or
6991        // vendor path).
6992        // TODO grab this value from PackageSettings
6993        if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
6994            if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
6995                policyFlags |= PackageParser.PARSE_FORWARD_LOCK;
6996            }
6997        }
6998
6999        // TODO: extend to support forward-locked splits
7000        String resourcePath = null;
7001        String baseResourcePath = null;
7002        if ((policyFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) {
7003            if (ps != null && ps.resourcePathString != null) {
7004                resourcePath = ps.resourcePathString;
7005                baseResourcePath = ps.resourcePathString;
7006            } else {
7007                // Should not happen at all. Just log an error.
7008                Slog.e(TAG, "Resource path not set for package " + pkg.packageName);
7009            }
7010        } else {
7011            resourcePath = pkg.codePath;
7012            baseResourcePath = pkg.baseCodePath;
7013        }
7014
7015        // Set application objects path explicitly.
7016        pkg.setApplicationVolumeUuid(pkg.volumeUuid);
7017        pkg.setApplicationInfoCodePath(pkg.codePath);
7018        pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
7019        pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
7020        pkg.setApplicationInfoResourcePath(resourcePath);
7021        pkg.setApplicationInfoBaseResourcePath(baseResourcePath);
7022        pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
7023
7024        // Note that we invoke the following method only if we are about to unpack an application
7025        PackageParser.Package scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags
7026                | SCAN_UPDATE_SIGNATURE, currentTime, user);
7027
7028        /*
7029         * If the system app should be overridden by a previously installed
7030         * data, hide the system app now and let the /data/app scan pick it up
7031         * again.
7032         */
7033        if (shouldHideSystemApp) {
7034            synchronized (mPackages) {
7035                mSettings.disableSystemPackageLPw(pkg.packageName, true);
7036            }
7037        }
7038
7039        return scannedPkg;
7040    }
7041
7042    private static String fixProcessName(String defProcessName,
7043            String processName, int uid) {
7044        if (processName == null) {
7045            return defProcessName;
7046        }
7047        return processName;
7048    }
7049
7050    private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg)
7051            throws PackageManagerException {
7052        if (pkgSetting.signatures.mSignatures != null) {
7053            // Already existing package. Make sure signatures match
7054            boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures)
7055                    == PackageManager.SIGNATURE_MATCH;
7056            if (!match) {
7057                match = compareSignaturesCompat(pkgSetting.signatures, pkg)
7058                        == PackageManager.SIGNATURE_MATCH;
7059            }
7060            if (!match) {
7061                match = compareSignaturesRecover(pkgSetting.signatures, pkg)
7062                        == PackageManager.SIGNATURE_MATCH;
7063            }
7064            if (!match) {
7065                throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
7066                        + pkg.packageName + " signatures do not match the "
7067                        + "previously installed version; ignoring!");
7068            }
7069        }
7070
7071        // Check for shared user signatures
7072        if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
7073            // Already existing package. Make sure signatures match
7074            boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
7075                    pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
7076            if (!match) {
7077                match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg)
7078                        == PackageManager.SIGNATURE_MATCH;
7079            }
7080            if (!match) {
7081                match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg)
7082                        == PackageManager.SIGNATURE_MATCH;
7083            }
7084            if (!match) {
7085                throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
7086                        "Package " + pkg.packageName
7087                        + " has no signatures that match those in shared user "
7088                        + pkgSetting.sharedUser.name + "; ignoring!");
7089            }
7090        }
7091    }
7092
7093    /**
7094     * Enforces that only the system UID or root's UID can call a method exposed
7095     * via Binder.
7096     *
7097     * @param message used as message if SecurityException is thrown
7098     * @throws SecurityException if the caller is not system or root
7099     */
7100    private static final void enforceSystemOrRoot(String message) {
7101        final int uid = Binder.getCallingUid();
7102        if (uid != Process.SYSTEM_UID && uid != 0) {
7103            throw new SecurityException(message);
7104        }
7105    }
7106
7107    @Override
7108    public void performFstrimIfNeeded() {
7109        enforceSystemOrRoot("Only the system can request fstrim");
7110
7111        // Before everything else, see whether we need to fstrim.
7112        try {
7113            IMountService ms = PackageHelper.getMountService();
7114            if (ms != null) {
7115                final boolean isUpgrade = isUpgrade();
7116                boolean doTrim = isUpgrade;
7117                if (doTrim) {
7118                    Slog.w(TAG, "Running disk maintenance immediately due to system update");
7119                } else {
7120                    final long interval = android.provider.Settings.Global.getLong(
7121                            mContext.getContentResolver(),
7122                            android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL,
7123                            DEFAULT_MANDATORY_FSTRIM_INTERVAL);
7124                    if (interval > 0) {
7125                        final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance();
7126                        if (timeSinceLast > interval) {
7127                            doTrim = true;
7128                            Slog.w(TAG, "No disk maintenance in " + timeSinceLast
7129                                    + "; running immediately");
7130                        }
7131                    }
7132                }
7133                if (doTrim) {
7134                    if (!isFirstBoot()) {
7135                        try {
7136                            ActivityManagerNative.getDefault().showBootMessage(
7137                                    mContext.getResources().getString(
7138                                            R.string.android_upgrading_fstrim), true);
7139                        } catch (RemoteException e) {
7140                        }
7141                    }
7142                    ms.runMaintenance();
7143                }
7144            } else {
7145                Slog.e(TAG, "Mount service unavailable!");
7146            }
7147        } catch (RemoteException e) {
7148            // Can't happen; MountService is local
7149        }
7150    }
7151
7152    @Override
7153    public void updatePackagesIfNeeded() {
7154        enforceSystemOrRoot("Only the system can request package update");
7155
7156        // We need to re-extract after an OTA.
7157        boolean causeUpgrade = isUpgrade();
7158
7159        // First boot or factory reset.
7160        // Note: we also handle devices that are upgrading to N right now as if it is their
7161        //       first boot, as they do not have profile data.
7162        boolean causeFirstBoot = isFirstBoot() || mIsPreNUpgrade;
7163
7164        // We need to re-extract after a pruned cache, as AoT-ed files will be out of date.
7165        boolean causePrunedCache = VMRuntime.didPruneDalvikCache();
7166
7167        if (!causeUpgrade && !causeFirstBoot && !causePrunedCache) {
7168            return;
7169        }
7170
7171        List<PackageParser.Package> pkgs;
7172        synchronized (mPackages) {
7173            pkgs = PackageManagerServiceUtils.getPackagesForDexopt(mPackages.values(), this);
7174        }
7175
7176        int curr = 0;
7177        int total = pkgs.size();
7178        for (PackageParser.Package pkg : pkgs) {
7179            curr++;
7180
7181            if (!PackageDexOptimizer.canOptimizePackage(pkg)) {
7182                if (DEBUG_DEXOPT) {
7183                    Log.i(TAG, "Skipping update of of non-optimizable app " + pkg.packageName);
7184                }
7185                continue;
7186            }
7187
7188            if (DEBUG_DEXOPT) {
7189                Log.i(TAG, "Extracting app " + curr + " of " + total + ": " + pkg.packageName);
7190            }
7191
7192            if (!isFirstBoot()) {
7193                try {
7194                    ActivityManagerNative.getDefault().showBootMessage(
7195                            mContext.getResources().getString(R.string.android_upgrading_apk,
7196                                    curr, total), true);
7197                } catch (RemoteException e) {
7198                }
7199            }
7200
7201            performDexOpt(pkg.packageName,
7202                    null /* instructionSet */,
7203                    true /* checkProfiles */,
7204                    causeFirstBoot ? REASON_FIRST_BOOT : REASON_BOOT,
7205                    false /* force */);
7206        }
7207    }
7208
7209    @Override
7210    public void notifyPackageUse(String packageName, int reason) {
7211        synchronized (mPackages) {
7212            PackageParser.Package p = mPackages.get(packageName);
7213            if (p == null) {
7214                return;
7215            }
7216            p.mLastPackageUsageTimeInMills[reason] = System.currentTimeMillis();
7217        }
7218    }
7219
7220    // TODO: this is not used nor needed. Delete it.
7221    @Override
7222    public boolean performDexOptIfNeeded(String packageName, String instructionSet) {
7223        return performDexOptTraced(packageName, instructionSet, false /* checkProfiles */,
7224                getFullCompilerFilter(), false /* force */);
7225    }
7226
7227    @Override
7228    public boolean performDexOpt(String packageName, String instructionSet,
7229            boolean checkProfiles, int compileReason, boolean force) {
7230        return performDexOptTraced(packageName, instructionSet, checkProfiles,
7231                getCompilerFilterForReason(compileReason), force);
7232    }
7233
7234    @Override
7235    public boolean performDexOptMode(String packageName, String instructionSet,
7236            boolean checkProfiles, String targetCompilerFilter, boolean force) {
7237        return performDexOptTraced(packageName, instructionSet, checkProfiles,
7238                targetCompilerFilter, force);
7239    }
7240
7241    private boolean performDexOptTraced(String packageName, String instructionSet,
7242                boolean checkProfiles, String targetCompilerFilter, boolean force) {
7243        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
7244        try {
7245            return performDexOptInternal(packageName, instructionSet, checkProfiles,
7246                    targetCompilerFilter, force);
7247        } finally {
7248            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7249        }
7250    }
7251
7252    // Run dexopt on a given package. Returns true if dexopt did not fail, i.e.
7253    // if the package can now be considered up to date for the given filter.
7254    private boolean performDexOptInternal(String packageName, String instructionSet,
7255                boolean checkProfiles, String targetCompilerFilter, boolean force) {
7256        PackageParser.Package p;
7257        final String targetInstructionSet;
7258        synchronized (mPackages) {
7259            p = mPackages.get(packageName);
7260            if (p == null) {
7261                return false;
7262            }
7263            mPackageUsage.write(false);
7264
7265            targetInstructionSet = instructionSet != null ? instructionSet :
7266                    getPrimaryInstructionSet(p.applicationInfo);
7267        }
7268        long callingId = Binder.clearCallingIdentity();
7269        try {
7270            synchronized (mInstallLock) {
7271                final String[] instructionSets = new String[] { targetInstructionSet };
7272                int result = performDexOptInternalWithDependenciesLI(p, instructionSets,
7273                        checkProfiles, targetCompilerFilter, force);
7274                return result != PackageDexOptimizer.DEX_OPT_FAILED;
7275            }
7276        } finally {
7277            Binder.restoreCallingIdentity(callingId);
7278        }
7279    }
7280
7281    public ArraySet<String> getOptimizablePackages() {
7282        ArraySet<String> pkgs = new ArraySet<String>();
7283        synchronized (mPackages) {
7284            for (PackageParser.Package p : mPackages.values()) {
7285                if (PackageDexOptimizer.canOptimizePackage(p)) {
7286                    pkgs.add(p.packageName);
7287                }
7288            }
7289        }
7290        return pkgs;
7291    }
7292
7293    private int performDexOptInternalWithDependenciesLI(PackageParser.Package p,
7294            String instructionSets[], boolean checkProfiles, String targetCompilerFilter,
7295            boolean force) {
7296        // Select the dex optimizer based on the force parameter.
7297        // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to
7298        //       allocate an object here.
7299        PackageDexOptimizer pdo = force
7300                ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer)
7301                : mPackageDexOptimizer;
7302
7303        // Optimize all dependencies first. Note: we ignore the return value and march on
7304        // on errors.
7305        Collection<PackageParser.Package> deps = findSharedNonSystemLibraries(p);
7306        if (!deps.isEmpty()) {
7307            for (PackageParser.Package depPackage : deps) {
7308                // TODO: Analyze and investigate if we (should) profile libraries.
7309                // Currently this will do a full compilation of the library by default.
7310                pdo.performDexOpt(depPackage, instructionSets, false /* checkProfiles */,
7311                        getCompilerFilterForReason(REASON_NON_SYSTEM_LIBRARY));
7312            }
7313        }
7314
7315        return pdo.performDexOpt(p, instructionSets, checkProfiles, targetCompilerFilter);
7316    }
7317
7318    Collection<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package p) {
7319        if (p.usesLibraries != null || p.usesOptionalLibraries != null) {
7320            ArrayList<PackageParser.Package> retValue = new ArrayList<>();
7321            Set<String> collectedNames = new HashSet<>();
7322            findSharedNonSystemLibrariesRecursive(p, retValue, collectedNames);
7323
7324            retValue.remove(p);
7325
7326            return retValue;
7327        } else {
7328            return Collections.emptyList();
7329        }
7330    }
7331
7332    private void findSharedNonSystemLibrariesRecursive(PackageParser.Package p,
7333            Collection<PackageParser.Package> collected, Set<String> collectedNames) {
7334        if (!collectedNames.contains(p.packageName)) {
7335            collectedNames.add(p.packageName);
7336            collected.add(p);
7337
7338            if (p.usesLibraries != null) {
7339                findSharedNonSystemLibrariesRecursive(p.usesLibraries, collected, collectedNames);
7340            }
7341            if (p.usesOptionalLibraries != null) {
7342                findSharedNonSystemLibrariesRecursive(p.usesOptionalLibraries, collected,
7343                        collectedNames);
7344            }
7345        }
7346    }
7347
7348    private void findSharedNonSystemLibrariesRecursive(Collection<String> libs,
7349            Collection<PackageParser.Package> collected, Set<String> collectedNames) {
7350        for (String libName : libs) {
7351            PackageParser.Package libPkg = findSharedNonSystemLibrary(libName);
7352            if (libPkg != null) {
7353                findSharedNonSystemLibrariesRecursive(libPkg, collected, collectedNames);
7354            }
7355        }
7356    }
7357
7358    private PackageParser.Package findSharedNonSystemLibrary(String libName) {
7359        synchronized (mPackages) {
7360            PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName);
7361            if (lib != null && lib.apk != null) {
7362                return mPackages.get(lib.apk);
7363            }
7364        }
7365        return null;
7366    }
7367
7368    public void shutdown() {
7369        mPackageUsage.write(true);
7370    }
7371
7372    @Override
7373    public void forceDexOpt(String packageName) {
7374        enforceSystemOrRoot("forceDexOpt");
7375
7376        PackageParser.Package pkg;
7377        synchronized (mPackages) {
7378            pkg = mPackages.get(packageName);
7379            if (pkg == null) {
7380                throw new IllegalArgumentException("Unknown package: " + packageName);
7381            }
7382        }
7383
7384        synchronized (mInstallLock) {
7385            final String[] instructionSets = new String[] {
7386                    getPrimaryInstructionSet(pkg.applicationInfo) };
7387
7388            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
7389
7390            // Whoever is calling forceDexOpt wants a fully compiled package.
7391            // Don't use profiles since that may cause compilation to be skipped.
7392            final int res = performDexOptInternalWithDependenciesLI(pkg, instructionSets,
7393                    false /* checkProfiles */, getCompilerFilterForReason(REASON_FORCED_DEXOPT),
7394                    true /* force */);
7395
7396            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7397            if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) {
7398                throw new IllegalStateException("Failed to dexopt: " + res);
7399            }
7400        }
7401    }
7402
7403    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
7404        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
7405            Slog.w(TAG, "Unable to update from " + oldPkg.name
7406                    + " to " + newPkg.packageName
7407                    + ": old package not in system partition");
7408            return false;
7409        } else if (mPackages.get(oldPkg.name) != null) {
7410            Slog.w(TAG, "Unable to update from " + oldPkg.name
7411                    + " to " + newPkg.packageName
7412                    + ": old package still exists");
7413            return false;
7414        }
7415        return true;
7416    }
7417
7418    void removeCodePathLI(File codePath) {
7419        if (codePath.isDirectory()) {
7420            try {
7421                mInstaller.rmPackageDir(codePath.getAbsolutePath());
7422            } catch (InstallerException e) {
7423                Slog.w(TAG, "Failed to remove code path", e);
7424            }
7425        } else {
7426            codePath.delete();
7427        }
7428    }
7429
7430    private int[] resolveUserIds(int userId) {
7431        return (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() : new int[] { userId };
7432    }
7433
7434    private void clearAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
7435        if (pkg == null) {
7436            Slog.wtf(TAG, "Package was null!", new Throwable());
7437            return;
7438        }
7439        clearAppDataLeafLIF(pkg, userId, flags);
7440        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7441        for (int i = 0; i < childCount; i++) {
7442            clearAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
7443        }
7444    }
7445
7446    private void clearAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
7447        final PackageSetting ps;
7448        synchronized (mPackages) {
7449            ps = mSettings.mPackages.get(pkg.packageName);
7450        }
7451        for (int realUserId : resolveUserIds(userId)) {
7452            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
7453            try {
7454                mInstaller.clearAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
7455                        ceDataInode);
7456            } catch (InstallerException e) {
7457                Slog.w(TAG, String.valueOf(e));
7458            }
7459        }
7460    }
7461
7462    private void destroyAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
7463        if (pkg == null) {
7464            Slog.wtf(TAG, "Package was null!", new Throwable());
7465            return;
7466        }
7467        destroyAppDataLeafLIF(pkg, userId, flags);
7468        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7469        for (int i = 0; i < childCount; i++) {
7470            destroyAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
7471        }
7472    }
7473
7474    private void destroyAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
7475        final PackageSetting ps;
7476        synchronized (mPackages) {
7477            ps = mSettings.mPackages.get(pkg.packageName);
7478        }
7479        for (int realUserId : resolveUserIds(userId)) {
7480            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
7481            try {
7482                mInstaller.destroyAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
7483                        ceDataInode);
7484            } catch (InstallerException e) {
7485                Slog.w(TAG, String.valueOf(e));
7486            }
7487        }
7488    }
7489
7490    private void destroyAppProfilesLIF(PackageParser.Package pkg) {
7491        if (pkg == null) {
7492            Slog.wtf(TAG, "Package was null!", new Throwable());
7493            return;
7494        }
7495        destroyAppProfilesLeafLIF(pkg);
7496        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7497        for (int i = 0; i < childCount; i++) {
7498            destroyAppProfilesLeafLIF(pkg.childPackages.get(i));
7499        }
7500    }
7501
7502    private void destroyAppProfilesLeafLIF(PackageParser.Package pkg) {
7503        try {
7504            mInstaller.destroyAppProfiles(pkg.packageName);
7505        } catch (InstallerException e) {
7506            Slog.w(TAG, String.valueOf(e));
7507        }
7508    }
7509
7510    private void clearAppProfilesLIF(PackageParser.Package pkg) {
7511        if (pkg == null) {
7512            Slog.wtf(TAG, "Package was null!", new Throwable());
7513            return;
7514        }
7515        clearAppProfilesLeafLIF(pkg);
7516        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7517        for (int i = 0; i < childCount; i++) {
7518            clearAppProfilesLeafLIF(pkg.childPackages.get(i));
7519        }
7520    }
7521
7522    private void clearAppProfilesLeafLIF(PackageParser.Package pkg) {
7523        try {
7524            mInstaller.clearAppProfiles(pkg.packageName);
7525        } catch (InstallerException e) {
7526            Slog.w(TAG, String.valueOf(e));
7527        }
7528    }
7529
7530    private void setInstallAndUpdateTime(PackageParser.Package pkg, long firstInstallTime,
7531            long lastUpdateTime) {
7532        // Set parent install/update time
7533        PackageSetting ps = (PackageSetting) pkg.mExtras;
7534        if (ps != null) {
7535            ps.firstInstallTime = firstInstallTime;
7536            ps.lastUpdateTime = lastUpdateTime;
7537        }
7538        // Set children install/update time
7539        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7540        for (int i = 0; i < childCount; i++) {
7541            PackageParser.Package childPkg = pkg.childPackages.get(i);
7542            ps = (PackageSetting) childPkg.mExtras;
7543            if (ps != null) {
7544                ps.firstInstallTime = firstInstallTime;
7545                ps.lastUpdateTime = lastUpdateTime;
7546            }
7547        }
7548    }
7549
7550    private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file,
7551            PackageParser.Package changingLib) {
7552        if (file.path != null) {
7553            usesLibraryFiles.add(file.path);
7554            return;
7555        }
7556        PackageParser.Package p = mPackages.get(file.apk);
7557        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
7558            // If we are doing this while in the middle of updating a library apk,
7559            // then we need to make sure to use that new apk for determining the
7560            // dependencies here.  (We haven't yet finished committing the new apk
7561            // to the package manager state.)
7562            if (p == null || p.packageName.equals(changingLib.packageName)) {
7563                p = changingLib;
7564            }
7565        }
7566        if (p != null) {
7567            usesLibraryFiles.addAll(p.getAllCodePaths());
7568        }
7569    }
7570
7571    private void updateSharedLibrariesLPw(PackageParser.Package pkg,
7572            PackageParser.Package changingLib) throws PackageManagerException {
7573        if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) {
7574            final ArraySet<String> usesLibraryFiles = new ArraySet<>();
7575            int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0;
7576            for (int i=0; i<N; i++) {
7577                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i));
7578                if (file == null) {
7579                    throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
7580                            "Package " + pkg.packageName + " requires unavailable shared library "
7581                            + pkg.usesLibraries.get(i) + "; failing!");
7582                }
7583                addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
7584            }
7585            N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0;
7586            for (int i=0; i<N; i++) {
7587                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i));
7588                if (file == null) {
7589                    Slog.w(TAG, "Package " + pkg.packageName
7590                            + " desires unavailable shared library "
7591                            + pkg.usesOptionalLibraries.get(i) + "; ignoring!");
7592                } else {
7593                    addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
7594                }
7595            }
7596            N = usesLibraryFiles.size();
7597            if (N > 0) {
7598                pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]);
7599            } else {
7600                pkg.usesLibraryFiles = null;
7601            }
7602        }
7603    }
7604
7605    private static boolean hasString(List<String> list, List<String> which) {
7606        if (list == null) {
7607            return false;
7608        }
7609        for (int i=list.size()-1; i>=0; i--) {
7610            for (int j=which.size()-1; j>=0; j--) {
7611                if (which.get(j).equals(list.get(i))) {
7612                    return true;
7613                }
7614            }
7615        }
7616        return false;
7617    }
7618
7619    private void updateAllSharedLibrariesLPw() {
7620        for (PackageParser.Package pkg : mPackages.values()) {
7621            try {
7622                updateSharedLibrariesLPw(pkg, null);
7623            } catch (PackageManagerException e) {
7624                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
7625            }
7626        }
7627    }
7628
7629    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
7630            PackageParser.Package changingPkg) {
7631        ArrayList<PackageParser.Package> res = null;
7632        for (PackageParser.Package pkg : mPackages.values()) {
7633            if (hasString(pkg.usesLibraries, changingPkg.libraryNames)
7634                    || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) {
7635                if (res == null) {
7636                    res = new ArrayList<PackageParser.Package>();
7637                }
7638                res.add(pkg);
7639                try {
7640                    updateSharedLibrariesLPw(pkg, changingPkg);
7641                } catch (PackageManagerException e) {
7642                    Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
7643                }
7644            }
7645        }
7646        return res;
7647    }
7648
7649    /**
7650     * Derive the value of the {@code cpuAbiOverride} based on the provided
7651     * value and an optional stored value from the package settings.
7652     */
7653    private static String deriveAbiOverride(String abiOverride, PackageSetting settings) {
7654        String cpuAbiOverride = null;
7655
7656        if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) {
7657            cpuAbiOverride = null;
7658        } else if (abiOverride != null) {
7659            cpuAbiOverride = abiOverride;
7660        } else if (settings != null) {
7661            cpuAbiOverride = settings.cpuAbiOverrideString;
7662        }
7663
7664        return cpuAbiOverride;
7665    }
7666
7667    private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg,
7668            final int policyFlags, int scanFlags, long currentTime, UserHandle user)
7669                    throws PackageManagerException {
7670        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage");
7671        // If the package has children and this is the first dive in the function
7672        // we recursively scan the package with the SCAN_CHECK_ONLY flag set to see
7673        // whether all packages (parent and children) would be successfully scanned
7674        // before the actual scan since scanning mutates internal state and we want
7675        // to atomically install the package and its children.
7676        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
7677            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
7678                scanFlags |= SCAN_CHECK_ONLY;
7679            }
7680        } else {
7681            scanFlags &= ~SCAN_CHECK_ONLY;
7682        }
7683
7684        final PackageParser.Package scannedPkg;
7685        try {
7686            // Scan the parent
7687            scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags, currentTime, user);
7688            // Scan the children
7689            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7690            for (int i = 0; i < childCount; i++) {
7691                PackageParser.Package childPkg = pkg.childPackages.get(i);
7692                scanPackageLI(childPkg, policyFlags,
7693                        scanFlags, currentTime, user);
7694            }
7695        } finally {
7696            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7697        }
7698
7699        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
7700            return scanPackageTracedLI(pkg, policyFlags, scanFlags, currentTime, user);
7701        }
7702
7703        return scannedPkg;
7704    }
7705
7706    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, final int policyFlags,
7707            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
7708        boolean success = false;
7709        try {
7710            final PackageParser.Package res = scanPackageDirtyLI(pkg, policyFlags, scanFlags,
7711                    currentTime, user);
7712            success = true;
7713            return res;
7714        } finally {
7715            if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
7716                // DELETE_DATA_ON_FAILURES is only used by frozen paths
7717                destroyAppDataLIF(pkg, UserHandle.USER_ALL,
7718                        StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
7719                destroyAppProfilesLIF(pkg);
7720            }
7721        }
7722    }
7723
7724    /**
7725     * Returns {@code true} if the given file contains code. Otherwise {@code false}.
7726     */
7727    private static boolean apkHasCode(String fileName) {
7728        StrictJarFile jarFile = null;
7729        try {
7730            jarFile = new StrictJarFile(fileName,
7731                    false /*verify*/, false /*signatureSchemeRollbackProtectionsEnforced*/);
7732            return jarFile.findEntry("classes.dex") != null;
7733        } catch (IOException ignore) {
7734        } finally {
7735            try {
7736                jarFile.close();
7737            } catch (IOException ignore) {}
7738        }
7739        return false;
7740    }
7741
7742    /**
7743     * Enforces code policy for the package. This ensures that if an APK has
7744     * declared hasCode="true" in its manifest that the APK actually contains
7745     * code.
7746     *
7747     * @throws PackageManagerException If bytecode could not be found when it should exist
7748     */
7749    private static void enforceCodePolicy(PackageParser.Package pkg)
7750            throws PackageManagerException {
7751        final boolean shouldHaveCode =
7752                (pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) != 0;
7753        if (shouldHaveCode && !apkHasCode(pkg.baseCodePath)) {
7754            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
7755                    "Package " + pkg.baseCodePath + " code is missing");
7756        }
7757
7758        if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
7759            for (int i = 0; i < pkg.splitCodePaths.length; i++) {
7760                final boolean splitShouldHaveCode =
7761                        (pkg.splitFlags[i] & ApplicationInfo.FLAG_HAS_CODE) != 0;
7762                if (splitShouldHaveCode && !apkHasCode(pkg.splitCodePaths[i])) {
7763                    throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
7764                            "Package " + pkg.splitCodePaths[i] + " code is missing");
7765                }
7766            }
7767        }
7768    }
7769
7770    private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg,
7771            final int policyFlags, final int scanFlags, long currentTime, UserHandle user)
7772            throws PackageManagerException {
7773        final File scanFile = new File(pkg.codePath);
7774        if (pkg.applicationInfo.getCodePath() == null ||
7775                pkg.applicationInfo.getResourcePath() == null) {
7776            // Bail out. The resource and code paths haven't been set.
7777            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
7778                    "Code and resource paths haven't been set correctly");
7779        }
7780
7781        // Apply policy
7782        if ((policyFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
7783            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
7784            if (pkg.applicationInfo.isDirectBootAware()) {
7785                // we're direct boot aware; set for all components
7786                for (PackageParser.Service s : pkg.services) {
7787                    s.info.encryptionAware = s.info.directBootAware = true;
7788                }
7789                for (PackageParser.Provider p : pkg.providers) {
7790                    p.info.encryptionAware = p.info.directBootAware = true;
7791                }
7792                for (PackageParser.Activity a : pkg.activities) {
7793                    a.info.encryptionAware = a.info.directBootAware = true;
7794                }
7795                for (PackageParser.Activity r : pkg.receivers) {
7796                    r.info.encryptionAware = r.info.directBootAware = true;
7797                }
7798            }
7799        } else {
7800            // Only allow system apps to be flagged as core apps.
7801            pkg.coreApp = false;
7802            // clear flags not applicable to regular apps
7803            pkg.applicationInfo.privateFlags &=
7804                    ~ApplicationInfo.PRIVATE_FLAG_DEFAULT_TO_DEVICE_PROTECTED_STORAGE;
7805            pkg.applicationInfo.privateFlags &=
7806                    ~ApplicationInfo.PRIVATE_FLAG_DIRECT_BOOT_AWARE;
7807        }
7808        pkg.mTrustedOverlay = (policyFlags&PackageParser.PARSE_TRUSTED_OVERLAY) != 0;
7809
7810        if ((policyFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) {
7811            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
7812        }
7813
7814        if ((policyFlags & PackageParser.PARSE_ENFORCE_CODE) != 0) {
7815            enforceCodePolicy(pkg);
7816        }
7817
7818        if (mCustomResolverComponentName != null &&
7819                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
7820            setUpCustomResolverActivity(pkg);
7821        }
7822
7823        if (pkg.packageName.equals("android")) {
7824            synchronized (mPackages) {
7825                if (mAndroidApplication != null) {
7826                    Slog.w(TAG, "*************************************************");
7827                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
7828                    Slog.w(TAG, " file=" + scanFile);
7829                    Slog.w(TAG, "*************************************************");
7830                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
7831                            "Core android package being redefined.  Skipping.");
7832                }
7833
7834                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
7835                    // Set up information for our fall-back user intent resolution activity.
7836                    mPlatformPackage = pkg;
7837                    pkg.mVersionCode = mSdkVersion;
7838                    mAndroidApplication = pkg.applicationInfo;
7839
7840                    if (!mResolverReplaced) {
7841                        mResolveActivity.applicationInfo = mAndroidApplication;
7842                        mResolveActivity.name = ResolverActivity.class.getName();
7843                        mResolveActivity.packageName = mAndroidApplication.packageName;
7844                        mResolveActivity.processName = "system:ui";
7845                        mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
7846                        mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
7847                        mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
7848                        mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert;
7849                        mResolveActivity.exported = true;
7850                        mResolveActivity.enabled = true;
7851                        mResolveInfo.activityInfo = mResolveActivity;
7852                        mResolveInfo.priority = 0;
7853                        mResolveInfo.preferredOrder = 0;
7854                        mResolveInfo.match = 0;
7855                        mResolveComponentName = new ComponentName(
7856                                mAndroidApplication.packageName, mResolveActivity.name);
7857                    }
7858                }
7859            }
7860        }
7861
7862        if (DEBUG_PACKAGE_SCANNING) {
7863            if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
7864                Log.d(TAG, "Scanning package " + pkg.packageName);
7865        }
7866
7867        synchronized (mPackages) {
7868            if (mPackages.containsKey(pkg.packageName)
7869                    || mSharedLibraries.containsKey(pkg.packageName)) {
7870                throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
7871                        "Application package " + pkg.packageName
7872                                + " already installed.  Skipping duplicate.");
7873            }
7874
7875            // If we're only installing presumed-existing packages, require that the
7876            // scanned APK is both already known and at the path previously established
7877            // for it.  Previously unknown packages we pick up normally, but if we have an
7878            // a priori expectation about this package's install presence, enforce it.
7879            // With a singular exception for new system packages. When an OTA contains
7880            // a new system package, we allow the codepath to change from a system location
7881            // to the user-installed location. If we don't allow this change, any newer,
7882            // user-installed version of the application will be ignored.
7883            if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) {
7884                if (mExpectingBetter.containsKey(pkg.packageName)) {
7885                    logCriticalInfo(Log.WARN,
7886                            "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName);
7887                } else {
7888                    PackageSetting known = mSettings.peekPackageLPr(pkg.packageName);
7889                    if (known != null) {
7890                        if (DEBUG_PACKAGE_SCANNING) {
7891                            Log.d(TAG, "Examining " + pkg.codePath
7892                                    + " and requiring known paths " + known.codePathString
7893                                    + " & " + known.resourcePathString);
7894                        }
7895                        if (!pkg.applicationInfo.getCodePath().equals(known.codePathString)
7896                                || !pkg.applicationInfo.getResourcePath().equals(
7897                                known.resourcePathString)) {
7898                            throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED,
7899                                    "Application package " + pkg.packageName
7900                                            + " found at " + pkg.applicationInfo.getCodePath()
7901                                            + " but expected at " + known.codePathString
7902                                            + "; ignoring.");
7903                        }
7904                    }
7905                }
7906            }
7907        }
7908
7909        // Initialize package source and resource directories
7910        File destCodeFile = new File(pkg.applicationInfo.getCodePath());
7911        File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
7912
7913        SharedUserSetting suid = null;
7914        PackageSetting pkgSetting = null;
7915
7916        if (!isSystemApp(pkg)) {
7917            // Only system apps can use these features.
7918            pkg.mOriginalPackages = null;
7919            pkg.mRealPackage = null;
7920            pkg.mAdoptPermissions = null;
7921        }
7922
7923        // Getting the package setting may have a side-effect, so if we
7924        // are only checking if scan would succeed, stash a copy of the
7925        // old setting to restore at the end.
7926        PackageSetting nonMutatedPs = null;
7927
7928        // writer
7929        synchronized (mPackages) {
7930            if (pkg.mSharedUserId != null) {
7931                suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true);
7932                if (suid == null) {
7933                    throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
7934                            "Creating application package " + pkg.packageName
7935                            + " for shared user failed");
7936                }
7937                if (DEBUG_PACKAGE_SCANNING) {
7938                    if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
7939                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId
7940                                + "): packages=" + suid.packages);
7941                }
7942            }
7943
7944            // Check if we are renaming from an original package name.
7945            PackageSetting origPackage = null;
7946            String realName = null;
7947            if (pkg.mOriginalPackages != null) {
7948                // This package may need to be renamed to a previously
7949                // installed name.  Let's check on that...
7950                final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage);
7951                if (pkg.mOriginalPackages.contains(renamed)) {
7952                    // This package had originally been installed as the
7953                    // original name, and we have already taken care of
7954                    // transitioning to the new one.  Just update the new
7955                    // one to continue using the old name.
7956                    realName = pkg.mRealPackage;
7957                    if (!pkg.packageName.equals(renamed)) {
7958                        // Callers into this function may have already taken
7959                        // care of renaming the package; only do it here if
7960                        // it is not already done.
7961                        pkg.setPackageName(renamed);
7962                    }
7963
7964                } else {
7965                    for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
7966                        if ((origPackage = mSettings.peekPackageLPr(
7967                                pkg.mOriginalPackages.get(i))) != null) {
7968                            // We do have the package already installed under its
7969                            // original name...  should we use it?
7970                            if (!verifyPackageUpdateLPr(origPackage, pkg)) {
7971                                // New package is not compatible with original.
7972                                origPackage = null;
7973                                continue;
7974                            } else if (origPackage.sharedUser != null) {
7975                                // Make sure uid is compatible between packages.
7976                                if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
7977                                    Slog.w(TAG, "Unable to migrate data from " + origPackage.name
7978                                            + " to " + pkg.packageName + ": old uid "
7979                                            + origPackage.sharedUser.name
7980                                            + " differs from " + pkg.mSharedUserId);
7981                                    origPackage = null;
7982                                    continue;
7983                                }
7984                                // TODO: Add case when shared user id is added [b/28144775]
7985                            } else {
7986                                if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
7987                                        + pkg.packageName + " to old name " + origPackage.name);
7988                            }
7989                            break;
7990                        }
7991                    }
7992                }
7993            }
7994
7995            if (mTransferedPackages.contains(pkg.packageName)) {
7996                Slog.w(TAG, "Package " + pkg.packageName
7997                        + " was transferred to another, but its .apk remains");
7998            }
7999
8000            // See comments in nonMutatedPs declaration
8001            if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
8002                PackageSetting foundPs = mSettings.peekPackageLPr(pkg.packageName);
8003                if (foundPs != null) {
8004                    nonMutatedPs = new PackageSetting(foundPs);
8005                }
8006            }
8007
8008            // Just create the setting, don't add it yet. For already existing packages
8009            // the PkgSetting exists already and doesn't have to be created.
8010            pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile,
8011                    destResourceFile, pkg.applicationInfo.nativeLibraryRootDir,
8012                    pkg.applicationInfo.primaryCpuAbi,
8013                    pkg.applicationInfo.secondaryCpuAbi,
8014                    pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags,
8015                    user, false);
8016            if (pkgSetting == null) {
8017                throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
8018                        "Creating application package " + pkg.packageName + " failed");
8019            }
8020
8021            if (pkgSetting.origPackage != null) {
8022                // If we are first transitioning from an original package,
8023                // fix up the new package's name now.  We need to do this after
8024                // looking up the package under its new name, so getPackageLP
8025                // can take care of fiddling things correctly.
8026                pkg.setPackageName(origPackage.name);
8027
8028                // File a report about this.
8029                String msg = "New package " + pkgSetting.realName
8030                        + " renamed to replace old package " + pkgSetting.name;
8031                reportSettingsProblem(Log.WARN, msg);
8032
8033                // Make a note of it.
8034                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
8035                    mTransferedPackages.add(origPackage.name);
8036                }
8037
8038                // No longer need to retain this.
8039                pkgSetting.origPackage = null;
8040            }
8041
8042            if ((scanFlags & SCAN_CHECK_ONLY) == 0 && realName != null) {
8043                // Make a note of it.
8044                mTransferedPackages.add(pkg.packageName);
8045            }
8046
8047            if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) {
8048                pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
8049            }
8050
8051            if ((policyFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
8052                // Check all shared libraries and map to their actual file path.
8053                // We only do this here for apps not on a system dir, because those
8054                // are the only ones that can fail an install due to this.  We
8055                // will take care of the system apps by updating all of their
8056                // library paths after the scan is done.
8057                updateSharedLibrariesLPw(pkg, null);
8058            }
8059
8060            if (mFoundPolicyFile) {
8061                SELinuxMMAC.assignSeinfoValue(pkg);
8062            }
8063
8064            pkg.applicationInfo.uid = pkgSetting.appId;
8065            pkg.mExtras = pkgSetting;
8066            if (shouldCheckUpgradeKeySetLP(pkgSetting, scanFlags)) {
8067                if (checkUpgradeKeySetLP(pkgSetting, pkg)) {
8068                    // We just determined the app is signed correctly, so bring
8069                    // over the latest parsed certs.
8070                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
8071                } else {
8072                    if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
8073                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
8074                                "Package " + pkg.packageName + " upgrade keys do not match the "
8075                                + "previously installed version");
8076                    } else {
8077                        pkgSetting.signatures.mSignatures = pkg.mSignatures;
8078                        String msg = "System package " + pkg.packageName
8079                            + " signature changed; retaining data.";
8080                        reportSettingsProblem(Log.WARN, msg);
8081                    }
8082                }
8083            } else {
8084                try {
8085                    verifySignaturesLP(pkgSetting, pkg);
8086                    // We just determined the app is signed correctly, so bring
8087                    // over the latest parsed certs.
8088                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
8089                } catch (PackageManagerException e) {
8090                    if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
8091                        throw e;
8092                    }
8093                    // The signature has changed, but this package is in the system
8094                    // image...  let's recover!
8095                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
8096                    // However...  if this package is part of a shared user, but it
8097                    // doesn't match the signature of the shared user, let's fail.
8098                    // What this means is that you can't change the signatures
8099                    // associated with an overall shared user, which doesn't seem all
8100                    // that unreasonable.
8101                    if (pkgSetting.sharedUser != null) {
8102                        if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
8103                                              pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
8104                            throw new PackageManagerException(
8105                                    INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
8106                                            "Signature mismatch for shared user: "
8107                                            + pkgSetting.sharedUser);
8108                        }
8109                    }
8110                    // File a report about this.
8111                    String msg = "System package " + pkg.packageName
8112                        + " signature changed; retaining data.";
8113                    reportSettingsProblem(Log.WARN, msg);
8114                }
8115            }
8116            // Verify that this new package doesn't have any content providers
8117            // that conflict with existing packages.  Only do this if the
8118            // package isn't already installed, since we don't want to break
8119            // things that are installed.
8120            if ((scanFlags & SCAN_NEW_INSTALL) != 0) {
8121                final int N = pkg.providers.size();
8122                int i;
8123                for (i=0; i<N; i++) {
8124                    PackageParser.Provider p = pkg.providers.get(i);
8125                    if (p.info.authority != null) {
8126                        String names[] = p.info.authority.split(";");
8127                        for (int j = 0; j < names.length; j++) {
8128                            if (mProvidersByAuthority.containsKey(names[j])) {
8129                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
8130                                final String otherPackageName =
8131                                        ((other != null && other.getComponentName() != null) ?
8132                                                other.getComponentName().getPackageName() : "?");
8133                                throw new PackageManagerException(
8134                                        INSTALL_FAILED_CONFLICTING_PROVIDER,
8135                                                "Can't install because provider name " + names[j]
8136                                                + " (in package " + pkg.applicationInfo.packageName
8137                                                + ") is already used by " + otherPackageName);
8138                            }
8139                        }
8140                    }
8141                }
8142            }
8143
8144            if ((scanFlags & SCAN_CHECK_ONLY) == 0 && pkg.mAdoptPermissions != null) {
8145                // This package wants to adopt ownership of permissions from
8146                // another package.
8147                for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
8148                    final String origName = pkg.mAdoptPermissions.get(i);
8149                    final PackageSetting orig = mSettings.peekPackageLPr(origName);
8150                    if (orig != null) {
8151                        if (verifyPackageUpdateLPr(orig, pkg)) {
8152                            Slog.i(TAG, "Adopting permissions from " + origName + " to "
8153                                    + pkg.packageName);
8154                            mSettings.transferPermissionsLPw(origName, pkg.packageName);
8155                        }
8156                    }
8157                }
8158            }
8159        }
8160
8161        final String pkgName = pkg.packageName;
8162
8163        final long scanFileTime = scanFile.lastModified();
8164        final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0;
8165        pkg.applicationInfo.processName = fixProcessName(
8166                pkg.applicationInfo.packageName,
8167                pkg.applicationInfo.processName,
8168                pkg.applicationInfo.uid);
8169
8170        if (pkg != mPlatformPackage) {
8171            // Get all of our default paths setup
8172            pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM);
8173        }
8174
8175        final String path = scanFile.getPath();
8176        final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
8177
8178        if ((scanFlags & SCAN_NEW_INSTALL) == 0) {
8179            derivePackageAbi(pkg, scanFile, cpuAbiOverride, true /* extract libs */);
8180
8181            // Some system apps still use directory structure for native libraries
8182            // in which case we might end up not detecting abi solely based on apk
8183            // structure. Try to detect abi based on directory structure.
8184            if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() &&
8185                    pkg.applicationInfo.primaryCpuAbi == null) {
8186                setBundledAppAbisAndRoots(pkg, pkgSetting);
8187                setNativeLibraryPaths(pkg);
8188            }
8189
8190        } else {
8191            if ((scanFlags & SCAN_MOVE) != 0) {
8192                // We haven't run dex-opt for this move (since we've moved the compiled output too)
8193                // but we already have this packages package info in the PackageSetting. We just
8194                // use that and derive the native library path based on the new codepath.
8195                pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString;
8196                pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString;
8197            }
8198
8199            // Set native library paths again. For moves, the path will be updated based on the
8200            // ABIs we've determined above. For non-moves, the path will be updated based on the
8201            // ABIs we determined during compilation, but the path will depend on the final
8202            // package path (after the rename away from the stage path).
8203            setNativeLibraryPaths(pkg);
8204        }
8205
8206        // This is a special case for the "system" package, where the ABI is
8207        // dictated by the zygote configuration (and init.rc). We should keep track
8208        // of this ABI so that we can deal with "normal" applications that run under
8209        // the same UID correctly.
8210        if (mPlatformPackage == pkg) {
8211            pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
8212                    Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
8213        }
8214
8215        // If there's a mismatch between the abi-override in the package setting
8216        // and the abiOverride specified for the install. Warn about this because we
8217        // would've already compiled the app without taking the package setting into
8218        // account.
8219        if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) {
8220            if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) {
8221                Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride +
8222                        " for package " + pkg.packageName);
8223            }
8224        }
8225
8226        pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
8227        pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
8228        pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
8229
8230        // Copy the derived override back to the parsed package, so that we can
8231        // update the package settings accordingly.
8232        pkg.cpuAbiOverride = cpuAbiOverride;
8233
8234        if (DEBUG_ABI_SELECTION) {
8235            Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName
8236                    + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
8237                    + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
8238        }
8239
8240        // Push the derived path down into PackageSettings so we know what to
8241        // clean up at uninstall time.
8242        pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
8243
8244        if (DEBUG_ABI_SELECTION) {
8245            Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
8246                    " primary=" + pkg.applicationInfo.primaryCpuAbi +
8247                    " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
8248        }
8249
8250        if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
8251            // We don't do this here during boot because we can do it all
8252            // at once after scanning all existing packages.
8253            //
8254            // We also do this *before* we perform dexopt on this package, so that
8255            // we can avoid redundant dexopts, and also to make sure we've got the
8256            // code and package path correct.
8257            adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages,
8258                    pkg, true /* boot complete */);
8259        }
8260
8261        if (mFactoryTest && pkg.requestedPermissions.contains(
8262                android.Manifest.permission.FACTORY_TEST)) {
8263            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
8264        }
8265
8266        ArrayList<PackageParser.Package> clientLibPkgs = null;
8267
8268        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
8269            if (nonMutatedPs != null) {
8270                synchronized (mPackages) {
8271                    mSettings.mPackages.put(nonMutatedPs.name, nonMutatedPs);
8272                }
8273            }
8274            return pkg;
8275        }
8276
8277        // Only privileged apps and updated privileged apps can add child packages.
8278        if (pkg.childPackages != null && !pkg.childPackages.isEmpty()) {
8279            if ((policyFlags & PARSE_IS_PRIVILEGED) == 0) {
8280                throw new PackageManagerException("Only privileged apps and updated "
8281                        + "privileged apps can add child packages. Ignoring package "
8282                        + pkg.packageName);
8283            }
8284            final int childCount = pkg.childPackages.size();
8285            for (int i = 0; i < childCount; i++) {
8286                PackageParser.Package childPkg = pkg.childPackages.get(i);
8287                if (mSettings.hasOtherDisabledSystemPkgWithChildLPr(pkg.packageName,
8288                        childPkg.packageName)) {
8289                    throw new PackageManagerException("Cannot override a child package of "
8290                            + "another disabled system app. Ignoring package " + pkg.packageName);
8291                }
8292            }
8293        }
8294
8295        // writer
8296        synchronized (mPackages) {
8297            if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
8298                // Only system apps can add new shared libraries.
8299                if (pkg.libraryNames != null) {
8300                    for (int i=0; i<pkg.libraryNames.size(); i++) {
8301                        String name = pkg.libraryNames.get(i);
8302                        boolean allowed = false;
8303                        if (pkg.isUpdatedSystemApp()) {
8304                            // New library entries can only be added through the
8305                            // system image.  This is important to get rid of a lot
8306                            // of nasty edge cases: for example if we allowed a non-
8307                            // system update of the app to add a library, then uninstalling
8308                            // the update would make the library go away, and assumptions
8309                            // we made such as through app install filtering would now
8310                            // have allowed apps on the device which aren't compatible
8311                            // with it.  Better to just have the restriction here, be
8312                            // conservative, and create many fewer cases that can negatively
8313                            // impact the user experience.
8314                            final PackageSetting sysPs = mSettings
8315                                    .getDisabledSystemPkgLPr(pkg.packageName);
8316                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
8317                                for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) {
8318                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
8319                                        allowed = true;
8320                                        break;
8321                                    }
8322                                }
8323                            }
8324                        } else {
8325                            allowed = true;
8326                        }
8327                        if (allowed) {
8328                            if (!mSharedLibraries.containsKey(name)) {
8329                                mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName));
8330                            } else if (!name.equals(pkg.packageName)) {
8331                                Slog.w(TAG, "Package " + pkg.packageName + " library "
8332                                        + name + " already exists; skipping");
8333                            }
8334                        } else {
8335                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
8336                                    + name + " that is not declared on system image; skipping");
8337                        }
8338                    }
8339                    if ((scanFlags & SCAN_BOOTING) == 0) {
8340                        // If we are not booting, we need to update any applications
8341                        // that are clients of our shared library.  If we are booting,
8342                        // this will all be done once the scan is complete.
8343                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
8344                    }
8345                }
8346            }
8347        }
8348
8349        if ((scanFlags & SCAN_BOOTING) != 0) {
8350            // No apps can run during boot scan, so they don't need to be frozen
8351        } else if ((scanFlags & SCAN_DONT_KILL_APP) != 0) {
8352            // Caller asked to not kill app, so it's probably not frozen
8353        } else if ((scanFlags & SCAN_IGNORE_FROZEN) != 0) {
8354            // Caller asked us to ignore frozen check for some reason; they
8355            // probably didn't know the package name
8356        } else {
8357            // We're doing major surgery on this package, so it better be frozen
8358            // right now to keep it from launching
8359            checkPackageFrozen(pkgName);
8360        }
8361
8362        // Also need to kill any apps that are dependent on the library.
8363        if (clientLibPkgs != null) {
8364            for (int i=0; i<clientLibPkgs.size(); i++) {
8365                PackageParser.Package clientPkg = clientLibPkgs.get(i);
8366                killApplication(clientPkg.applicationInfo.packageName,
8367                        clientPkg.applicationInfo.uid, "update lib");
8368            }
8369        }
8370
8371        // Make sure we're not adding any bogus keyset info
8372        KeySetManagerService ksms = mSettings.mKeySetManagerService;
8373        ksms.assertScannedPackageValid(pkg);
8374
8375        // writer
8376        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
8377
8378        boolean createIdmapFailed = false;
8379        synchronized (mPackages) {
8380            // We don't expect installation to fail beyond this point
8381
8382            // Add the new setting to mSettings
8383            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
8384            // Add the new setting to mPackages
8385            mPackages.put(pkg.applicationInfo.packageName, pkg);
8386            // Make sure we don't accidentally delete its data.
8387            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
8388            while (iter.hasNext()) {
8389                PackageCleanItem item = iter.next();
8390                if (pkgName.equals(item.packageName)) {
8391                    iter.remove();
8392                }
8393            }
8394
8395            // Take care of first install / last update times.
8396            if (currentTime != 0) {
8397                if (pkgSetting.firstInstallTime == 0) {
8398                    pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
8399                } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) {
8400                    pkgSetting.lastUpdateTime = currentTime;
8401                }
8402            } else if (pkgSetting.firstInstallTime == 0) {
8403                // We need *something*.  Take time time stamp of the file.
8404                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
8405            } else if ((policyFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
8406                if (scanFileTime != pkgSetting.timeStamp) {
8407                    // A package on the system image has changed; consider this
8408                    // to be an update.
8409                    pkgSetting.lastUpdateTime = scanFileTime;
8410                }
8411            }
8412
8413            // Add the package's KeySets to the global KeySetManagerService
8414            ksms.addScannedPackageLPw(pkg);
8415
8416            int N = pkg.providers.size();
8417            StringBuilder r = null;
8418            int i;
8419            for (i=0; i<N; i++) {
8420                PackageParser.Provider p = pkg.providers.get(i);
8421                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
8422                        p.info.processName, pkg.applicationInfo.uid);
8423                mProviders.addProvider(p);
8424                p.syncable = p.info.isSyncable;
8425                if (p.info.authority != null) {
8426                    String names[] = p.info.authority.split(";");
8427                    p.info.authority = null;
8428                    for (int j = 0; j < names.length; j++) {
8429                        if (j == 1 && p.syncable) {
8430                            // We only want the first authority for a provider to possibly be
8431                            // syncable, so if we already added this provider using a different
8432                            // authority clear the syncable flag. We copy the provider before
8433                            // changing it because the mProviders object contains a reference
8434                            // to a provider that we don't want to change.
8435                            // Only do this for the second authority since the resulting provider
8436                            // object can be the same for all future authorities for this provider.
8437                            p = new PackageParser.Provider(p);
8438                            p.syncable = false;
8439                        }
8440                        if (!mProvidersByAuthority.containsKey(names[j])) {
8441                            mProvidersByAuthority.put(names[j], p);
8442                            if (p.info.authority == null) {
8443                                p.info.authority = names[j];
8444                            } else {
8445                                p.info.authority = p.info.authority + ";" + names[j];
8446                            }
8447                            if (DEBUG_PACKAGE_SCANNING) {
8448                                if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
8449                                    Log.d(TAG, "Registered content provider: " + names[j]
8450                                            + ", className = " + p.info.name + ", isSyncable = "
8451                                            + p.info.isSyncable);
8452                            }
8453                        } else {
8454                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
8455                            Slog.w(TAG, "Skipping provider name " + names[j] +
8456                                    " (in package " + pkg.applicationInfo.packageName +
8457                                    "): name already used by "
8458                                    + ((other != null && other.getComponentName() != null)
8459                                            ? other.getComponentName().getPackageName() : "?"));
8460                        }
8461                    }
8462                }
8463                if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8464                    if (r == null) {
8465                        r = new StringBuilder(256);
8466                    } else {
8467                        r.append(' ');
8468                    }
8469                    r.append(p.info.name);
8470                }
8471            }
8472            if (r != null) {
8473                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
8474            }
8475
8476            N = pkg.services.size();
8477            r = null;
8478            for (i=0; i<N; i++) {
8479                PackageParser.Service s = pkg.services.get(i);
8480                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
8481                        s.info.processName, pkg.applicationInfo.uid);
8482                mServices.addService(s);
8483                if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8484                    if (r == null) {
8485                        r = new StringBuilder(256);
8486                    } else {
8487                        r.append(' ');
8488                    }
8489                    r.append(s.info.name);
8490                }
8491            }
8492            if (r != null) {
8493                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
8494            }
8495
8496            N = pkg.receivers.size();
8497            r = null;
8498            for (i=0; i<N; i++) {
8499                PackageParser.Activity a = pkg.receivers.get(i);
8500                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
8501                        a.info.processName, pkg.applicationInfo.uid);
8502                mReceivers.addActivity(a, "receiver");
8503                if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8504                    if (r == null) {
8505                        r = new StringBuilder(256);
8506                    } else {
8507                        r.append(' ');
8508                    }
8509                    r.append(a.info.name);
8510                }
8511            }
8512            if (r != null) {
8513                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
8514            }
8515
8516            N = pkg.activities.size();
8517            r = null;
8518            for (i=0; i<N; i++) {
8519                PackageParser.Activity a = pkg.activities.get(i);
8520                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
8521                        a.info.processName, pkg.applicationInfo.uid);
8522                mActivities.addActivity(a, "activity");
8523                if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8524                    if (r == null) {
8525                        r = new StringBuilder(256);
8526                    } else {
8527                        r.append(' ');
8528                    }
8529                    r.append(a.info.name);
8530                }
8531            }
8532            if (r != null) {
8533                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
8534            }
8535
8536            N = pkg.permissionGroups.size();
8537            r = null;
8538            for (i=0; i<N; i++) {
8539                PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
8540                PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
8541                if (cur == null) {
8542                    mPermissionGroups.put(pg.info.name, pg);
8543                    if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8544                        if (r == null) {
8545                            r = new StringBuilder(256);
8546                        } else {
8547                            r.append(' ');
8548                        }
8549                        r.append(pg.info.name);
8550                    }
8551                } else {
8552                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
8553                            + pg.info.packageName + " ignored: original from "
8554                            + cur.info.packageName);
8555                    if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8556                        if (r == null) {
8557                            r = new StringBuilder(256);
8558                        } else {
8559                            r.append(' ');
8560                        }
8561                        r.append("DUP:");
8562                        r.append(pg.info.name);
8563                    }
8564                }
8565            }
8566            if (r != null) {
8567                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permission Groups: " + r);
8568            }
8569
8570            N = pkg.permissions.size();
8571            r = null;
8572            for (i=0; i<N; i++) {
8573                PackageParser.Permission p = pkg.permissions.get(i);
8574
8575                // Assume by default that we did not install this permission into the system.
8576                p.info.flags &= ~PermissionInfo.FLAG_INSTALLED;
8577
8578                // Now that permission groups have a special meaning, we ignore permission
8579                // groups for legacy apps to prevent unexpected behavior. In particular,
8580                // permissions for one app being granted to someone just becase they happen
8581                // to be in a group defined by another app (before this had no implications).
8582                if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) {
8583                    p.group = mPermissionGroups.get(p.info.group);
8584                    // Warn for a permission in an unknown group.
8585                    if (p.info.group != null && p.group == null) {
8586                        Slog.w(TAG, "Permission " + p.info.name + " from package "
8587                                + p.info.packageName + " in an unknown group " + p.info.group);
8588                    }
8589                }
8590
8591                ArrayMap<String, BasePermission> permissionMap =
8592                        p.tree ? mSettings.mPermissionTrees
8593                                : mSettings.mPermissions;
8594                BasePermission bp = permissionMap.get(p.info.name);
8595
8596                // Allow system apps to redefine non-system permissions
8597                if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) {
8598                    final boolean currentOwnerIsSystem = (bp.perm != null
8599                            && isSystemApp(bp.perm.owner));
8600                    if (isSystemApp(p.owner)) {
8601                        if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) {
8602                            // It's a built-in permission and no owner, take ownership now
8603                            bp.packageSetting = pkgSetting;
8604                            bp.perm = p;
8605                            bp.uid = pkg.applicationInfo.uid;
8606                            bp.sourcePackage = p.info.packageName;
8607                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
8608                        } else if (!currentOwnerIsSystem) {
8609                            String msg = "New decl " + p.owner + " of permission  "
8610                                    + p.info.name + " is system; overriding " + bp.sourcePackage;
8611                            reportSettingsProblem(Log.WARN, msg);
8612                            bp = null;
8613                        }
8614                    }
8615                }
8616
8617                if (bp == null) {
8618                    bp = new BasePermission(p.info.name, p.info.packageName,
8619                            BasePermission.TYPE_NORMAL);
8620                    permissionMap.put(p.info.name, bp);
8621                }
8622
8623                if (bp.perm == null) {
8624                    if (bp.sourcePackage == null
8625                            || bp.sourcePackage.equals(p.info.packageName)) {
8626                        BasePermission tree = findPermissionTreeLP(p.info.name);
8627                        if (tree == null
8628                                || tree.sourcePackage.equals(p.info.packageName)) {
8629                            bp.packageSetting = pkgSetting;
8630                            bp.perm = p;
8631                            bp.uid = pkg.applicationInfo.uid;
8632                            bp.sourcePackage = p.info.packageName;
8633                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
8634                            if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8635                                if (r == null) {
8636                                    r = new StringBuilder(256);
8637                                } else {
8638                                    r.append(' ');
8639                                }
8640                                r.append(p.info.name);
8641                            }
8642                        } else {
8643                            Slog.w(TAG, "Permission " + p.info.name + " from package "
8644                                    + p.info.packageName + " ignored: base tree "
8645                                    + tree.name + " is from package "
8646                                    + tree.sourcePackage);
8647                        }
8648                    } else {
8649                        Slog.w(TAG, "Permission " + p.info.name + " from package "
8650                                + p.info.packageName + " ignored: original from "
8651                                + bp.sourcePackage);
8652                    }
8653                } else if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8654                    if (r == null) {
8655                        r = new StringBuilder(256);
8656                    } else {
8657                        r.append(' ');
8658                    }
8659                    r.append("DUP:");
8660                    r.append(p.info.name);
8661                }
8662                if (bp.perm == p) {
8663                    bp.protectionLevel = p.info.protectionLevel;
8664                }
8665            }
8666
8667            if (r != null) {
8668                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permissions: " + r);
8669            }
8670
8671            N = pkg.instrumentation.size();
8672            r = null;
8673            for (i=0; i<N; i++) {
8674                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
8675                a.info.packageName = pkg.applicationInfo.packageName;
8676                a.info.sourceDir = pkg.applicationInfo.sourceDir;
8677                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
8678                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
8679                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
8680                a.info.dataDir = pkg.applicationInfo.dataDir;
8681                a.info.deviceProtectedDataDir = pkg.applicationInfo.deviceProtectedDataDir;
8682                a.info.credentialProtectedDataDir = pkg.applicationInfo.credentialProtectedDataDir;
8683
8684                // TODO: Update instrumentation.nativeLibraryDir as well ? Does it
8685                // need other information about the application, like the ABI and what not ?
8686                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
8687                mInstrumentation.put(a.getComponentName(), a);
8688                if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8689                    if (r == null) {
8690                        r = new StringBuilder(256);
8691                    } else {
8692                        r.append(' ');
8693                    }
8694                    r.append(a.info.name);
8695                }
8696            }
8697            if (r != null) {
8698                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
8699            }
8700
8701            if (pkg.protectedBroadcasts != null) {
8702                N = pkg.protectedBroadcasts.size();
8703                for (i=0; i<N; i++) {
8704                    mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
8705                }
8706            }
8707
8708            pkgSetting.setTimeStamp(scanFileTime);
8709
8710            // Create idmap files for pairs of (packages, overlay packages).
8711            // Note: "android", ie framework-res.apk, is handled by native layers.
8712            if (pkg.mOverlayTarget != null) {
8713                // This is an overlay package.
8714                if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) {
8715                    if (!mOverlays.containsKey(pkg.mOverlayTarget)) {
8716                        mOverlays.put(pkg.mOverlayTarget,
8717                                new ArrayMap<String, PackageParser.Package>());
8718                    }
8719                    ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget);
8720                    map.put(pkg.packageName, pkg);
8721                    PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget);
8722                    if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) {
8723                        createIdmapFailed = true;
8724                    }
8725                }
8726            } else if (mOverlays.containsKey(pkg.packageName) &&
8727                    !pkg.packageName.equals("android")) {
8728                // This is a regular package, with one or more known overlay packages.
8729                createIdmapsForPackageLI(pkg);
8730            }
8731        }
8732
8733        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8734
8735        if (createIdmapFailed) {
8736            throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
8737                    "scanPackageLI failed to createIdmap");
8738        }
8739        return pkg;
8740    }
8741
8742    /**
8743     * Derive the ABI of a non-system package located at {@code scanFile}. This information
8744     * is derived purely on the basis of the contents of {@code scanFile} and
8745     * {@code cpuAbiOverride}.
8746     *
8747     * If {@code extractLibs} is true, native libraries are extracted from the app if required.
8748     */
8749    private void derivePackageAbi(PackageParser.Package pkg, File scanFile,
8750                                 String cpuAbiOverride, boolean extractLibs)
8751            throws PackageManagerException {
8752        // TODO: We can probably be smarter about this stuff. For installed apps,
8753        // we can calculate this information at install time once and for all. For
8754        // system apps, we can probably assume that this information doesn't change
8755        // after the first boot scan. As things stand, we do lots of unnecessary work.
8756
8757        // Give ourselves some initial paths; we'll come back for another
8758        // pass once we've determined ABI below.
8759        setNativeLibraryPaths(pkg);
8760
8761        // We would never need to extract libs for forward-locked and external packages,
8762        // since the container service will do it for us. We shouldn't attempt to
8763        // extract libs from system app when it was not updated.
8764        if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() ||
8765                (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) {
8766            extractLibs = false;
8767        }
8768
8769        final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
8770        final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
8771
8772        NativeLibraryHelper.Handle handle = null;
8773        try {
8774            handle = NativeLibraryHelper.Handle.create(pkg);
8775            // TODO(multiArch): This can be null for apps that didn't go through the
8776            // usual installation process. We can calculate it again, like we
8777            // do during install time.
8778            //
8779            // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
8780            // unnecessary.
8781            final File nativeLibraryRoot = new File(nativeLibraryRootStr);
8782
8783            // Null out the abis so that they can be recalculated.
8784            pkg.applicationInfo.primaryCpuAbi = null;
8785            pkg.applicationInfo.secondaryCpuAbi = null;
8786            if (isMultiArch(pkg.applicationInfo)) {
8787                // Warn if we've set an abiOverride for multi-lib packages..
8788                // By definition, we need to copy both 32 and 64 bit libraries for
8789                // such packages.
8790                if (pkg.cpuAbiOverride != null
8791                        && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
8792                    Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
8793                }
8794
8795                int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
8796                int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
8797                if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
8798                    if (extractLibs) {
8799                        abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
8800                                nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
8801                                useIsaSpecificSubdirs);
8802                    } else {
8803                        abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
8804                    }
8805                }
8806
8807                maybeThrowExceptionForMultiArchCopy(
8808                        "Error unpackaging 32 bit native libs for multiarch app.", abi32);
8809
8810                if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
8811                    if (extractLibs) {
8812                        abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
8813                                nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
8814                                useIsaSpecificSubdirs);
8815                    } else {
8816                        abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
8817                    }
8818                }
8819
8820                maybeThrowExceptionForMultiArchCopy(
8821                        "Error unpackaging 64 bit native libs for multiarch app.", abi64);
8822
8823                if (abi64 >= 0) {
8824                    pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
8825                }
8826
8827                if (abi32 >= 0) {
8828                    final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
8829                    if (abi64 >= 0) {
8830                        if (pkg.use32bitAbi) {
8831                            pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi;
8832                            pkg.applicationInfo.primaryCpuAbi = abi;
8833                        } else {
8834                            pkg.applicationInfo.secondaryCpuAbi = abi;
8835                        }
8836                    } else {
8837                        pkg.applicationInfo.primaryCpuAbi = abi;
8838                    }
8839                }
8840
8841            } else {
8842                String[] abiList = (cpuAbiOverride != null) ?
8843                        new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
8844
8845                // Enable gross and lame hacks for apps that are built with old
8846                // SDK tools. We must scan their APKs for renderscript bitcode and
8847                // not launch them if it's present. Don't bother checking on devices
8848                // that don't have 64 bit support.
8849                boolean needsRenderScriptOverride = false;
8850                if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
8851                        NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
8852                    abiList = Build.SUPPORTED_32_BIT_ABIS;
8853                    needsRenderScriptOverride = true;
8854                }
8855
8856                final int copyRet;
8857                if (extractLibs) {
8858                    copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
8859                            nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
8860                } else {
8861                    copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
8862                }
8863
8864                if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
8865                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
8866                            "Error unpackaging native libs for app, errorCode=" + copyRet);
8867                }
8868
8869                if (copyRet >= 0) {
8870                    pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
8871                } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
8872                    pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
8873                } else if (needsRenderScriptOverride) {
8874                    pkg.applicationInfo.primaryCpuAbi = abiList[0];
8875                }
8876            }
8877        } catch (IOException ioe) {
8878            Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
8879        } finally {
8880            IoUtils.closeQuietly(handle);
8881        }
8882
8883        // Now that we've calculated the ABIs and determined if it's an internal app,
8884        // we will go ahead and populate the nativeLibraryPath.
8885        setNativeLibraryPaths(pkg);
8886    }
8887
8888    /**
8889     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
8890     * i.e, so that all packages can be run inside a single process if required.
8891     *
8892     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
8893     * this function will either try and make the ABI for all packages in {@code packagesForUser}
8894     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
8895     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
8896     * updating a package that belongs to a shared user.
8897     *
8898     * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
8899     * adds unnecessary complexity.
8900     */
8901    private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser,
8902            PackageParser.Package scannedPackage, boolean bootComplete) {
8903        String requiredInstructionSet = null;
8904        if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
8905            requiredInstructionSet = VMRuntime.getInstructionSet(
8906                     scannedPackage.applicationInfo.primaryCpuAbi);
8907        }
8908
8909        PackageSetting requirer = null;
8910        for (PackageSetting ps : packagesForUser) {
8911            // If packagesForUser contains scannedPackage, we skip it. This will happen
8912            // when scannedPackage is an update of an existing package. Without this check,
8913            // we will never be able to change the ABI of any package belonging to a shared
8914            // user, even if it's compatible with other packages.
8915            if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
8916                if (ps.primaryCpuAbiString == null) {
8917                    continue;
8918                }
8919
8920                final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
8921                if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
8922                    // We have a mismatch between instruction sets (say arm vs arm64) warn about
8923                    // this but there's not much we can do.
8924                    String errorMessage = "Instruction set mismatch, "
8925                            + ((requirer == null) ? "[caller]" : requirer)
8926                            + " requires " + requiredInstructionSet + " whereas " + ps
8927                            + " requires " + instructionSet;
8928                    Slog.w(TAG, errorMessage);
8929                }
8930
8931                if (requiredInstructionSet == null) {
8932                    requiredInstructionSet = instructionSet;
8933                    requirer = ps;
8934                }
8935            }
8936        }
8937
8938        if (requiredInstructionSet != null) {
8939            String adjustedAbi;
8940            if (requirer != null) {
8941                // requirer != null implies that either scannedPackage was null or that scannedPackage
8942                // did not require an ABI, in which case we have to adjust scannedPackage to match
8943                // the ABI of the set (which is the same as requirer's ABI)
8944                adjustedAbi = requirer.primaryCpuAbiString;
8945                if (scannedPackage != null) {
8946                    scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
8947                }
8948            } else {
8949                // requirer == null implies that we're updating all ABIs in the set to
8950                // match scannedPackage.
8951                adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
8952            }
8953
8954            for (PackageSetting ps : packagesForUser) {
8955                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
8956                    if (ps.primaryCpuAbiString != null) {
8957                        continue;
8958                    }
8959
8960                    ps.primaryCpuAbiString = adjustedAbi;
8961                    if (ps.pkg != null && ps.pkg.applicationInfo != null &&
8962                            !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) {
8963                        ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
8964                        Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi
8965                                + " (requirer="
8966                                + (requirer == null ? "null" : requirer.pkg.packageName)
8967                                + ", scannedPackage="
8968                                + (scannedPackage != null ? scannedPackage.packageName : "null")
8969                                + ")");
8970                        try {
8971                            mInstaller.rmdex(ps.codePathString,
8972                                    getDexCodeInstructionSet(getPreferredInstructionSet()));
8973                        } catch (InstallerException ignored) {
8974                        }
8975                    }
8976                }
8977            }
8978        }
8979    }
8980
8981    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
8982        synchronized (mPackages) {
8983            mResolverReplaced = true;
8984            // Set up information for custom user intent resolution activity.
8985            mResolveActivity.applicationInfo = pkg.applicationInfo;
8986            mResolveActivity.name = mCustomResolverComponentName.getClassName();
8987            mResolveActivity.packageName = pkg.applicationInfo.packageName;
8988            mResolveActivity.processName = pkg.applicationInfo.packageName;
8989            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
8990            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
8991                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
8992            mResolveActivity.theme = 0;
8993            mResolveActivity.exported = true;
8994            mResolveActivity.enabled = true;
8995            mResolveInfo.activityInfo = mResolveActivity;
8996            mResolveInfo.priority = 0;
8997            mResolveInfo.preferredOrder = 0;
8998            mResolveInfo.match = 0;
8999            mResolveComponentName = mCustomResolverComponentName;
9000            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
9001                    mResolveComponentName);
9002        }
9003    }
9004
9005    private void setUpEphemeralInstallerActivityLP(ComponentName installerComponent) {
9006        final PackageParser.Package pkg = mPackages.get(installerComponent.getPackageName());
9007
9008        // Set up information for ephemeral installer activity
9009        mEphemeralInstallerActivity.applicationInfo = pkg.applicationInfo;
9010        mEphemeralInstallerActivity.name = mEphemeralInstallerComponent.getClassName();
9011        mEphemeralInstallerActivity.packageName = pkg.applicationInfo.packageName;
9012        mEphemeralInstallerActivity.processName = pkg.applicationInfo.packageName;
9013        mEphemeralInstallerActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
9014        mEphemeralInstallerActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
9015                ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
9016        mEphemeralInstallerActivity.theme = 0;
9017        mEphemeralInstallerActivity.exported = true;
9018        mEphemeralInstallerActivity.enabled = true;
9019        mEphemeralInstallerInfo.activityInfo = mEphemeralInstallerActivity;
9020        mEphemeralInstallerInfo.priority = 0;
9021        mEphemeralInstallerInfo.preferredOrder = 0;
9022        mEphemeralInstallerInfo.match = 0;
9023
9024        if (DEBUG_EPHEMERAL) {
9025            Slog.d(TAG, "Set ephemeral installer activity: " + mEphemeralInstallerComponent);
9026        }
9027    }
9028
9029    private static String calculateBundledApkRoot(final String codePathString) {
9030        final File codePath = new File(codePathString);
9031        final File codeRoot;
9032        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
9033            codeRoot = Environment.getRootDirectory();
9034        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
9035            codeRoot = Environment.getOemDirectory();
9036        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
9037            codeRoot = Environment.getVendorDirectory();
9038        } else {
9039            // Unrecognized code path; take its top real segment as the apk root:
9040            // e.g. /something/app/blah.apk => /something
9041            try {
9042                File f = codePath.getCanonicalFile();
9043                File parent = f.getParentFile();    // non-null because codePath is a file
9044                File tmp;
9045                while ((tmp = parent.getParentFile()) != null) {
9046                    f = parent;
9047                    parent = tmp;
9048                }
9049                codeRoot = f;
9050                Slog.w(TAG, "Unrecognized code path "
9051                        + codePath + " - using " + codeRoot);
9052            } catch (IOException e) {
9053                // Can't canonicalize the code path -- shenanigans?
9054                Slog.w(TAG, "Can't canonicalize code path " + codePath);
9055                return Environment.getRootDirectory().getPath();
9056            }
9057        }
9058        return codeRoot.getPath();
9059    }
9060
9061    /**
9062     * Derive and set the location of native libraries for the given package,
9063     * which varies depending on where and how the package was installed.
9064     */
9065    private void setNativeLibraryPaths(PackageParser.Package pkg) {
9066        final ApplicationInfo info = pkg.applicationInfo;
9067        final String codePath = pkg.codePath;
9068        final File codeFile = new File(codePath);
9069        final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp();
9070        final boolean asecApp = info.isForwardLocked() || info.isExternalAsec();
9071
9072        info.nativeLibraryRootDir = null;
9073        info.nativeLibraryRootRequiresIsa = false;
9074        info.nativeLibraryDir = null;
9075        info.secondaryNativeLibraryDir = null;
9076
9077        if (isApkFile(codeFile)) {
9078            // Monolithic install
9079            if (bundledApp) {
9080                // If "/system/lib64/apkname" exists, assume that is the per-package
9081                // native library directory to use; otherwise use "/system/lib/apkname".
9082                final String apkRoot = calculateBundledApkRoot(info.sourceDir);
9083                final boolean is64Bit = VMRuntime.is64BitInstructionSet(
9084                        getPrimaryInstructionSet(info));
9085
9086                // This is a bundled system app so choose the path based on the ABI.
9087                // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
9088                // is just the default path.
9089                final String apkName = deriveCodePathName(codePath);
9090                final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
9091                info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
9092                        apkName).getAbsolutePath();
9093
9094                if (info.secondaryCpuAbi != null) {
9095                    final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
9096                    info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
9097                            secondaryLibDir, apkName).getAbsolutePath();
9098                }
9099            } else if (asecApp) {
9100                info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
9101                        .getAbsolutePath();
9102            } else {
9103                final String apkName = deriveCodePathName(codePath);
9104                info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName)
9105                        .getAbsolutePath();
9106            }
9107
9108            info.nativeLibraryRootRequiresIsa = false;
9109            info.nativeLibraryDir = info.nativeLibraryRootDir;
9110        } else {
9111            // Cluster install
9112            info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
9113            info.nativeLibraryRootRequiresIsa = true;
9114
9115            info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
9116                    getPrimaryInstructionSet(info)).getAbsolutePath();
9117
9118            if (info.secondaryCpuAbi != null) {
9119                info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
9120                        VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
9121            }
9122        }
9123    }
9124
9125    /**
9126     * Calculate the abis and roots for a bundled app. These can uniquely
9127     * be determined from the contents of the system partition, i.e whether
9128     * it contains 64 or 32 bit shared libraries etc. We do not validate any
9129     * of this information, and instead assume that the system was built
9130     * sensibly.
9131     */
9132    private void setBundledAppAbisAndRoots(PackageParser.Package pkg,
9133                                           PackageSetting pkgSetting) {
9134        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
9135
9136        // If "/system/lib64/apkname" exists, assume that is the per-package
9137        // native library directory to use; otherwise use "/system/lib/apkname".
9138        final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
9139        setBundledAppAbi(pkg, apkRoot, apkName);
9140        // pkgSetting might be null during rescan following uninstall of updates
9141        // to a bundled app, so accommodate that possibility.  The settings in
9142        // that case will be established later from the parsed package.
9143        //
9144        // If the settings aren't null, sync them up with what we've just derived.
9145        // note that apkRoot isn't stored in the package settings.
9146        if (pkgSetting != null) {
9147            pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
9148            pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
9149        }
9150    }
9151
9152    /**
9153     * Deduces the ABI of a bundled app and sets the relevant fields on the
9154     * parsed pkg object.
9155     *
9156     * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
9157     *        under which system libraries are installed.
9158     * @param apkName the name of the installed package.
9159     */
9160    private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
9161        final File codeFile = new File(pkg.codePath);
9162
9163        final boolean has64BitLibs;
9164        final boolean has32BitLibs;
9165        if (isApkFile(codeFile)) {
9166            // Monolithic install
9167            has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
9168            has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
9169        } else {
9170            // Cluster install
9171            final File rootDir = new File(codeFile, LIB_DIR_NAME);
9172            if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
9173                    && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
9174                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
9175                has64BitLibs = (new File(rootDir, isa)).exists();
9176            } else {
9177                has64BitLibs = false;
9178            }
9179            if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
9180                    && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
9181                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
9182                has32BitLibs = (new File(rootDir, isa)).exists();
9183            } else {
9184                has32BitLibs = false;
9185            }
9186        }
9187
9188        if (has64BitLibs && !has32BitLibs) {
9189            // The package has 64 bit libs, but not 32 bit libs. Its primary
9190            // ABI should be 64 bit. We can safely assume here that the bundled
9191            // native libraries correspond to the most preferred ABI in the list.
9192
9193            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
9194            pkg.applicationInfo.secondaryCpuAbi = null;
9195        } else if (has32BitLibs && !has64BitLibs) {
9196            // The package has 32 bit libs but not 64 bit libs. Its primary
9197            // ABI should be 32 bit.
9198
9199            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
9200            pkg.applicationInfo.secondaryCpuAbi = null;
9201        } else if (has32BitLibs && has64BitLibs) {
9202            // The application has both 64 and 32 bit bundled libraries. We check
9203            // here that the app declares multiArch support, and warn if it doesn't.
9204            //
9205            // We will be lenient here and record both ABIs. The primary will be the
9206            // ABI that's higher on the list, i.e, a device that's configured to prefer
9207            // 64 bit apps will see a 64 bit primary ABI,
9208
9209            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
9210                Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch.");
9211            }
9212
9213            if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
9214                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
9215                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
9216            } else {
9217                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
9218                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
9219            }
9220        } else {
9221            pkg.applicationInfo.primaryCpuAbi = null;
9222            pkg.applicationInfo.secondaryCpuAbi = null;
9223        }
9224    }
9225
9226    private void killApplication(String pkgName, int appId, String reason) {
9227        // Request the ActivityManager to kill the process(only for existing packages)
9228        // so that we do not end up in a confused state while the user is still using the older
9229        // version of the application while the new one gets installed.
9230        final long token = Binder.clearCallingIdentity();
9231        try {
9232            IActivityManager am = ActivityManagerNative.getDefault();
9233            if (am != null) {
9234                try {
9235                    am.killApplicationWithAppId(pkgName, appId, reason);
9236                } catch (RemoteException e) {
9237                }
9238            }
9239        } finally {
9240            Binder.restoreCallingIdentity(token);
9241        }
9242    }
9243
9244    private void removePackageLI(PackageParser.Package pkg, boolean chatty) {
9245        // Remove the parent package setting
9246        PackageSetting ps = (PackageSetting) pkg.mExtras;
9247        if (ps != null) {
9248            removePackageLI(ps, chatty);
9249        }
9250        // Remove the child package setting
9251        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9252        for (int i = 0; i < childCount; i++) {
9253            PackageParser.Package childPkg = pkg.childPackages.get(i);
9254            ps = (PackageSetting) childPkg.mExtras;
9255            if (ps != null) {
9256                removePackageLI(ps, chatty);
9257            }
9258        }
9259    }
9260
9261    void removePackageLI(PackageSetting ps, boolean chatty) {
9262        if (DEBUG_INSTALL) {
9263            if (chatty)
9264                Log.d(TAG, "Removing package " + ps.name);
9265        }
9266
9267        // writer
9268        synchronized (mPackages) {
9269            mPackages.remove(ps.name);
9270            final PackageParser.Package pkg = ps.pkg;
9271            if (pkg != null) {
9272                cleanPackageDataStructuresLILPw(pkg, chatty);
9273            }
9274        }
9275    }
9276
9277    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
9278        if (DEBUG_INSTALL) {
9279            if (chatty)
9280                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
9281        }
9282
9283        // writer
9284        synchronized (mPackages) {
9285            // Remove the parent package
9286            mPackages.remove(pkg.applicationInfo.packageName);
9287            cleanPackageDataStructuresLILPw(pkg, chatty);
9288
9289            // Remove the child packages
9290            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9291            for (int i = 0; i < childCount; i++) {
9292                PackageParser.Package childPkg = pkg.childPackages.get(i);
9293                mPackages.remove(childPkg.applicationInfo.packageName);
9294                cleanPackageDataStructuresLILPw(childPkg, chatty);
9295            }
9296        }
9297    }
9298
9299    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
9300        int N = pkg.providers.size();
9301        StringBuilder r = null;
9302        int i;
9303        for (i=0; i<N; i++) {
9304            PackageParser.Provider p = pkg.providers.get(i);
9305            mProviders.removeProvider(p);
9306            if (p.info.authority == null) {
9307
9308                /* There was another ContentProvider with this authority when
9309                 * this app was installed so this authority is null,
9310                 * Ignore it as we don't have to unregister the provider.
9311                 */
9312                continue;
9313            }
9314            String names[] = p.info.authority.split(";");
9315            for (int j = 0; j < names.length; j++) {
9316                if (mProvidersByAuthority.get(names[j]) == p) {
9317                    mProvidersByAuthority.remove(names[j]);
9318                    if (DEBUG_REMOVE) {
9319                        if (chatty)
9320                            Log.d(TAG, "Unregistered content provider: " + names[j]
9321                                    + ", className = " + p.info.name + ", isSyncable = "
9322                                    + p.info.isSyncable);
9323                    }
9324                }
9325            }
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 (r != null) {
9336            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
9337        }
9338
9339        N = pkg.services.size();
9340        r = null;
9341        for (i=0; i<N; i++) {
9342            PackageParser.Service s = pkg.services.get(i);
9343            mServices.removeService(s);
9344            if (chatty) {
9345                if (r == null) {
9346                    r = new StringBuilder(256);
9347                } else {
9348                    r.append(' ');
9349                }
9350                r.append(s.info.name);
9351            }
9352        }
9353        if (r != null) {
9354            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
9355        }
9356
9357        N = pkg.receivers.size();
9358        r = null;
9359        for (i=0; i<N; i++) {
9360            PackageParser.Activity a = pkg.receivers.get(i);
9361            mReceivers.removeActivity(a, "receiver");
9362            if (DEBUG_REMOVE && chatty) {
9363                if (r == null) {
9364                    r = new StringBuilder(256);
9365                } else {
9366                    r.append(' ');
9367                }
9368                r.append(a.info.name);
9369            }
9370        }
9371        if (r != null) {
9372            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
9373        }
9374
9375        N = pkg.activities.size();
9376        r = null;
9377        for (i=0; i<N; i++) {
9378            PackageParser.Activity a = pkg.activities.get(i);
9379            mActivities.removeActivity(a, "activity");
9380            if (DEBUG_REMOVE && chatty) {
9381                if (r == null) {
9382                    r = new StringBuilder(256);
9383                } else {
9384                    r.append(' ');
9385                }
9386                r.append(a.info.name);
9387            }
9388        }
9389        if (r != null) {
9390            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
9391        }
9392
9393        N = pkg.permissions.size();
9394        r = null;
9395        for (i=0; i<N; i++) {
9396            PackageParser.Permission p = pkg.permissions.get(i);
9397            BasePermission bp = mSettings.mPermissions.get(p.info.name);
9398            if (bp == null) {
9399                bp = mSettings.mPermissionTrees.get(p.info.name);
9400            }
9401            if (bp != null && bp.perm == p) {
9402                bp.perm = null;
9403                if (DEBUG_REMOVE && chatty) {
9404                    if (r == null) {
9405                        r = new StringBuilder(256);
9406                    } else {
9407                        r.append(' ');
9408                    }
9409                    r.append(p.info.name);
9410                }
9411            }
9412            if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
9413                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(p.info.name);
9414                if (appOpPkgs != null) {
9415                    appOpPkgs.remove(pkg.packageName);
9416                }
9417            }
9418        }
9419        if (r != null) {
9420            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
9421        }
9422
9423        N = pkg.requestedPermissions.size();
9424        r = null;
9425        for (i=0; i<N; i++) {
9426            String perm = pkg.requestedPermissions.get(i);
9427            BasePermission bp = mSettings.mPermissions.get(perm);
9428            if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
9429                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(perm);
9430                if (appOpPkgs != null) {
9431                    appOpPkgs.remove(pkg.packageName);
9432                    if (appOpPkgs.isEmpty()) {
9433                        mAppOpPermissionPackages.remove(perm);
9434                    }
9435                }
9436            }
9437        }
9438        if (r != null) {
9439            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
9440        }
9441
9442        N = pkg.instrumentation.size();
9443        r = null;
9444        for (i=0; i<N; i++) {
9445            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
9446            mInstrumentation.remove(a.getComponentName());
9447            if (DEBUG_REMOVE && chatty) {
9448                if (r == null) {
9449                    r = new StringBuilder(256);
9450                } else {
9451                    r.append(' ');
9452                }
9453                r.append(a.info.name);
9454            }
9455        }
9456        if (r != null) {
9457            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
9458        }
9459
9460        r = null;
9461        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
9462            // Only system apps can hold shared libraries.
9463            if (pkg.libraryNames != null) {
9464                for (i=0; i<pkg.libraryNames.size(); i++) {
9465                    String name = pkg.libraryNames.get(i);
9466                    SharedLibraryEntry cur = mSharedLibraries.get(name);
9467                    if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) {
9468                        mSharedLibraries.remove(name);
9469                        if (DEBUG_REMOVE && chatty) {
9470                            if (r == null) {
9471                                r = new StringBuilder(256);
9472                            } else {
9473                                r.append(' ');
9474                            }
9475                            r.append(name);
9476                        }
9477                    }
9478                }
9479            }
9480        }
9481        if (r != null) {
9482            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
9483        }
9484    }
9485
9486    private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
9487        for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
9488            if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
9489                return true;
9490            }
9491        }
9492        return false;
9493    }
9494
9495    static final int UPDATE_PERMISSIONS_ALL = 1<<0;
9496    static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
9497    static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
9498
9499    private void updatePermissionsLPw(PackageParser.Package pkg, int flags) {
9500        // Update the parent permissions
9501        updatePermissionsLPw(pkg.packageName, pkg, flags);
9502        // Update the child permissions
9503        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9504        for (int i = 0; i < childCount; i++) {
9505            PackageParser.Package childPkg = pkg.childPackages.get(i);
9506            updatePermissionsLPw(childPkg.packageName, childPkg, flags);
9507        }
9508    }
9509
9510    private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo,
9511            int flags) {
9512        final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null;
9513        updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags);
9514    }
9515
9516    private void updatePermissionsLPw(String changingPkg,
9517            PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) {
9518        // Make sure there are no dangling permission trees.
9519        Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator();
9520        while (it.hasNext()) {
9521            final BasePermission bp = it.next();
9522            if (bp.packageSetting == null) {
9523                // We may not yet have parsed the package, so just see if
9524                // we still know about its settings.
9525                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
9526            }
9527            if (bp.packageSetting == null) {
9528                Slog.w(TAG, "Removing dangling permission tree: " + bp.name
9529                        + " from package " + bp.sourcePackage);
9530                it.remove();
9531            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
9532                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
9533                    Slog.i(TAG, "Removing old permission tree: " + bp.name
9534                            + " from package " + bp.sourcePackage);
9535                    flags |= UPDATE_PERMISSIONS_ALL;
9536                    it.remove();
9537                }
9538            }
9539        }
9540
9541        // Make sure all dynamic permissions have been assigned to a package,
9542        // and make sure there are no dangling permissions.
9543        it = mSettings.mPermissions.values().iterator();
9544        while (it.hasNext()) {
9545            final BasePermission bp = it.next();
9546            if (bp.type == BasePermission.TYPE_DYNAMIC) {
9547                if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
9548                        + bp.name + " pkg=" + bp.sourcePackage
9549                        + " info=" + bp.pendingInfo);
9550                if (bp.packageSetting == null && bp.pendingInfo != null) {
9551                    final BasePermission tree = findPermissionTreeLP(bp.name);
9552                    if (tree != null && tree.perm != null) {
9553                        bp.packageSetting = tree.packageSetting;
9554                        bp.perm = new PackageParser.Permission(tree.perm.owner,
9555                                new PermissionInfo(bp.pendingInfo));
9556                        bp.perm.info.packageName = tree.perm.info.packageName;
9557                        bp.perm.info.name = bp.name;
9558                        bp.uid = tree.uid;
9559                    }
9560                }
9561            }
9562            if (bp.packageSetting == null) {
9563                // We may not yet have parsed the package, so just see if
9564                // we still know about its settings.
9565                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
9566            }
9567            if (bp.packageSetting == null) {
9568                Slog.w(TAG, "Removing dangling permission: " + bp.name
9569                        + " from package " + bp.sourcePackage);
9570                it.remove();
9571            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
9572                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
9573                    Slog.i(TAG, "Removing old permission: " + bp.name
9574                            + " from package " + bp.sourcePackage);
9575                    flags |= UPDATE_PERMISSIONS_ALL;
9576                    it.remove();
9577                }
9578            }
9579        }
9580
9581        // Now update the permissions for all packages, in particular
9582        // replace the granted permissions of the system packages.
9583        if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
9584            for (PackageParser.Package pkg : mPackages.values()) {
9585                if (pkg != pkgInfo) {
9586                    // Only replace for packages on requested volume
9587                    final String volumeUuid = getVolumeUuidForPackage(pkg);
9588                    final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0)
9589                            && Objects.equals(replaceVolumeUuid, volumeUuid);
9590                    grantPermissionsLPw(pkg, replace, changingPkg);
9591                }
9592            }
9593        }
9594
9595        if (pkgInfo != null) {
9596            // Only replace for packages on requested volume
9597            final String volumeUuid = getVolumeUuidForPackage(pkgInfo);
9598            final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0)
9599                    && Objects.equals(replaceVolumeUuid, volumeUuid);
9600            grantPermissionsLPw(pkgInfo, replace, changingPkg);
9601        }
9602    }
9603
9604    private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace,
9605            String packageOfInterest) {
9606        // IMPORTANT: There are two types of permissions: install and runtime.
9607        // Install time permissions are granted when the app is installed to
9608        // all device users and users added in the future. Runtime permissions
9609        // are granted at runtime explicitly to specific users. Normal and signature
9610        // protected permissions are install time permissions. Dangerous permissions
9611        // are install permissions if the app's target SDK is Lollipop MR1 or older,
9612        // otherwise they are runtime permissions. This function does not manage
9613        // runtime permissions except for the case an app targeting Lollipop MR1
9614        // being upgraded to target a newer SDK, in which case dangerous permissions
9615        // are transformed from install time to runtime ones.
9616
9617        final PackageSetting ps = (PackageSetting) pkg.mExtras;
9618        if (ps == null) {
9619            return;
9620        }
9621
9622        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions");
9623
9624        PermissionsState permissionsState = ps.getPermissionsState();
9625        PermissionsState origPermissions = permissionsState;
9626
9627        final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
9628
9629        boolean runtimePermissionsRevoked = false;
9630        int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY;
9631
9632        boolean changedInstallPermission = false;
9633
9634        if (replace) {
9635            ps.installPermissionsFixed = false;
9636            if (!ps.isSharedUser()) {
9637                origPermissions = new PermissionsState(permissionsState);
9638                permissionsState.reset();
9639            } else {
9640                // We need to know only about runtime permission changes since the
9641                // calling code always writes the install permissions state but
9642                // the runtime ones are written only if changed. The only cases of
9643                // changed runtime permissions here are promotion of an install to
9644                // runtime and revocation of a runtime from a shared user.
9645                changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw(
9646                        ps.sharedUser, UserManagerService.getInstance().getUserIds());
9647                if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) {
9648                    runtimePermissionsRevoked = true;
9649                }
9650            }
9651        }
9652
9653        permissionsState.setGlobalGids(mGlobalGids);
9654
9655        final int N = pkg.requestedPermissions.size();
9656        for (int i=0; i<N; i++) {
9657            final String name = pkg.requestedPermissions.get(i);
9658            final BasePermission bp = mSettings.mPermissions.get(name);
9659
9660            if (DEBUG_INSTALL) {
9661                Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
9662            }
9663
9664            if (bp == null || bp.packageSetting == null) {
9665                if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
9666                    Slog.w(TAG, "Unknown permission " + name
9667                            + " in package " + pkg.packageName);
9668                }
9669                continue;
9670            }
9671
9672            final String perm = bp.name;
9673            boolean allowedSig = false;
9674            int grant = GRANT_DENIED;
9675
9676            // Keep track of app op permissions.
9677            if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
9678                ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name);
9679                if (pkgs == null) {
9680                    pkgs = new ArraySet<>();
9681                    mAppOpPermissionPackages.put(bp.name, pkgs);
9682                }
9683                pkgs.add(pkg.packageName);
9684            }
9685
9686            final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE;
9687            final boolean appSupportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion
9688                    >= Build.VERSION_CODES.M;
9689            switch (level) {
9690                case PermissionInfo.PROTECTION_NORMAL: {
9691                    // For all apps normal permissions are install time ones.
9692                    grant = GRANT_INSTALL;
9693                } break;
9694
9695                case PermissionInfo.PROTECTION_DANGEROUS: {
9696                    // If a permission review is required for legacy apps we represent
9697                    // their permissions as always granted runtime ones since we need
9698                    // to keep the review required permission flag per user while an
9699                    // install permission's state is shared across all users.
9700                    if (!appSupportsRuntimePermissions && !Build.PERMISSIONS_REVIEW_REQUIRED) {
9701                        // For legacy apps dangerous permissions are install time ones.
9702                        grant = GRANT_INSTALL;
9703                    } else if (origPermissions.hasInstallPermission(bp.name)) {
9704                        // For legacy apps that became modern, install becomes runtime.
9705                        grant = GRANT_UPGRADE;
9706                    } else if (mPromoteSystemApps
9707                            && isSystemApp(ps)
9708                            && mExistingSystemPackages.contains(ps.name)) {
9709                        // For legacy system apps, install becomes runtime.
9710                        // We cannot check hasInstallPermission() for system apps since those
9711                        // permissions were granted implicitly and not persisted pre-M.
9712                        grant = GRANT_UPGRADE;
9713                    } else {
9714                        // For modern apps keep runtime permissions unchanged.
9715                        grant = GRANT_RUNTIME;
9716                    }
9717                } break;
9718
9719                case PermissionInfo.PROTECTION_SIGNATURE: {
9720                    // For all apps signature permissions are install time ones.
9721                    allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions);
9722                    if (allowedSig) {
9723                        grant = GRANT_INSTALL;
9724                    }
9725                } break;
9726            }
9727
9728            if (DEBUG_INSTALL) {
9729                Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
9730            }
9731
9732            if (grant != GRANT_DENIED) {
9733                if (!isSystemApp(ps) && ps.installPermissionsFixed) {
9734                    // If this is an existing, non-system package, then
9735                    // we can't add any new permissions to it.
9736                    if (!allowedSig && !origPermissions.hasInstallPermission(perm)) {
9737                        // Except...  if this is a permission that was added
9738                        // to the platform (note: need to only do this when
9739                        // updating the platform).
9740                        if (!isNewPlatformPermissionForPackage(perm, pkg)) {
9741                            grant = GRANT_DENIED;
9742                        }
9743                    }
9744                }
9745
9746                switch (grant) {
9747                    case GRANT_INSTALL: {
9748                        // Revoke this as runtime permission to handle the case of
9749                        // a runtime permission being downgraded to an install one.
9750                        // Also in permission review mode we keep dangerous permissions
9751                        // for legacy apps
9752                        for (int userId : UserManagerService.getInstance().getUserIds()) {
9753                            if (origPermissions.getRuntimePermissionState(
9754                                    bp.name, userId) != null) {
9755                                // Revoke the runtime permission and clear the flags.
9756                                origPermissions.revokeRuntimePermission(bp, userId);
9757                                origPermissions.updatePermissionFlags(bp, userId,
9758                                      PackageManager.MASK_PERMISSION_FLAGS, 0);
9759                                // If we revoked a permission permission, we have to write.
9760                                changedRuntimePermissionUserIds = ArrayUtils.appendInt(
9761                                        changedRuntimePermissionUserIds, userId);
9762                            }
9763                        }
9764                        // Grant an install permission.
9765                        if (permissionsState.grantInstallPermission(bp) !=
9766                                PermissionsState.PERMISSION_OPERATION_FAILURE) {
9767                            changedInstallPermission = true;
9768                        }
9769                    } break;
9770
9771                    case GRANT_RUNTIME: {
9772                        // Grant previously granted runtime permissions.
9773                        for (int userId : UserManagerService.getInstance().getUserIds()) {
9774                            PermissionState permissionState = origPermissions
9775                                    .getRuntimePermissionState(bp.name, userId);
9776                            int flags = permissionState != null
9777                                    ? permissionState.getFlags() : 0;
9778                            if (origPermissions.hasRuntimePermission(bp.name, userId)) {
9779                                if (permissionsState.grantRuntimePermission(bp, userId) ==
9780                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
9781                                    // If we cannot put the permission as it was, we have to write.
9782                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
9783                                            changedRuntimePermissionUserIds, userId);
9784                                }
9785                                // If the app supports runtime permissions no need for a review.
9786                                if (Build.PERMISSIONS_REVIEW_REQUIRED
9787                                        && appSupportsRuntimePermissions
9788                                        && (flags & PackageManager
9789                                                .FLAG_PERMISSION_REVIEW_REQUIRED) != 0) {
9790                                    flags &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
9791                                    // Since we changed the flags, we have to write.
9792                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
9793                                            changedRuntimePermissionUserIds, userId);
9794                                }
9795                            } else if (Build.PERMISSIONS_REVIEW_REQUIRED
9796                                    && !appSupportsRuntimePermissions) {
9797                                // For legacy apps that need a permission review, every new
9798                                // runtime permission is granted but it is pending a review.
9799                                // We also need to review only platform defined runtime
9800                                // permissions as these are the only ones the platform knows
9801                                // how to disable the API to simulate revocation as legacy
9802                                // apps don't expect to run with revoked permissions.
9803                                if (PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage)) {
9804                                    if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
9805                                        flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
9806                                        // We changed the flags, hence have to write.
9807                                        changedRuntimePermissionUserIds = ArrayUtils.appendInt(
9808                                                changedRuntimePermissionUserIds, userId);
9809                                    }
9810                                }
9811                                if (permissionsState.grantRuntimePermission(bp, userId)
9812                                        != PermissionsState.PERMISSION_OPERATION_FAILURE) {
9813                                    // We changed the permission, hence have to write.
9814                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
9815                                            changedRuntimePermissionUserIds, userId);
9816                                }
9817                            }
9818                            // Propagate the permission flags.
9819                            permissionsState.updatePermissionFlags(bp, userId, flags, flags);
9820                        }
9821                    } break;
9822
9823                    case GRANT_UPGRADE: {
9824                        // Grant runtime permissions for a previously held install permission.
9825                        PermissionState permissionState = origPermissions
9826                                .getInstallPermissionState(bp.name);
9827                        final int flags = permissionState != null ? permissionState.getFlags() : 0;
9828
9829                        if (origPermissions.revokeInstallPermission(bp)
9830                                != PermissionsState.PERMISSION_OPERATION_FAILURE) {
9831                            // We will be transferring the permission flags, so clear them.
9832                            origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL,
9833                                    PackageManager.MASK_PERMISSION_FLAGS, 0);
9834                            changedInstallPermission = true;
9835                        }
9836
9837                        // If the permission is not to be promoted to runtime we ignore it and
9838                        // also its other flags as they are not applicable to install permissions.
9839                        if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) {
9840                            for (int userId : currentUserIds) {
9841                                if (permissionsState.grantRuntimePermission(bp, userId) !=
9842                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
9843                                    // Transfer the permission flags.
9844                                    permissionsState.updatePermissionFlags(bp, userId,
9845                                            flags, flags);
9846                                    // If we granted the permission, we have to write.
9847                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
9848                                            changedRuntimePermissionUserIds, userId);
9849                                }
9850                            }
9851                        }
9852                    } break;
9853
9854                    default: {
9855                        if (packageOfInterest == null
9856                                || packageOfInterest.equals(pkg.packageName)) {
9857                            Slog.w(TAG, "Not granting permission " + perm
9858                                    + " to package " + pkg.packageName
9859                                    + " because it was previously installed without");
9860                        }
9861                    } break;
9862                }
9863            } else {
9864                if (permissionsState.revokeInstallPermission(bp) !=
9865                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
9866                    // Also drop the permission flags.
9867                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
9868                            PackageManager.MASK_PERMISSION_FLAGS, 0);
9869                    changedInstallPermission = true;
9870                    Slog.i(TAG, "Un-granting permission " + perm
9871                            + " from package " + pkg.packageName
9872                            + " (protectionLevel=" + bp.protectionLevel
9873                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
9874                            + ")");
9875                } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) {
9876                    // Don't print warning for app op permissions, since it is fine for them
9877                    // not to be granted, there is a UI for the user to decide.
9878                    if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
9879                        Slog.w(TAG, "Not granting permission " + perm
9880                                + " to package " + pkg.packageName
9881                                + " (protectionLevel=" + bp.protectionLevel
9882                                + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
9883                                + ")");
9884                    }
9885                }
9886            }
9887        }
9888
9889        if ((changedInstallPermission || replace) && !ps.installPermissionsFixed &&
9890                !isSystemApp(ps) || isUpdatedSystemApp(ps)){
9891            // This is the first that we have heard about this package, so the
9892            // permissions we have now selected are fixed until explicitly
9893            // changed.
9894            ps.installPermissionsFixed = true;
9895        }
9896
9897        // Persist the runtime permissions state for users with changes. If permissions
9898        // were revoked because no app in the shared user declares them we have to
9899        // write synchronously to avoid losing runtime permissions state.
9900        for (int userId : changedRuntimePermissionUserIds) {
9901            mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked);
9902        }
9903
9904        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9905    }
9906
9907    private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) {
9908        boolean allowed = false;
9909        final int NP = PackageParser.NEW_PERMISSIONS.length;
9910        for (int ip=0; ip<NP; ip++) {
9911            final PackageParser.NewPermissionInfo npi
9912                    = PackageParser.NEW_PERMISSIONS[ip];
9913            if (npi.name.equals(perm)
9914                    && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
9915                allowed = true;
9916                Log.i(TAG, "Auto-granting " + perm + " to old pkg "
9917                        + pkg.packageName);
9918                break;
9919            }
9920        }
9921        return allowed;
9922    }
9923
9924    private boolean grantSignaturePermission(String perm, PackageParser.Package pkg,
9925            BasePermission bp, PermissionsState origPermissions) {
9926        boolean allowed;
9927        allowed = (compareSignatures(
9928                bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
9929                        == PackageManager.SIGNATURE_MATCH)
9930                || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
9931                        == PackageManager.SIGNATURE_MATCH);
9932        if (!allowed && (bp.protectionLevel
9933                & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0) {
9934            if (isSystemApp(pkg)) {
9935                // For updated system applications, a system permission
9936                // is granted only if it had been defined by the original application.
9937                if (pkg.isUpdatedSystemApp()) {
9938                    final PackageSetting sysPs = mSettings
9939                            .getDisabledSystemPkgLPr(pkg.packageName);
9940                    if (sysPs != null && sysPs.getPermissionsState().hasInstallPermission(perm)) {
9941                        // If the original was granted this permission, we take
9942                        // that grant decision as read and propagate it to the
9943                        // update.
9944                        if (sysPs.isPrivileged()) {
9945                            allowed = true;
9946                        }
9947                    } else {
9948                        // The system apk may have been updated with an older
9949                        // version of the one on the data partition, but which
9950                        // granted a new system permission that it didn't have
9951                        // before.  In this case we do want to allow the app to
9952                        // now get the new permission if the ancestral apk is
9953                        // privileged to get it.
9954                        if (sysPs != null && sysPs.pkg != null && sysPs.isPrivileged()) {
9955                            for (int j = 0; j < sysPs.pkg.requestedPermissions.size(); j++) {
9956                                if (perm.equals(sysPs.pkg.requestedPermissions.get(j))) {
9957                                    allowed = true;
9958                                    break;
9959                                }
9960                            }
9961                        }
9962                        // Also if a privileged parent package on the system image or any of
9963                        // its children requested a privileged permission, the updated child
9964                        // packages can also get the permission.
9965                        if (pkg.parentPackage != null) {
9966                            final PackageSetting disabledSysParentPs = mSettings
9967                                    .getDisabledSystemPkgLPr(pkg.parentPackage.packageName);
9968                            if (disabledSysParentPs != null && disabledSysParentPs.pkg != null
9969                                    && disabledSysParentPs.isPrivileged()) {
9970                                if (isPackageRequestingPermission(disabledSysParentPs.pkg, perm)) {
9971                                    allowed = true;
9972                                } else if (disabledSysParentPs.pkg.childPackages != null) {
9973                                    final int count = disabledSysParentPs.pkg.childPackages.size();
9974                                    for (int i = 0; i < count; i++) {
9975                                        PackageParser.Package disabledSysChildPkg =
9976                                                disabledSysParentPs.pkg.childPackages.get(i);
9977                                        if (isPackageRequestingPermission(disabledSysChildPkg,
9978                                                perm)) {
9979                                            allowed = true;
9980                                            break;
9981                                        }
9982                                    }
9983                                }
9984                            }
9985                        }
9986                    }
9987                } else {
9988                    allowed = isPrivilegedApp(pkg);
9989                }
9990            }
9991        }
9992        if (!allowed) {
9993            if (!allowed && (bp.protectionLevel
9994                    & PermissionInfo.PROTECTION_FLAG_PRE23) != 0
9995                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
9996                // If this was a previously normal/dangerous permission that got moved
9997                // to a system permission as part of the runtime permission redesign, then
9998                // we still want to blindly grant it to old apps.
9999                allowed = true;
10000            }
10001            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0
10002                    && pkg.packageName.equals(mRequiredInstallerPackage)) {
10003                // If this permission is to be granted to the system installer and
10004                // this app is an installer, then it gets the permission.
10005                allowed = true;
10006            }
10007            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0
10008                    && pkg.packageName.equals(mRequiredVerifierPackage)) {
10009                // If this permission is to be granted to the system verifier and
10010                // this app is a verifier, then it gets the permission.
10011                allowed = true;
10012            }
10013            if (!allowed && (bp.protectionLevel
10014                    & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0
10015                    && isSystemApp(pkg)) {
10016                // Any pre-installed system app is allowed to get this permission.
10017                allowed = true;
10018            }
10019            if (!allowed && (bp.protectionLevel
10020                    & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) {
10021                // For development permissions, a development permission
10022                // is granted only if it was already granted.
10023                allowed = origPermissions.hasInstallPermission(perm);
10024            }
10025            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_SETUP) != 0
10026                    && pkg.packageName.equals(mSetupWizardPackage)) {
10027                // If this permission is to be granted to the system setup wizard and
10028                // this app is a setup wizard, then it gets the permission.
10029                allowed = true;
10030            }
10031        }
10032        return allowed;
10033    }
10034
10035    private boolean isPackageRequestingPermission(PackageParser.Package pkg, String permission) {
10036        final int permCount = pkg.requestedPermissions.size();
10037        for (int j = 0; j < permCount; j++) {
10038            String requestedPermission = pkg.requestedPermissions.get(j);
10039            if (permission.equals(requestedPermission)) {
10040                return true;
10041            }
10042        }
10043        return false;
10044    }
10045
10046    final class ActivityIntentResolver
10047            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
10048        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
10049                boolean defaultOnly, int userId) {
10050            if (!sUserManager.exists(userId)) return null;
10051            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
10052            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
10053        }
10054
10055        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
10056                int userId) {
10057            if (!sUserManager.exists(userId)) return null;
10058            mFlags = flags;
10059            return super.queryIntent(intent, resolvedType,
10060                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
10061        }
10062
10063        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
10064                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
10065            if (!sUserManager.exists(userId)) return null;
10066            if (packageActivities == null) {
10067                return null;
10068            }
10069            mFlags = flags;
10070            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
10071            final int N = packageActivities.size();
10072            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
10073                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
10074
10075            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
10076            for (int i = 0; i < N; ++i) {
10077                intentFilters = packageActivities.get(i).intents;
10078                if (intentFilters != null && intentFilters.size() > 0) {
10079                    PackageParser.ActivityIntentInfo[] array =
10080                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
10081                    intentFilters.toArray(array);
10082                    listCut.add(array);
10083                }
10084            }
10085            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
10086        }
10087
10088        /**
10089         * Finds a privileged activity that matches the specified activity names.
10090         */
10091        private PackageParser.Activity findMatchingActivity(
10092                List<PackageParser.Activity> activityList, ActivityInfo activityInfo) {
10093            for (PackageParser.Activity sysActivity : activityList) {
10094                if (sysActivity.info.name.equals(activityInfo.name)) {
10095                    return sysActivity;
10096                }
10097                if (sysActivity.info.name.equals(activityInfo.targetActivity)) {
10098                    return sysActivity;
10099                }
10100                if (sysActivity.info.targetActivity != null) {
10101                    if (sysActivity.info.targetActivity.equals(activityInfo.name)) {
10102                        return sysActivity;
10103                    }
10104                    if (sysActivity.info.targetActivity.equals(activityInfo.targetActivity)) {
10105                        return sysActivity;
10106                    }
10107                }
10108            }
10109            return null;
10110        }
10111
10112        public class IterGenerator<E> {
10113            public Iterator<E> generate(ActivityIntentInfo info) {
10114                return null;
10115            }
10116        }
10117
10118        public class ActionIterGenerator extends IterGenerator<String> {
10119            @Override
10120            public Iterator<String> generate(ActivityIntentInfo info) {
10121                return info.actionsIterator();
10122            }
10123        }
10124
10125        public class CategoriesIterGenerator extends IterGenerator<String> {
10126            @Override
10127            public Iterator<String> generate(ActivityIntentInfo info) {
10128                return info.categoriesIterator();
10129            }
10130        }
10131
10132        public class SchemesIterGenerator extends IterGenerator<String> {
10133            @Override
10134            public Iterator<String> generate(ActivityIntentInfo info) {
10135                return info.schemesIterator();
10136            }
10137        }
10138
10139        public class AuthoritiesIterGenerator extends IterGenerator<IntentFilter.AuthorityEntry> {
10140            @Override
10141            public Iterator<IntentFilter.AuthorityEntry> generate(ActivityIntentInfo info) {
10142                return info.authoritiesIterator();
10143            }
10144        }
10145
10146        /**
10147         * <em>WARNING</em> for performance reasons, the passed in intentList WILL BE
10148         * MODIFIED. Do not pass in a list that should not be changed.
10149         */
10150        private <T> void getIntentListSubset(List<ActivityIntentInfo> intentList,
10151                IterGenerator<T> generator, Iterator<T> searchIterator) {
10152            // loop through the set of actions; every one must be found in the intent filter
10153            while (searchIterator.hasNext()) {
10154                // we must have at least one filter in the list to consider a match
10155                if (intentList.size() == 0) {
10156                    break;
10157                }
10158
10159                final T searchAction = searchIterator.next();
10160
10161                // loop through the set of intent filters
10162                final Iterator<ActivityIntentInfo> intentIter = intentList.iterator();
10163                while (intentIter.hasNext()) {
10164                    final ActivityIntentInfo intentInfo = intentIter.next();
10165                    boolean selectionFound = false;
10166
10167                    // loop through the intent filter's selection criteria; at least one
10168                    // of them must match the searched criteria
10169                    final Iterator<T> intentSelectionIter = generator.generate(intentInfo);
10170                    while (intentSelectionIter != null && intentSelectionIter.hasNext()) {
10171                        final T intentSelection = intentSelectionIter.next();
10172                        if (intentSelection != null && intentSelection.equals(searchAction)) {
10173                            selectionFound = true;
10174                            break;
10175                        }
10176                    }
10177
10178                    // the selection criteria wasn't found in this filter's set; this filter
10179                    // is not a potential match
10180                    if (!selectionFound) {
10181                        intentIter.remove();
10182                    }
10183                }
10184            }
10185        }
10186
10187        private boolean isProtectedAction(ActivityIntentInfo filter) {
10188            final Iterator<String> actionsIter = filter.actionsIterator();
10189            while (actionsIter != null && actionsIter.hasNext()) {
10190                final String filterAction = actionsIter.next();
10191                if (PROTECTED_ACTIONS.contains(filterAction)) {
10192                    return true;
10193                }
10194            }
10195            return false;
10196        }
10197
10198        /**
10199         * Adjusts the priority of the given intent filter according to policy.
10200         * <p>
10201         * <ul>
10202         * <li>The priority for non privileged applications is capped to '0'</li>
10203         * <li>The priority for protected actions on privileged applications is capped to '0'</li>
10204         * <li>The priority for unbundled updates to privileged applications is capped to the
10205         *      priority defined on the system partition</li>
10206         * </ul>
10207         * <p>
10208         * <em>NOTE:</em> There is one exception. For security reasons, the setup wizard is
10209         * allowed to obtain any priority on any action.
10210         */
10211        private void adjustPriority(
10212                List<PackageParser.Activity> systemActivities, ActivityIntentInfo intent) {
10213            // nothing to do; priority is fine as-is
10214            if (intent.getPriority() <= 0) {
10215                return;
10216            }
10217
10218            final ActivityInfo activityInfo = intent.activity.info;
10219            final ApplicationInfo applicationInfo = activityInfo.applicationInfo;
10220
10221            final boolean privilegedApp =
10222                    ((applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0);
10223            if (!privilegedApp) {
10224                // non-privileged applications can never define a priority >0
10225                Slog.w(TAG, "Non-privileged app; cap priority to 0;"
10226                        + " package: " + applicationInfo.packageName
10227                        + " activity: " + intent.activity.className
10228                        + " origPrio: " + intent.getPriority());
10229                intent.setPriority(0);
10230                return;
10231            }
10232
10233            if (systemActivities == null) {
10234                // the system package is not disabled; we're parsing the system partition
10235                if (isProtectedAction(intent)) {
10236                    if (mDeferProtectedFilters) {
10237                        // We can't deal with these just yet. No component should ever obtain a
10238                        // >0 priority for a protected actions, with ONE exception -- the setup
10239                        // wizard. The setup wizard, however, cannot be known until we're able to
10240                        // query it for the category CATEGORY_SETUP_WIZARD. Which we can't do
10241                        // until all intent filters have been processed. Chicken, meet egg.
10242                        // Let the filter temporarily have a high priority and rectify the
10243                        // priorities after all system packages have been scanned.
10244                        mProtectedFilters.add(intent);
10245                        if (DEBUG_FILTERS) {
10246                            Slog.i(TAG, "Protected action; save for later;"
10247                                    + " package: " + applicationInfo.packageName
10248                                    + " activity: " + intent.activity.className
10249                                    + " origPrio: " + intent.getPriority());
10250                        }
10251                        return;
10252                    } else {
10253                        if (DEBUG_FILTERS && mSetupWizardPackage == null) {
10254                            Slog.i(TAG, "No setup wizard;"
10255                                + " All protected intents capped to priority 0");
10256                        }
10257                        if (intent.activity.info.packageName.equals(mSetupWizardPackage)) {
10258                            if (DEBUG_FILTERS) {
10259                                Slog.i(TAG, "Found setup wizard;"
10260                                    + " allow priority " + intent.getPriority() + ";"
10261                                    + " package: " + intent.activity.info.packageName
10262                                    + " activity: " + intent.activity.className
10263                                    + " priority: " + intent.getPriority());
10264                            }
10265                            // setup wizard gets whatever it wants
10266                            return;
10267                        }
10268                        Slog.w(TAG, "Protected action; cap priority to 0;"
10269                                + " package: " + intent.activity.info.packageName
10270                                + " activity: " + intent.activity.className
10271                                + " origPrio: " + intent.getPriority());
10272                        intent.setPriority(0);
10273                        return;
10274                    }
10275                }
10276                // privileged apps on the system image get whatever priority they request
10277                return;
10278            }
10279
10280            // privileged app unbundled update ... try to find the same activity
10281            final PackageParser.Activity foundActivity =
10282                    findMatchingActivity(systemActivities, activityInfo);
10283            if (foundActivity == null) {
10284                // this is a new activity; it cannot obtain >0 priority
10285                if (DEBUG_FILTERS) {
10286                    Slog.i(TAG, "New activity; cap priority to 0;"
10287                            + " package: " + applicationInfo.packageName
10288                            + " activity: " + intent.activity.className
10289                            + " origPrio: " + intent.getPriority());
10290                }
10291                intent.setPriority(0);
10292                return;
10293            }
10294
10295            // found activity, now check for filter equivalence
10296
10297            // a shallow copy is enough; we modify the list, not its contents
10298            final List<ActivityIntentInfo> intentListCopy =
10299                    new ArrayList<>(foundActivity.intents);
10300            final List<ActivityIntentInfo> foundFilters = findFilters(intent);
10301
10302            // find matching action subsets
10303            final Iterator<String> actionsIterator = intent.actionsIterator();
10304            if (actionsIterator != null) {
10305                getIntentListSubset(
10306                        intentListCopy, new ActionIterGenerator(), actionsIterator);
10307                if (intentListCopy.size() == 0) {
10308                    // no more intents to match; we're not equivalent
10309                    if (DEBUG_FILTERS) {
10310                        Slog.i(TAG, "Mismatched action; cap priority to 0;"
10311                                + " package: " + applicationInfo.packageName
10312                                + " activity: " + intent.activity.className
10313                                + " origPrio: " + intent.getPriority());
10314                    }
10315                    intent.setPriority(0);
10316                    return;
10317                }
10318            }
10319
10320            // find matching category subsets
10321            final Iterator<String> categoriesIterator = intent.categoriesIterator();
10322            if (categoriesIterator != null) {
10323                getIntentListSubset(intentListCopy, new CategoriesIterGenerator(),
10324                        categoriesIterator);
10325                if (intentListCopy.size() == 0) {
10326                    // no more intents to match; we're not equivalent
10327                    if (DEBUG_FILTERS) {
10328                        Slog.i(TAG, "Mismatched category; cap priority to 0;"
10329                                + " package: " + applicationInfo.packageName
10330                                + " activity: " + intent.activity.className
10331                                + " origPrio: " + intent.getPriority());
10332                    }
10333                    intent.setPriority(0);
10334                    return;
10335                }
10336            }
10337
10338            // find matching schemes subsets
10339            final Iterator<String> schemesIterator = intent.schemesIterator();
10340            if (schemesIterator != null) {
10341                getIntentListSubset(intentListCopy, new SchemesIterGenerator(),
10342                        schemesIterator);
10343                if (intentListCopy.size() == 0) {
10344                    // no more intents to match; we're not equivalent
10345                    if (DEBUG_FILTERS) {
10346                        Slog.i(TAG, "Mismatched scheme; cap priority to 0;"
10347                                + " package: " + applicationInfo.packageName
10348                                + " activity: " + intent.activity.className
10349                                + " origPrio: " + intent.getPriority());
10350                    }
10351                    intent.setPriority(0);
10352                    return;
10353                }
10354            }
10355
10356            // find matching authorities subsets
10357            final Iterator<IntentFilter.AuthorityEntry>
10358                    authoritiesIterator = intent.authoritiesIterator();
10359            if (authoritiesIterator != null) {
10360                getIntentListSubset(intentListCopy,
10361                        new AuthoritiesIterGenerator(),
10362                        authoritiesIterator);
10363                if (intentListCopy.size() == 0) {
10364                    // no more intents to match; we're not equivalent
10365                    if (DEBUG_FILTERS) {
10366                        Slog.i(TAG, "Mismatched authority; cap priority to 0;"
10367                                + " package: " + applicationInfo.packageName
10368                                + " activity: " + intent.activity.className
10369                                + " origPrio: " + intent.getPriority());
10370                    }
10371                    intent.setPriority(0);
10372                    return;
10373                }
10374            }
10375
10376            // we found matching filter(s); app gets the max priority of all intents
10377            int cappedPriority = 0;
10378            for (int i = intentListCopy.size() - 1; i >= 0; --i) {
10379                cappedPriority = Math.max(cappedPriority, intentListCopy.get(i).getPriority());
10380            }
10381            if (intent.getPriority() > cappedPriority) {
10382                if (DEBUG_FILTERS) {
10383                    Slog.i(TAG, "Found matching filter(s);"
10384                            + " cap priority to " + cappedPriority + ";"
10385                            + " package: " + applicationInfo.packageName
10386                            + " activity: " + intent.activity.className
10387                            + " origPrio: " + intent.getPriority());
10388                }
10389                intent.setPriority(cappedPriority);
10390                return;
10391            }
10392            // all this for nothing; the requested priority was <= what was on the system
10393        }
10394
10395        public final void addActivity(PackageParser.Activity a, String type) {
10396            mActivities.put(a.getComponentName(), a);
10397            if (DEBUG_SHOW_INFO)
10398                Log.v(
10399                TAG, "  " + type + " " +
10400                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
10401            if (DEBUG_SHOW_INFO)
10402                Log.v(TAG, "    Class=" + a.info.name);
10403            final int NI = a.intents.size();
10404            for (int j=0; j<NI; j++) {
10405                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
10406                if ("activity".equals(type)) {
10407                    final PackageSetting ps =
10408                            mSettings.getDisabledSystemPkgLPr(intent.activity.info.packageName);
10409                    final List<PackageParser.Activity> systemActivities =
10410                            ps != null && ps.pkg != null ? ps.pkg.activities : null;
10411                    adjustPriority(systemActivities, intent);
10412                }
10413                if (DEBUG_SHOW_INFO) {
10414                    Log.v(TAG, "    IntentFilter:");
10415                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
10416                }
10417                if (!intent.debugCheck()) {
10418                    Log.w(TAG, "==> For Activity " + a.info.name);
10419                }
10420                addFilter(intent);
10421            }
10422        }
10423
10424        public final void removeActivity(PackageParser.Activity a, String type) {
10425            mActivities.remove(a.getComponentName());
10426            if (DEBUG_SHOW_INFO) {
10427                Log.v(TAG, "  " + type + " "
10428                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
10429                                : a.info.name) + ":");
10430                Log.v(TAG, "    Class=" + a.info.name);
10431            }
10432            final int NI = a.intents.size();
10433            for (int j=0; j<NI; j++) {
10434                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
10435                if (DEBUG_SHOW_INFO) {
10436                    Log.v(TAG, "    IntentFilter:");
10437                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
10438                }
10439                removeFilter(intent);
10440            }
10441        }
10442
10443        @Override
10444        protected boolean allowFilterResult(
10445                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
10446            ActivityInfo filterAi = filter.activity.info;
10447            for (int i=dest.size()-1; i>=0; i--) {
10448                ActivityInfo destAi = dest.get(i).activityInfo;
10449                if (destAi.name == filterAi.name
10450                        && destAi.packageName == filterAi.packageName) {
10451                    return false;
10452                }
10453            }
10454            return true;
10455        }
10456
10457        @Override
10458        protected ActivityIntentInfo[] newArray(int size) {
10459            return new ActivityIntentInfo[size];
10460        }
10461
10462        @Override
10463        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
10464            if (!sUserManager.exists(userId)) return true;
10465            PackageParser.Package p = filter.activity.owner;
10466            if (p != null) {
10467                PackageSetting ps = (PackageSetting)p.mExtras;
10468                if (ps != null) {
10469                    // System apps are never considered stopped for purposes of
10470                    // filtering, because there may be no way for the user to
10471                    // actually re-launch them.
10472                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
10473                            && ps.getStopped(userId);
10474                }
10475            }
10476            return false;
10477        }
10478
10479        @Override
10480        protected boolean isPackageForFilter(String packageName,
10481                PackageParser.ActivityIntentInfo info) {
10482            return packageName.equals(info.activity.owner.packageName);
10483        }
10484
10485        @Override
10486        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
10487                int match, int userId) {
10488            if (!sUserManager.exists(userId)) return null;
10489            if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) {
10490                return null;
10491            }
10492            final PackageParser.Activity activity = info.activity;
10493            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
10494            if (ps == null) {
10495                return null;
10496            }
10497            ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags,
10498                    ps.readUserState(userId), userId);
10499            if (ai == null) {
10500                return null;
10501            }
10502            final ResolveInfo res = new ResolveInfo();
10503            res.activityInfo = ai;
10504            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
10505                res.filter = info;
10506            }
10507            if (info != null) {
10508                res.handleAllWebDataURI = info.handleAllWebDataURI();
10509            }
10510            res.priority = info.getPriority();
10511            res.preferredOrder = activity.owner.mPreferredOrder;
10512            //System.out.println("Result: " + res.activityInfo.className +
10513            //                   " = " + res.priority);
10514            res.match = match;
10515            res.isDefault = info.hasDefault;
10516            res.labelRes = info.labelRes;
10517            res.nonLocalizedLabel = info.nonLocalizedLabel;
10518            if (userNeedsBadging(userId)) {
10519                res.noResourceId = true;
10520            } else {
10521                res.icon = info.icon;
10522            }
10523            res.iconResourceId = info.icon;
10524            res.system = res.activityInfo.applicationInfo.isSystemApp();
10525            return res;
10526        }
10527
10528        @Override
10529        protected void sortResults(List<ResolveInfo> results) {
10530            Collections.sort(results, mResolvePrioritySorter);
10531        }
10532
10533        @Override
10534        protected void dumpFilter(PrintWriter out, String prefix,
10535                PackageParser.ActivityIntentInfo filter) {
10536            out.print(prefix); out.print(
10537                    Integer.toHexString(System.identityHashCode(filter.activity)));
10538                    out.print(' ');
10539                    filter.activity.printComponentShortName(out);
10540                    out.print(" filter ");
10541                    out.println(Integer.toHexString(System.identityHashCode(filter)));
10542        }
10543
10544        @Override
10545        protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) {
10546            return filter.activity;
10547        }
10548
10549        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
10550            PackageParser.Activity activity = (PackageParser.Activity)label;
10551            out.print(prefix); out.print(
10552                    Integer.toHexString(System.identityHashCode(activity)));
10553                    out.print(' ');
10554                    activity.printComponentShortName(out);
10555            if (count > 1) {
10556                out.print(" ("); out.print(count); out.print(" filters)");
10557            }
10558            out.println();
10559        }
10560
10561        // Keys are String (activity class name), values are Activity.
10562        private final ArrayMap<ComponentName, PackageParser.Activity> mActivities
10563                = new ArrayMap<ComponentName, PackageParser.Activity>();
10564        private int mFlags;
10565    }
10566
10567    private final class ServiceIntentResolver
10568            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
10569        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
10570                boolean defaultOnly, int userId) {
10571            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
10572            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
10573        }
10574
10575        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
10576                int userId) {
10577            if (!sUserManager.exists(userId)) return null;
10578            mFlags = flags;
10579            return super.queryIntent(intent, resolvedType,
10580                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
10581        }
10582
10583        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
10584                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
10585            if (!sUserManager.exists(userId)) return null;
10586            if (packageServices == null) {
10587                return null;
10588            }
10589            mFlags = flags;
10590            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
10591            final int N = packageServices.size();
10592            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
10593                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
10594
10595            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
10596            for (int i = 0; i < N; ++i) {
10597                intentFilters = packageServices.get(i).intents;
10598                if (intentFilters != null && intentFilters.size() > 0) {
10599                    PackageParser.ServiceIntentInfo[] array =
10600                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
10601                    intentFilters.toArray(array);
10602                    listCut.add(array);
10603                }
10604            }
10605            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
10606        }
10607
10608        public final void addService(PackageParser.Service s) {
10609            mServices.put(s.getComponentName(), s);
10610            if (DEBUG_SHOW_INFO) {
10611                Log.v(TAG, "  "
10612                        + (s.info.nonLocalizedLabel != null
10613                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
10614                Log.v(TAG, "    Class=" + s.info.name);
10615            }
10616            final int NI = s.intents.size();
10617            int j;
10618            for (j=0; j<NI; j++) {
10619                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
10620                if (DEBUG_SHOW_INFO) {
10621                    Log.v(TAG, "    IntentFilter:");
10622                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
10623                }
10624                if (!intent.debugCheck()) {
10625                    Log.w(TAG, "==> For Service " + s.info.name);
10626                }
10627                addFilter(intent);
10628            }
10629        }
10630
10631        public final void removeService(PackageParser.Service s) {
10632            mServices.remove(s.getComponentName());
10633            if (DEBUG_SHOW_INFO) {
10634                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
10635                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
10636                Log.v(TAG, "    Class=" + s.info.name);
10637            }
10638            final int NI = s.intents.size();
10639            int j;
10640            for (j=0; j<NI; j++) {
10641                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
10642                if (DEBUG_SHOW_INFO) {
10643                    Log.v(TAG, "    IntentFilter:");
10644                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
10645                }
10646                removeFilter(intent);
10647            }
10648        }
10649
10650        @Override
10651        protected boolean allowFilterResult(
10652                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
10653            ServiceInfo filterSi = filter.service.info;
10654            for (int i=dest.size()-1; i>=0; i--) {
10655                ServiceInfo destAi = dest.get(i).serviceInfo;
10656                if (destAi.name == filterSi.name
10657                        && destAi.packageName == filterSi.packageName) {
10658                    return false;
10659                }
10660            }
10661            return true;
10662        }
10663
10664        @Override
10665        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
10666            return new PackageParser.ServiceIntentInfo[size];
10667        }
10668
10669        @Override
10670        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
10671            if (!sUserManager.exists(userId)) return true;
10672            PackageParser.Package p = filter.service.owner;
10673            if (p != null) {
10674                PackageSetting ps = (PackageSetting)p.mExtras;
10675                if (ps != null) {
10676                    // System apps are never considered stopped for purposes of
10677                    // filtering, because there may be no way for the user to
10678                    // actually re-launch them.
10679                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
10680                            && ps.getStopped(userId);
10681                }
10682            }
10683            return false;
10684        }
10685
10686        @Override
10687        protected boolean isPackageForFilter(String packageName,
10688                PackageParser.ServiceIntentInfo info) {
10689            return packageName.equals(info.service.owner.packageName);
10690        }
10691
10692        @Override
10693        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
10694                int match, int userId) {
10695            if (!sUserManager.exists(userId)) return null;
10696            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
10697            if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) {
10698                return null;
10699            }
10700            final PackageParser.Service service = info.service;
10701            PackageSetting ps = (PackageSetting) service.owner.mExtras;
10702            if (ps == null) {
10703                return null;
10704            }
10705            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
10706                    ps.readUserState(userId), userId);
10707            if (si == null) {
10708                return null;
10709            }
10710            final ResolveInfo res = new ResolveInfo();
10711            res.serviceInfo = si;
10712            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
10713                res.filter = filter;
10714            }
10715            res.priority = info.getPriority();
10716            res.preferredOrder = service.owner.mPreferredOrder;
10717            res.match = match;
10718            res.isDefault = info.hasDefault;
10719            res.labelRes = info.labelRes;
10720            res.nonLocalizedLabel = info.nonLocalizedLabel;
10721            res.icon = info.icon;
10722            res.system = res.serviceInfo.applicationInfo.isSystemApp();
10723            return res;
10724        }
10725
10726        @Override
10727        protected void sortResults(List<ResolveInfo> results) {
10728            Collections.sort(results, mResolvePrioritySorter);
10729        }
10730
10731        @Override
10732        protected void dumpFilter(PrintWriter out, String prefix,
10733                PackageParser.ServiceIntentInfo filter) {
10734            out.print(prefix); out.print(
10735                    Integer.toHexString(System.identityHashCode(filter.service)));
10736                    out.print(' ');
10737                    filter.service.printComponentShortName(out);
10738                    out.print(" filter ");
10739                    out.println(Integer.toHexString(System.identityHashCode(filter)));
10740        }
10741
10742        @Override
10743        protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) {
10744            return filter.service;
10745        }
10746
10747        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
10748            PackageParser.Service service = (PackageParser.Service)label;
10749            out.print(prefix); out.print(
10750                    Integer.toHexString(System.identityHashCode(service)));
10751                    out.print(' ');
10752                    service.printComponentShortName(out);
10753            if (count > 1) {
10754                out.print(" ("); out.print(count); out.print(" filters)");
10755            }
10756            out.println();
10757        }
10758
10759//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
10760//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
10761//            final List<ResolveInfo> retList = Lists.newArrayList();
10762//            while (i.hasNext()) {
10763//                final ResolveInfo resolveInfo = (ResolveInfo) i;
10764//                if (isEnabledLP(resolveInfo.serviceInfo)) {
10765//                    retList.add(resolveInfo);
10766//                }
10767//            }
10768//            return retList;
10769//        }
10770
10771        // Keys are String (activity class name), values are Activity.
10772        private final ArrayMap<ComponentName, PackageParser.Service> mServices
10773                = new ArrayMap<ComponentName, PackageParser.Service>();
10774        private int mFlags;
10775    };
10776
10777    private final class ProviderIntentResolver
10778            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
10779        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
10780                boolean defaultOnly, int userId) {
10781            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
10782            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
10783        }
10784
10785        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
10786                int userId) {
10787            if (!sUserManager.exists(userId))
10788                return null;
10789            mFlags = flags;
10790            return super.queryIntent(intent, resolvedType,
10791                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
10792        }
10793
10794        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
10795                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
10796            if (!sUserManager.exists(userId))
10797                return null;
10798            if (packageProviders == null) {
10799                return null;
10800            }
10801            mFlags = flags;
10802            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
10803            final int N = packageProviders.size();
10804            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
10805                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
10806
10807            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
10808            for (int i = 0; i < N; ++i) {
10809                intentFilters = packageProviders.get(i).intents;
10810                if (intentFilters != null && intentFilters.size() > 0) {
10811                    PackageParser.ProviderIntentInfo[] array =
10812                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
10813                    intentFilters.toArray(array);
10814                    listCut.add(array);
10815                }
10816            }
10817            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
10818        }
10819
10820        public final void addProvider(PackageParser.Provider p) {
10821            if (mProviders.containsKey(p.getComponentName())) {
10822                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
10823                return;
10824            }
10825
10826            mProviders.put(p.getComponentName(), p);
10827            if (DEBUG_SHOW_INFO) {
10828                Log.v(TAG, "  "
10829                        + (p.info.nonLocalizedLabel != null
10830                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
10831                Log.v(TAG, "    Class=" + p.info.name);
10832            }
10833            final int NI = p.intents.size();
10834            int j;
10835            for (j = 0; j < NI; j++) {
10836                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
10837                if (DEBUG_SHOW_INFO) {
10838                    Log.v(TAG, "    IntentFilter:");
10839                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
10840                }
10841                if (!intent.debugCheck()) {
10842                    Log.w(TAG, "==> For Provider " + p.info.name);
10843                }
10844                addFilter(intent);
10845            }
10846        }
10847
10848        public final void removeProvider(PackageParser.Provider p) {
10849            mProviders.remove(p.getComponentName());
10850            if (DEBUG_SHOW_INFO) {
10851                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
10852                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
10853                Log.v(TAG, "    Class=" + p.info.name);
10854            }
10855            final int NI = p.intents.size();
10856            int j;
10857            for (j = 0; j < NI; j++) {
10858                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
10859                if (DEBUG_SHOW_INFO) {
10860                    Log.v(TAG, "    IntentFilter:");
10861                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
10862                }
10863                removeFilter(intent);
10864            }
10865        }
10866
10867        @Override
10868        protected boolean allowFilterResult(
10869                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
10870            ProviderInfo filterPi = filter.provider.info;
10871            for (int i = dest.size() - 1; i >= 0; i--) {
10872                ProviderInfo destPi = dest.get(i).providerInfo;
10873                if (destPi.name == filterPi.name
10874                        && destPi.packageName == filterPi.packageName) {
10875                    return false;
10876                }
10877            }
10878            return true;
10879        }
10880
10881        @Override
10882        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
10883            return new PackageParser.ProviderIntentInfo[size];
10884        }
10885
10886        @Override
10887        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
10888            if (!sUserManager.exists(userId))
10889                return true;
10890            PackageParser.Package p = filter.provider.owner;
10891            if (p != null) {
10892                PackageSetting ps = (PackageSetting) p.mExtras;
10893                if (ps != null) {
10894                    // System apps are never considered stopped for purposes of
10895                    // filtering, because there may be no way for the user to
10896                    // actually re-launch them.
10897                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
10898                            && ps.getStopped(userId);
10899                }
10900            }
10901            return false;
10902        }
10903
10904        @Override
10905        protected boolean isPackageForFilter(String packageName,
10906                PackageParser.ProviderIntentInfo info) {
10907            return packageName.equals(info.provider.owner.packageName);
10908        }
10909
10910        @Override
10911        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
10912                int match, int userId) {
10913            if (!sUserManager.exists(userId))
10914                return null;
10915            final PackageParser.ProviderIntentInfo info = filter;
10916            if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) {
10917                return null;
10918            }
10919            final PackageParser.Provider provider = info.provider;
10920            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
10921            if (ps == null) {
10922                return null;
10923            }
10924            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
10925                    ps.readUserState(userId), userId);
10926            if (pi == null) {
10927                return null;
10928            }
10929            final ResolveInfo res = new ResolveInfo();
10930            res.providerInfo = pi;
10931            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
10932                res.filter = filter;
10933            }
10934            res.priority = info.getPriority();
10935            res.preferredOrder = provider.owner.mPreferredOrder;
10936            res.match = match;
10937            res.isDefault = info.hasDefault;
10938            res.labelRes = info.labelRes;
10939            res.nonLocalizedLabel = info.nonLocalizedLabel;
10940            res.icon = info.icon;
10941            res.system = res.providerInfo.applicationInfo.isSystemApp();
10942            return res;
10943        }
10944
10945        @Override
10946        protected void sortResults(List<ResolveInfo> results) {
10947            Collections.sort(results, mResolvePrioritySorter);
10948        }
10949
10950        @Override
10951        protected void dumpFilter(PrintWriter out, String prefix,
10952                PackageParser.ProviderIntentInfo filter) {
10953            out.print(prefix);
10954            out.print(
10955                    Integer.toHexString(System.identityHashCode(filter.provider)));
10956            out.print(' ');
10957            filter.provider.printComponentShortName(out);
10958            out.print(" filter ");
10959            out.println(Integer.toHexString(System.identityHashCode(filter)));
10960        }
10961
10962        @Override
10963        protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) {
10964            return filter.provider;
10965        }
10966
10967        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
10968            PackageParser.Provider provider = (PackageParser.Provider)label;
10969            out.print(prefix); out.print(
10970                    Integer.toHexString(System.identityHashCode(provider)));
10971                    out.print(' ');
10972                    provider.printComponentShortName(out);
10973            if (count > 1) {
10974                out.print(" ("); out.print(count); out.print(" filters)");
10975            }
10976            out.println();
10977        }
10978
10979        private final ArrayMap<ComponentName, PackageParser.Provider> mProviders
10980                = new ArrayMap<ComponentName, PackageParser.Provider>();
10981        private int mFlags;
10982    }
10983
10984    private static final class EphemeralIntentResolver
10985            extends IntentResolver<EphemeralResolveIntentInfo, EphemeralResolveInfo> {
10986        @Override
10987        protected EphemeralResolveIntentInfo[] newArray(int size) {
10988            return new EphemeralResolveIntentInfo[size];
10989        }
10990
10991        @Override
10992        protected boolean isPackageForFilter(String packageName, EphemeralResolveIntentInfo info) {
10993            return true;
10994        }
10995
10996        @Override
10997        protected EphemeralResolveInfo newResult(EphemeralResolveIntentInfo info, int match,
10998                int userId) {
10999            if (!sUserManager.exists(userId)) {
11000                return null;
11001            }
11002            return info.getEphemeralResolveInfo();
11003        }
11004    }
11005
11006    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
11007            new Comparator<ResolveInfo>() {
11008        public int compare(ResolveInfo r1, ResolveInfo r2) {
11009            int v1 = r1.priority;
11010            int v2 = r2.priority;
11011            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
11012            if (v1 != v2) {
11013                return (v1 > v2) ? -1 : 1;
11014            }
11015            v1 = r1.preferredOrder;
11016            v2 = r2.preferredOrder;
11017            if (v1 != v2) {
11018                return (v1 > v2) ? -1 : 1;
11019            }
11020            if (r1.isDefault != r2.isDefault) {
11021                return r1.isDefault ? -1 : 1;
11022            }
11023            v1 = r1.match;
11024            v2 = r2.match;
11025            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
11026            if (v1 != v2) {
11027                return (v1 > v2) ? -1 : 1;
11028            }
11029            if (r1.system != r2.system) {
11030                return r1.system ? -1 : 1;
11031            }
11032            if (r1.activityInfo != null) {
11033                return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName);
11034            }
11035            if (r1.serviceInfo != null) {
11036                return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName);
11037            }
11038            if (r1.providerInfo != null) {
11039                return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName);
11040            }
11041            return 0;
11042        }
11043    };
11044
11045    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
11046            new Comparator<ProviderInfo>() {
11047        public int compare(ProviderInfo p1, ProviderInfo p2) {
11048            final int v1 = p1.initOrder;
11049            final int v2 = p2.initOrder;
11050            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
11051        }
11052    };
11053
11054    final void sendPackageBroadcast(final String action, final String pkg, final Bundle extras,
11055            final int flags, final String targetPkg, final IIntentReceiver finishedReceiver,
11056            final int[] userIds) {
11057        mHandler.post(new Runnable() {
11058            @Override
11059            public void run() {
11060                try {
11061                    final IActivityManager am = ActivityManagerNative.getDefault();
11062                    if (am == null) return;
11063                    final int[] resolvedUserIds;
11064                    if (userIds == null) {
11065                        resolvedUserIds = am.getRunningUserIds();
11066                    } else {
11067                        resolvedUserIds = userIds;
11068                    }
11069                    for (int id : resolvedUserIds) {
11070                        final Intent intent = new Intent(action,
11071                                pkg != null ? Uri.fromParts("package", pkg, null) : null);
11072                        if (extras != null) {
11073                            intent.putExtras(extras);
11074                        }
11075                        if (targetPkg != null) {
11076                            intent.setPackage(targetPkg);
11077                        }
11078                        // Modify the UID when posting to other users
11079                        int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
11080                        if (uid > 0 && UserHandle.getUserId(uid) != id) {
11081                            uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
11082                            intent.putExtra(Intent.EXTRA_UID, uid);
11083                        }
11084                        intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
11085                        intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags);
11086                        if (DEBUG_BROADCASTS) {
11087                            RuntimeException here = new RuntimeException("here");
11088                            here.fillInStackTrace();
11089                            Slog.d(TAG, "Sending to user " + id + ": "
11090                                    + intent.toShortString(false, true, false, false)
11091                                    + " " + intent.getExtras(), here);
11092                        }
11093                        am.broadcastIntent(null, intent, null, finishedReceiver,
11094                                0, null, null, null, android.app.AppOpsManager.OP_NONE,
11095                                null, finishedReceiver != null, false, id);
11096                    }
11097                } catch (RemoteException ex) {
11098                }
11099            }
11100        });
11101    }
11102
11103    /**
11104     * Check if the external storage media is available. This is true if there
11105     * is a mounted external storage medium or if the external storage is
11106     * emulated.
11107     */
11108    private boolean isExternalMediaAvailable() {
11109        return mMediaMounted || Environment.isExternalStorageEmulated();
11110    }
11111
11112    @Override
11113    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
11114        // writer
11115        synchronized (mPackages) {
11116            if (!isExternalMediaAvailable()) {
11117                // If the external storage is no longer mounted at this point,
11118                // the caller may not have been able to delete all of this
11119                // packages files and can not delete any more.  Bail.
11120                return null;
11121            }
11122            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
11123            if (lastPackage != null) {
11124                pkgs.remove(lastPackage);
11125            }
11126            if (pkgs.size() > 0) {
11127                return pkgs.get(0);
11128            }
11129        }
11130        return null;
11131    }
11132
11133    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
11134        final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
11135                userId, andCode ? 1 : 0, packageName);
11136        if (mSystemReady) {
11137            msg.sendToTarget();
11138        } else {
11139            if (mPostSystemReadyMessages == null) {
11140                mPostSystemReadyMessages = new ArrayList<>();
11141            }
11142            mPostSystemReadyMessages.add(msg);
11143        }
11144    }
11145
11146    void startCleaningPackages() {
11147        // reader
11148        if (!isExternalMediaAvailable()) {
11149            return;
11150        }
11151        synchronized (mPackages) {
11152            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
11153                return;
11154            }
11155        }
11156        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
11157        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
11158        IActivityManager am = ActivityManagerNative.getDefault();
11159        if (am != null) {
11160            try {
11161                am.startService(null, intent, null, mContext.getOpPackageName(),
11162                        UserHandle.USER_SYSTEM);
11163            } catch (RemoteException e) {
11164            }
11165        }
11166    }
11167
11168    @Override
11169    public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer,
11170            int installFlags, String installerPackageName, int userId) {
11171        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
11172
11173        final int callingUid = Binder.getCallingUid();
11174        enforceCrossUserPermission(callingUid, userId,
11175                true /* requireFullPermission */, true /* checkShell */, "installPackageAsUser");
11176
11177        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
11178            try {
11179                if (observer != null) {
11180                    observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null);
11181                }
11182            } catch (RemoteException re) {
11183            }
11184            return;
11185        }
11186
11187        if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) {
11188            installFlags |= PackageManager.INSTALL_FROM_ADB;
11189
11190        } else {
11191            // Caller holds INSTALL_PACKAGES permission, so we're less strict
11192            // about installerPackageName.
11193
11194            installFlags &= ~PackageManager.INSTALL_FROM_ADB;
11195            installFlags &= ~PackageManager.INSTALL_ALL_USERS;
11196        }
11197
11198        UserHandle user;
11199        if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) {
11200            user = UserHandle.ALL;
11201        } else {
11202            user = new UserHandle(userId);
11203        }
11204
11205        // Only system components can circumvent runtime permissions when installing.
11206        if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0
11207                && mContext.checkCallingOrSelfPermission(Manifest.permission
11208                .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) {
11209            throw new SecurityException("You need the "
11210                    + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission "
11211                    + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag");
11212        }
11213
11214        final File originFile = new File(originPath);
11215        final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile);
11216
11217        final Message msg = mHandler.obtainMessage(INIT_COPY);
11218        final VerificationInfo verificationInfo = new VerificationInfo(
11219                null /*originatingUri*/, null /*referrer*/, -1 /*originatingUid*/, callingUid);
11220        final InstallParams params = new InstallParams(origin, null /*moveInfo*/, observer,
11221                installFlags, installerPackageName, null /*volumeUuid*/, verificationInfo, user,
11222                null /*packageAbiOverride*/, null /*grantedPermissions*/,
11223                null /*certificates*/);
11224        params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params));
11225        msg.obj = params;
11226
11227        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser",
11228                System.identityHashCode(msg.obj));
11229        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
11230                System.identityHashCode(msg.obj));
11231
11232        mHandler.sendMessage(msg);
11233    }
11234
11235    void installStage(String packageName, File stagedDir, String stagedCid,
11236            IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams,
11237            String installerPackageName, int installerUid, UserHandle user,
11238            Certificate[][] certificates) {
11239        if (DEBUG_EPHEMERAL) {
11240            if ((sessionParams.installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) {
11241                Slog.d(TAG, "Ephemeral install of " + packageName);
11242            }
11243        }
11244        final VerificationInfo verificationInfo = new VerificationInfo(
11245                sessionParams.originatingUri, sessionParams.referrerUri,
11246                sessionParams.originatingUid, installerUid);
11247
11248        final OriginInfo origin;
11249        if (stagedDir != null) {
11250            origin = OriginInfo.fromStagedFile(stagedDir);
11251        } else {
11252            origin = OriginInfo.fromStagedContainer(stagedCid);
11253        }
11254
11255        final Message msg = mHandler.obtainMessage(INIT_COPY);
11256        final InstallParams params = new InstallParams(origin, null, observer,
11257                sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid,
11258                verificationInfo, user, sessionParams.abiOverride,
11259                sessionParams.grantedRuntimePermissions, certificates);
11260        params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params));
11261        msg.obj = params;
11262
11263        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage",
11264                System.identityHashCode(msg.obj));
11265        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
11266                System.identityHashCode(msg.obj));
11267
11268        mHandler.sendMessage(msg);
11269    }
11270
11271    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting,
11272            int userId) {
11273        final boolean isSystem = isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
11274        sendPackageAddedForUser(packageName, isSystem, pkgSetting.appId, userId);
11275    }
11276
11277    private void sendPackageAddedForUser(String packageName, boolean isSystem,
11278            int appId, int userId) {
11279        Bundle extras = new Bundle(1);
11280        extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, appId));
11281
11282        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
11283                packageName, extras, 0, null, null, new int[] {userId});
11284        try {
11285            IActivityManager am = ActivityManagerNative.getDefault();
11286            if (isSystem && am.isUserRunning(userId, 0)) {
11287                // The just-installed/enabled app is bundled on the system, so presumed
11288                // to be able to run automatically without needing an explicit launch.
11289                // Send it a BOOT_COMPLETED if it would ordinarily have gotten one.
11290                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED)
11291                        .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES)
11292                        .setPackage(packageName);
11293                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null,
11294                        android.app.AppOpsManager.OP_NONE, null, false, false, userId);
11295            }
11296        } catch (RemoteException e) {
11297            // shouldn't happen
11298            Slog.w(TAG, "Unable to bootstrap installed package", e);
11299        }
11300    }
11301
11302    @Override
11303    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
11304            int userId) {
11305        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
11306        PackageSetting pkgSetting;
11307        final int uid = Binder.getCallingUid();
11308        enforceCrossUserPermission(uid, userId,
11309                true /* requireFullPermission */, true /* checkShell */,
11310                "setApplicationHiddenSetting for user " + userId);
11311
11312        if (hidden && isPackageDeviceAdmin(packageName, userId)) {
11313            Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
11314            return false;
11315        }
11316
11317        long callingId = Binder.clearCallingIdentity();
11318        try {
11319            boolean sendAdded = false;
11320            boolean sendRemoved = false;
11321            // writer
11322            synchronized (mPackages) {
11323                pkgSetting = mSettings.mPackages.get(packageName);
11324                if (pkgSetting == null) {
11325                    return false;
11326                }
11327                if (pkgSetting.getHidden(userId) != hidden) {
11328                    pkgSetting.setHidden(hidden, userId);
11329                    mSettings.writePackageRestrictionsLPr(userId);
11330                    if (hidden) {
11331                        sendRemoved = true;
11332                    } else {
11333                        sendAdded = true;
11334                    }
11335                }
11336            }
11337            if (sendAdded) {
11338                sendPackageAddedForUser(packageName, pkgSetting, userId);
11339                return true;
11340            }
11341            if (sendRemoved) {
11342                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
11343                        "hiding pkg");
11344                sendApplicationHiddenForUser(packageName, pkgSetting, userId);
11345                return true;
11346            }
11347        } finally {
11348            Binder.restoreCallingIdentity(callingId);
11349        }
11350        return false;
11351    }
11352
11353    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
11354            int userId) {
11355        final PackageRemovedInfo info = new PackageRemovedInfo();
11356        info.removedPackage = packageName;
11357        info.removedUsers = new int[] {userId};
11358        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
11359        info.sendPackageRemovedBroadcasts(true /*killApp*/);
11360    }
11361
11362    private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended) {
11363        if (pkgList.length > 0) {
11364            Bundle extras = new Bundle(1);
11365            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
11366
11367            sendPackageBroadcast(
11368                    suspended ? Intent.ACTION_PACKAGES_SUSPENDED
11369                            : Intent.ACTION_PACKAGES_UNSUSPENDED,
11370                    null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null,
11371                    new int[] {userId});
11372        }
11373    }
11374
11375    /**
11376     * Returns true if application is not found or there was an error. Otherwise it returns
11377     * the hidden state of the package for the given user.
11378     */
11379    @Override
11380    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
11381        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
11382        enforceCrossUserPermission(Binder.getCallingUid(), userId,
11383                true /* requireFullPermission */, false /* checkShell */,
11384                "getApplicationHidden for user " + userId);
11385        PackageSetting pkgSetting;
11386        long callingId = Binder.clearCallingIdentity();
11387        try {
11388            // writer
11389            synchronized (mPackages) {
11390                pkgSetting = mSettings.mPackages.get(packageName);
11391                if (pkgSetting == null) {
11392                    return true;
11393                }
11394                return pkgSetting.getHidden(userId);
11395            }
11396        } finally {
11397            Binder.restoreCallingIdentity(callingId);
11398        }
11399    }
11400
11401    /**
11402     * @hide
11403     */
11404    @Override
11405    public int installExistingPackageAsUser(String packageName, int userId) {
11406        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
11407                null);
11408        PackageSetting pkgSetting;
11409        final int uid = Binder.getCallingUid();
11410        enforceCrossUserPermission(uid, userId,
11411                true /* requireFullPermission */, true /* checkShell */,
11412                "installExistingPackage for user " + userId);
11413        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
11414            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
11415        }
11416
11417        long callingId = Binder.clearCallingIdentity();
11418        try {
11419            boolean installed = false;
11420
11421            // writer
11422            synchronized (mPackages) {
11423                pkgSetting = mSettings.mPackages.get(packageName);
11424                if (pkgSetting == null) {
11425                    return PackageManager.INSTALL_FAILED_INVALID_URI;
11426                }
11427                if (!pkgSetting.getInstalled(userId)) {
11428                    pkgSetting.setInstalled(true, userId);
11429                    pkgSetting.setHidden(false, userId);
11430                    mSettings.writePackageRestrictionsLPr(userId);
11431                    installed = true;
11432                }
11433            }
11434
11435            if (installed) {
11436                if (pkgSetting.pkg != null) {
11437                    synchronized (mInstallLock) {
11438                        // We don't need to freeze for a brand new install
11439                        prepareAppDataAfterInstallLIF(pkgSetting.pkg);
11440                    }
11441                }
11442                sendPackageAddedForUser(packageName, pkgSetting, userId);
11443            }
11444        } finally {
11445            Binder.restoreCallingIdentity(callingId);
11446        }
11447
11448        return PackageManager.INSTALL_SUCCEEDED;
11449    }
11450
11451    boolean isUserRestricted(int userId, String restrictionKey) {
11452        Bundle restrictions = sUserManager.getUserRestrictions(userId);
11453        if (restrictions.getBoolean(restrictionKey, false)) {
11454            Log.w(TAG, "User is restricted: " + restrictionKey);
11455            return true;
11456        }
11457        return false;
11458    }
11459
11460    @Override
11461    public String[] setPackagesSuspendedAsUser(String[] packageNames, boolean suspended,
11462            int userId) {
11463        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
11464        enforceCrossUserPermission(Binder.getCallingUid(), userId,
11465                true /* requireFullPermission */, true /* checkShell */,
11466                "setPackagesSuspended for user " + userId);
11467
11468        if (ArrayUtils.isEmpty(packageNames)) {
11469            return packageNames;
11470        }
11471
11472        // List of package names for whom the suspended state has changed.
11473        List<String> changedPackages = new ArrayList<>(packageNames.length);
11474        // List of package names for whom the suspended state is not set as requested in this
11475        // method.
11476        List<String> unactionedPackages = new ArrayList<>(packageNames.length);
11477        for (int i = 0; i < packageNames.length; i++) {
11478            String packageName = packageNames[i];
11479            long callingId = Binder.clearCallingIdentity();
11480            try {
11481                boolean changed = false;
11482                final int appId;
11483                synchronized (mPackages) {
11484                    final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
11485                    if (pkgSetting == null) {
11486                        Slog.w(TAG, "Could not find package setting for package \"" + packageName
11487                                + "\". Skipping suspending/un-suspending.");
11488                        unactionedPackages.add(packageName);
11489                        continue;
11490                    }
11491                    appId = pkgSetting.appId;
11492                    if (pkgSetting.getSuspended(userId) != suspended) {
11493                        if (!canSuspendPackageForUserLocked(packageName, userId)) {
11494                            unactionedPackages.add(packageName);
11495                            continue;
11496                        }
11497                        pkgSetting.setSuspended(suspended, userId);
11498                        mSettings.writePackageRestrictionsLPr(userId);
11499                        changed = true;
11500                        changedPackages.add(packageName);
11501                    }
11502                }
11503
11504                if (changed && suspended) {
11505                    killApplication(packageName, UserHandle.getUid(userId, appId),
11506                            "suspending package");
11507                }
11508            } finally {
11509                Binder.restoreCallingIdentity(callingId);
11510            }
11511        }
11512
11513        if (!changedPackages.isEmpty()) {
11514            sendPackagesSuspendedForUser(changedPackages.toArray(
11515                    new String[changedPackages.size()]), userId, suspended);
11516        }
11517
11518        return unactionedPackages.toArray(new String[unactionedPackages.size()]);
11519    }
11520
11521    @Override
11522    public boolean isPackageSuspendedForUser(String packageName, int userId) {
11523        enforceCrossUserPermission(Binder.getCallingUid(), userId,
11524                true /* requireFullPermission */, false /* checkShell */,
11525                "isPackageSuspendedForUser for user " + userId);
11526        synchronized (mPackages) {
11527            final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
11528            if (pkgSetting == null) {
11529                throw new IllegalArgumentException("Unknown target package: " + packageName);
11530            }
11531            return pkgSetting.getSuspended(userId);
11532        }
11533    }
11534
11535    /**
11536     * TODO: cache and disallow blocking the active dialer.
11537     *
11538     * @see also DefaultPermissionGrantPolicy#grantDefaultSystemHandlerPermissions
11539     */
11540    private boolean canSuspendPackageForUserLocked(String packageName, int userId) {
11541        if (isPackageDeviceAdmin(packageName, userId)) {
11542            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
11543                    + "\": has an active device admin");
11544            return false;
11545        }
11546
11547        String activeLauncherPackageName = getActiveLauncherPackageName(userId);
11548        if (packageName.equals(activeLauncherPackageName)) {
11549            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
11550                    + "\": contains the active launcher");
11551            return false;
11552        }
11553
11554        if (packageName.equals(mRequiredInstallerPackage)) {
11555            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
11556                    + "\": required for package installation");
11557            return false;
11558        }
11559
11560        if (packageName.equals(mRequiredVerifierPackage)) {
11561            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
11562                    + "\": required for package verification");
11563            return false;
11564        }
11565
11566        final PackageParser.Package pkg = mPackages.get(packageName);
11567        if (pkg != null && isPrivilegedApp(pkg)) {
11568            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
11569                    + "\": is a privileged app");
11570            return false;
11571        }
11572
11573        return true;
11574    }
11575
11576    private String getActiveLauncherPackageName(int userId) {
11577        Intent intent = new Intent(Intent.ACTION_MAIN);
11578        intent.addCategory(Intent.CATEGORY_HOME);
11579        ResolveInfo resolveInfo = resolveIntent(
11580                intent,
11581                intent.resolveTypeIfNeeded(mContext.getContentResolver()),
11582                PackageManager.MATCH_DEFAULT_ONLY,
11583                userId);
11584
11585        return resolveInfo == null ? null : resolveInfo.activityInfo.packageName;
11586    }
11587
11588    @Override
11589    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
11590        mContext.enforceCallingOrSelfPermission(
11591                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
11592                "Only package verification agents can verify applications");
11593
11594        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
11595        final PackageVerificationResponse response = new PackageVerificationResponse(
11596                verificationCode, Binder.getCallingUid());
11597        msg.arg1 = id;
11598        msg.obj = response;
11599        mHandler.sendMessage(msg);
11600    }
11601
11602    @Override
11603    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
11604            long millisecondsToDelay) {
11605        mContext.enforceCallingOrSelfPermission(
11606                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
11607                "Only package verification agents can extend verification timeouts");
11608
11609        final PackageVerificationState state = mPendingVerification.get(id);
11610        final PackageVerificationResponse response = new PackageVerificationResponse(
11611                verificationCodeAtTimeout, Binder.getCallingUid());
11612
11613        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
11614            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
11615        }
11616        if (millisecondsToDelay < 0) {
11617            millisecondsToDelay = 0;
11618        }
11619        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
11620                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
11621            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
11622        }
11623
11624        if ((state != null) && !state.timeoutExtended()) {
11625            state.extendTimeout();
11626
11627            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
11628            msg.arg1 = id;
11629            msg.obj = response;
11630            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
11631        }
11632    }
11633
11634    private void broadcastPackageVerified(int verificationId, Uri packageUri,
11635            int verificationCode, UserHandle user) {
11636        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
11637        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
11638        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
11639        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
11640        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
11641
11642        mContext.sendBroadcastAsUser(intent, user,
11643                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
11644    }
11645
11646    private ComponentName matchComponentForVerifier(String packageName,
11647            List<ResolveInfo> receivers) {
11648        ActivityInfo targetReceiver = null;
11649
11650        final int NR = receivers.size();
11651        for (int i = 0; i < NR; i++) {
11652            final ResolveInfo info = receivers.get(i);
11653            if (info.activityInfo == null) {
11654                continue;
11655            }
11656
11657            if (packageName.equals(info.activityInfo.packageName)) {
11658                targetReceiver = info.activityInfo;
11659                break;
11660            }
11661        }
11662
11663        if (targetReceiver == null) {
11664            return null;
11665        }
11666
11667        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
11668    }
11669
11670    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
11671            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
11672        if (pkgInfo.verifiers.length == 0) {
11673            return null;
11674        }
11675
11676        final int N = pkgInfo.verifiers.length;
11677        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
11678        for (int i = 0; i < N; i++) {
11679            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
11680
11681            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
11682                    receivers);
11683            if (comp == null) {
11684                continue;
11685            }
11686
11687            final int verifierUid = getUidForVerifier(verifierInfo);
11688            if (verifierUid == -1) {
11689                continue;
11690            }
11691
11692            if (DEBUG_VERIFY) {
11693                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
11694                        + " with the correct signature");
11695            }
11696            sufficientVerifiers.add(comp);
11697            verificationState.addSufficientVerifier(verifierUid);
11698        }
11699
11700        return sufficientVerifiers;
11701    }
11702
11703    private int getUidForVerifier(VerifierInfo verifierInfo) {
11704        synchronized (mPackages) {
11705            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
11706            if (pkg == null) {
11707                return -1;
11708            } else if (pkg.mSignatures.length != 1) {
11709                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
11710                        + " has more than one signature; ignoring");
11711                return -1;
11712            }
11713
11714            /*
11715             * If the public key of the package's signature does not match
11716             * our expected public key, then this is a different package and
11717             * we should skip.
11718             */
11719
11720            final byte[] expectedPublicKey;
11721            try {
11722                final Signature verifierSig = pkg.mSignatures[0];
11723                final PublicKey publicKey = verifierSig.getPublicKey();
11724                expectedPublicKey = publicKey.getEncoded();
11725            } catch (CertificateException e) {
11726                return -1;
11727            }
11728
11729            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
11730
11731            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
11732                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
11733                        + " does not have the expected public key; ignoring");
11734                return -1;
11735            }
11736
11737            return pkg.applicationInfo.uid;
11738        }
11739    }
11740
11741    @Override
11742    public void finishPackageInstall(int token) {
11743        enforceSystemOrRoot("Only the system is allowed to finish installs");
11744
11745        if (DEBUG_INSTALL) {
11746            Slog.v(TAG, "BM finishing package install for " + token);
11747        }
11748        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
11749
11750        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
11751        mHandler.sendMessage(msg);
11752    }
11753
11754    /**
11755     * Get the verification agent timeout.
11756     *
11757     * @return verification timeout in milliseconds
11758     */
11759    private long getVerificationTimeout() {
11760        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
11761                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
11762                DEFAULT_VERIFICATION_TIMEOUT);
11763    }
11764
11765    /**
11766     * Get the default verification agent response code.
11767     *
11768     * @return default verification response code
11769     */
11770    private int getDefaultVerificationResponse() {
11771        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
11772                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
11773                DEFAULT_VERIFICATION_RESPONSE);
11774    }
11775
11776    /**
11777     * Check whether or not package verification has been enabled.
11778     *
11779     * @return true if verification should be performed
11780     */
11781    private boolean isVerificationEnabled(int userId, int installFlags) {
11782        if (!DEFAULT_VERIFY_ENABLE) {
11783            return false;
11784        }
11785        // Ephemeral apps don't get the full verification treatment
11786        if ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) {
11787            if (DEBUG_EPHEMERAL) {
11788                Slog.d(TAG, "INSTALL_EPHEMERAL so skipping verification");
11789            }
11790            return false;
11791        }
11792
11793        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
11794
11795        // Check if installing from ADB
11796        if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
11797            // Do not run verification in a test harness environment
11798            if (ActivityManager.isRunningInTestHarness()) {
11799                return false;
11800            }
11801            if (ensureVerifyAppsEnabled) {
11802                return true;
11803            }
11804            // Check if the developer does not want package verification for ADB installs
11805            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
11806                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
11807                return false;
11808            }
11809        }
11810
11811        if (ensureVerifyAppsEnabled) {
11812            return true;
11813        }
11814
11815        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
11816                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
11817    }
11818
11819    @Override
11820    public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains)
11821            throws RemoteException {
11822        mContext.enforceCallingOrSelfPermission(
11823                Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
11824                "Only intentfilter verification agents can verify applications");
11825
11826        final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED);
11827        final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse(
11828                Binder.getCallingUid(), verificationCode, failedDomains);
11829        msg.arg1 = id;
11830        msg.obj = response;
11831        mHandler.sendMessage(msg);
11832    }
11833
11834    @Override
11835    public int getIntentVerificationStatus(String packageName, int userId) {
11836        synchronized (mPackages) {
11837            return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
11838        }
11839    }
11840
11841    @Override
11842    public boolean updateIntentVerificationStatus(String packageName, int status, int userId) {
11843        mContext.enforceCallingOrSelfPermission(
11844                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
11845
11846        boolean result = false;
11847        synchronized (mPackages) {
11848            result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId);
11849        }
11850        if (result) {
11851            scheduleWritePackageRestrictionsLocked(userId);
11852        }
11853        return result;
11854    }
11855
11856    @Override
11857    public @NonNull ParceledListSlice<IntentFilterVerificationInfo> getIntentFilterVerifications(
11858            String packageName) {
11859        synchronized (mPackages) {
11860            return new ParceledListSlice<>(mSettings.getIntentFilterVerificationsLPr(packageName));
11861        }
11862    }
11863
11864    @Override
11865    public @NonNull ParceledListSlice<IntentFilter> getAllIntentFilters(String packageName) {
11866        if (TextUtils.isEmpty(packageName)) {
11867            return ParceledListSlice.emptyList();
11868        }
11869        synchronized (mPackages) {
11870            PackageParser.Package pkg = mPackages.get(packageName);
11871            if (pkg == null || pkg.activities == null) {
11872                return ParceledListSlice.emptyList();
11873            }
11874            final int count = pkg.activities.size();
11875            ArrayList<IntentFilter> result = new ArrayList<>();
11876            for (int n=0; n<count; n++) {
11877                PackageParser.Activity activity = pkg.activities.get(n);
11878                if (activity.intents != null && activity.intents.size() > 0) {
11879                    result.addAll(activity.intents);
11880                }
11881            }
11882            return new ParceledListSlice<>(result);
11883        }
11884    }
11885
11886    @Override
11887    public boolean setDefaultBrowserPackageName(String packageName, int userId) {
11888        mContext.enforceCallingOrSelfPermission(
11889                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
11890
11891        synchronized (mPackages) {
11892            boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId);
11893            if (packageName != null) {
11894                result |= updateIntentVerificationStatus(packageName,
11895                        PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS,
11896                        userId);
11897                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr(
11898                        packageName, userId);
11899            }
11900            return result;
11901        }
11902    }
11903
11904    @Override
11905    public String getDefaultBrowserPackageName(int userId) {
11906        synchronized (mPackages) {
11907            return mSettings.getDefaultBrowserPackageNameLPw(userId);
11908        }
11909    }
11910
11911    /**
11912     * Get the "allow unknown sources" setting.
11913     *
11914     * @return the current "allow unknown sources" setting
11915     */
11916    private int getUnknownSourcesSettings() {
11917        return android.provider.Settings.Secure.getInt(mContext.getContentResolver(),
11918                android.provider.Settings.Secure.INSTALL_NON_MARKET_APPS,
11919                -1);
11920    }
11921
11922    @Override
11923    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
11924        final int uid = Binder.getCallingUid();
11925        // writer
11926        synchronized (mPackages) {
11927            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
11928            if (targetPackageSetting == null) {
11929                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
11930            }
11931
11932            PackageSetting installerPackageSetting;
11933            if (installerPackageName != null) {
11934                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
11935                if (installerPackageSetting == null) {
11936                    throw new IllegalArgumentException("Unknown installer package: "
11937                            + installerPackageName);
11938                }
11939            } else {
11940                installerPackageSetting = null;
11941            }
11942
11943            Signature[] callerSignature;
11944            Object obj = mSettings.getUserIdLPr(uid);
11945            if (obj != null) {
11946                if (obj instanceof SharedUserSetting) {
11947                    callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
11948                } else if (obj instanceof PackageSetting) {
11949                    callerSignature = ((PackageSetting)obj).signatures.mSignatures;
11950                } else {
11951                    throw new SecurityException("Bad object " + obj + " for uid " + uid);
11952                }
11953            } else {
11954                throw new SecurityException("Unknown calling UID: " + uid);
11955            }
11956
11957            // Verify: can't set installerPackageName to a package that is
11958            // not signed with the same cert as the caller.
11959            if (installerPackageSetting != null) {
11960                if (compareSignatures(callerSignature,
11961                        installerPackageSetting.signatures.mSignatures)
11962                        != PackageManager.SIGNATURE_MATCH) {
11963                    throw new SecurityException(
11964                            "Caller does not have same cert as new installer package "
11965                            + installerPackageName);
11966                }
11967            }
11968
11969            // Verify: if target already has an installer package, it must
11970            // be signed with the same cert as the caller.
11971            if (targetPackageSetting.installerPackageName != null) {
11972                PackageSetting setting = mSettings.mPackages.get(
11973                        targetPackageSetting.installerPackageName);
11974                // If the currently set package isn't valid, then it's always
11975                // okay to change it.
11976                if (setting != null) {
11977                    if (compareSignatures(callerSignature,
11978                            setting.signatures.mSignatures)
11979                            != PackageManager.SIGNATURE_MATCH) {
11980                        throw new SecurityException(
11981                                "Caller does not have same cert as old installer package "
11982                                + targetPackageSetting.installerPackageName);
11983                    }
11984                }
11985            }
11986
11987            // Okay!
11988            targetPackageSetting.installerPackageName = installerPackageName;
11989            if (installerPackageName != null) {
11990                mSettings.mInstallerPackages.add(installerPackageName);
11991            }
11992            scheduleWriteSettingsLocked();
11993        }
11994    }
11995
11996    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
11997        // Queue up an async operation since the package installation may take a little while.
11998        mHandler.post(new Runnable() {
11999            public void run() {
12000                mHandler.removeCallbacks(this);
12001                 // Result object to be returned
12002                PackageInstalledInfo res = new PackageInstalledInfo();
12003                res.setReturnCode(currentStatus);
12004                res.uid = -1;
12005                res.pkg = null;
12006                res.removedInfo = null;
12007                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
12008                    args.doPreInstall(res.returnCode);
12009                    synchronized (mInstallLock) {
12010                        installPackageTracedLI(args, res);
12011                    }
12012                    args.doPostInstall(res.returnCode, res.uid);
12013                }
12014
12015                // A restore should be performed at this point if (a) the install
12016                // succeeded, (b) the operation is not an update, and (c) the new
12017                // package has not opted out of backup participation.
12018                final boolean update = res.removedInfo != null
12019                        && res.removedInfo.removedPackage != null;
12020                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
12021                boolean doRestore = !update
12022                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
12023
12024                // Set up the post-install work request bookkeeping.  This will be used
12025                // and cleaned up by the post-install event handling regardless of whether
12026                // there's a restore pass performed.  Token values are >= 1.
12027                int token;
12028                if (mNextInstallToken < 0) mNextInstallToken = 1;
12029                token = mNextInstallToken++;
12030
12031                PostInstallData data = new PostInstallData(args, res);
12032                mRunningInstalls.put(token, data);
12033                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
12034
12035                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
12036                    // Pass responsibility to the Backup Manager.  It will perform a
12037                    // restore if appropriate, then pass responsibility back to the
12038                    // Package Manager to run the post-install observer callbacks
12039                    // and broadcasts.
12040                    IBackupManager bm = IBackupManager.Stub.asInterface(
12041                            ServiceManager.getService(Context.BACKUP_SERVICE));
12042                    if (bm != null) {
12043                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
12044                                + " to BM for possible restore");
12045                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
12046                        try {
12047                            // TODO: http://b/22388012
12048                            if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) {
12049                                bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
12050                            } else {
12051                                doRestore = false;
12052                            }
12053                        } catch (RemoteException e) {
12054                            // can't happen; the backup manager is local
12055                        } catch (Exception e) {
12056                            Slog.e(TAG, "Exception trying to enqueue restore", e);
12057                            doRestore = false;
12058                        }
12059                    } else {
12060                        Slog.e(TAG, "Backup Manager not found!");
12061                        doRestore = false;
12062                    }
12063                }
12064
12065                if (!doRestore) {
12066                    // No restore possible, or the Backup Manager was mysteriously not
12067                    // available -- just fire the post-install work request directly.
12068                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
12069
12070                    Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token);
12071
12072                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
12073                    mHandler.sendMessage(msg);
12074                }
12075            }
12076        });
12077    }
12078
12079    private abstract class HandlerParams {
12080        private static final int MAX_RETRIES = 4;
12081
12082        /**
12083         * Number of times startCopy() has been attempted and had a non-fatal
12084         * error.
12085         */
12086        private int mRetries = 0;
12087
12088        /** User handle for the user requesting the information or installation. */
12089        private final UserHandle mUser;
12090        String traceMethod;
12091        int traceCookie;
12092
12093        HandlerParams(UserHandle user) {
12094            mUser = user;
12095        }
12096
12097        UserHandle getUser() {
12098            return mUser;
12099        }
12100
12101        HandlerParams setTraceMethod(String traceMethod) {
12102            this.traceMethod = traceMethod;
12103            return this;
12104        }
12105
12106        HandlerParams setTraceCookie(int traceCookie) {
12107            this.traceCookie = traceCookie;
12108            return this;
12109        }
12110
12111        final boolean startCopy() {
12112            boolean res;
12113            try {
12114                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
12115
12116                if (++mRetries > MAX_RETRIES) {
12117                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
12118                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
12119                    handleServiceError();
12120                    return false;
12121                } else {
12122                    handleStartCopy();
12123                    res = true;
12124                }
12125            } catch (RemoteException e) {
12126                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
12127                mHandler.sendEmptyMessage(MCS_RECONNECT);
12128                res = false;
12129            }
12130            handleReturnCode();
12131            return res;
12132        }
12133
12134        final void serviceError() {
12135            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
12136            handleServiceError();
12137            handleReturnCode();
12138        }
12139
12140        abstract void handleStartCopy() throws RemoteException;
12141        abstract void handleServiceError();
12142        abstract void handleReturnCode();
12143    }
12144
12145    class MeasureParams extends HandlerParams {
12146        private final PackageStats mStats;
12147        private boolean mSuccess;
12148
12149        private final IPackageStatsObserver mObserver;
12150
12151        public MeasureParams(PackageStats stats, IPackageStatsObserver observer) {
12152            super(new UserHandle(stats.userHandle));
12153            mObserver = observer;
12154            mStats = stats;
12155        }
12156
12157        @Override
12158        public String toString() {
12159            return "MeasureParams{"
12160                + Integer.toHexString(System.identityHashCode(this))
12161                + " " + mStats.packageName + "}";
12162        }
12163
12164        @Override
12165        void handleStartCopy() throws RemoteException {
12166            synchronized (mInstallLock) {
12167                mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats);
12168            }
12169
12170            if (mSuccess) {
12171                final boolean mounted;
12172                if (Environment.isExternalStorageEmulated()) {
12173                    mounted = true;
12174                } else {
12175                    final String status = Environment.getExternalStorageState();
12176                    mounted = (Environment.MEDIA_MOUNTED.equals(status)
12177                            || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status));
12178                }
12179
12180                if (mounted) {
12181                    final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle);
12182
12183                    mStats.externalCacheSize = calculateDirectorySize(mContainerService,
12184                            userEnv.buildExternalStorageAppCacheDirs(mStats.packageName));
12185
12186                    mStats.externalDataSize = calculateDirectorySize(mContainerService,
12187                            userEnv.buildExternalStorageAppDataDirs(mStats.packageName));
12188
12189                    // Always subtract cache size, since it's a subdirectory
12190                    mStats.externalDataSize -= mStats.externalCacheSize;
12191
12192                    mStats.externalMediaSize = calculateDirectorySize(mContainerService,
12193                            userEnv.buildExternalStorageAppMediaDirs(mStats.packageName));
12194
12195                    mStats.externalObbSize = calculateDirectorySize(mContainerService,
12196                            userEnv.buildExternalStorageAppObbDirs(mStats.packageName));
12197                }
12198            }
12199        }
12200
12201        @Override
12202        void handleReturnCode() {
12203            if (mObserver != null) {
12204                try {
12205                    mObserver.onGetStatsCompleted(mStats, mSuccess);
12206                } catch (RemoteException e) {
12207                    Slog.i(TAG, "Observer no longer exists.");
12208                }
12209            }
12210        }
12211
12212        @Override
12213        void handleServiceError() {
12214            Slog.e(TAG, "Could not measure application " + mStats.packageName
12215                            + " external storage");
12216        }
12217    }
12218
12219    private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths)
12220            throws RemoteException {
12221        long result = 0;
12222        for (File path : paths) {
12223            result += mcs.calculateDirectorySize(path.getAbsolutePath());
12224        }
12225        return result;
12226    }
12227
12228    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
12229        for (File path : paths) {
12230            try {
12231                mcs.clearDirectory(path.getAbsolutePath());
12232            } catch (RemoteException e) {
12233            }
12234        }
12235    }
12236
12237    static class OriginInfo {
12238        /**
12239         * Location where install is coming from, before it has been
12240         * copied/renamed into place. This could be a single monolithic APK
12241         * file, or a cluster directory. This location may be untrusted.
12242         */
12243        final File file;
12244        final String cid;
12245
12246        /**
12247         * Flag indicating that {@link #file} or {@link #cid} has already been
12248         * staged, meaning downstream users don't need to defensively copy the
12249         * contents.
12250         */
12251        final boolean staged;
12252
12253        /**
12254         * Flag indicating that {@link #file} or {@link #cid} is an already
12255         * installed app that is being moved.
12256         */
12257        final boolean existing;
12258
12259        final String resolvedPath;
12260        final File resolvedFile;
12261
12262        static OriginInfo fromNothing() {
12263            return new OriginInfo(null, null, false, false);
12264        }
12265
12266        static OriginInfo fromUntrustedFile(File file) {
12267            return new OriginInfo(file, null, false, false);
12268        }
12269
12270        static OriginInfo fromExistingFile(File file) {
12271            return new OriginInfo(file, null, false, true);
12272        }
12273
12274        static OriginInfo fromStagedFile(File file) {
12275            return new OriginInfo(file, null, true, false);
12276        }
12277
12278        static OriginInfo fromStagedContainer(String cid) {
12279            return new OriginInfo(null, cid, true, false);
12280        }
12281
12282        private OriginInfo(File file, String cid, boolean staged, boolean existing) {
12283            this.file = file;
12284            this.cid = cid;
12285            this.staged = staged;
12286            this.existing = existing;
12287
12288            if (cid != null) {
12289                resolvedPath = PackageHelper.getSdDir(cid);
12290                resolvedFile = new File(resolvedPath);
12291            } else if (file != null) {
12292                resolvedPath = file.getAbsolutePath();
12293                resolvedFile = file;
12294            } else {
12295                resolvedPath = null;
12296                resolvedFile = null;
12297            }
12298        }
12299    }
12300
12301    static class MoveInfo {
12302        final int moveId;
12303        final String fromUuid;
12304        final String toUuid;
12305        final String packageName;
12306        final String dataAppName;
12307        final int appId;
12308        final String seinfo;
12309        final int targetSdkVersion;
12310
12311        public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName,
12312                String dataAppName, int appId, String seinfo, int targetSdkVersion) {
12313            this.moveId = moveId;
12314            this.fromUuid = fromUuid;
12315            this.toUuid = toUuid;
12316            this.packageName = packageName;
12317            this.dataAppName = dataAppName;
12318            this.appId = appId;
12319            this.seinfo = seinfo;
12320            this.targetSdkVersion = targetSdkVersion;
12321        }
12322    }
12323
12324    static class VerificationInfo {
12325        /** A constant used to indicate that a uid value is not present. */
12326        public static final int NO_UID = -1;
12327
12328        /** URI referencing where the package was downloaded from. */
12329        final Uri originatingUri;
12330
12331        /** HTTP referrer URI associated with the originatingURI. */
12332        final Uri referrer;
12333
12334        /** UID of the application that the install request originated from. */
12335        final int originatingUid;
12336
12337        /** UID of application requesting the install */
12338        final int installerUid;
12339
12340        VerificationInfo(Uri originatingUri, Uri referrer, int originatingUid, int installerUid) {
12341            this.originatingUri = originatingUri;
12342            this.referrer = referrer;
12343            this.originatingUid = originatingUid;
12344            this.installerUid = installerUid;
12345        }
12346    }
12347
12348    class InstallParams extends HandlerParams {
12349        final OriginInfo origin;
12350        final MoveInfo move;
12351        final IPackageInstallObserver2 observer;
12352        int installFlags;
12353        final String installerPackageName;
12354        final String volumeUuid;
12355        private InstallArgs mArgs;
12356        private int mRet;
12357        final String packageAbiOverride;
12358        final String[] grantedRuntimePermissions;
12359        final VerificationInfo verificationInfo;
12360        final Certificate[][] certificates;
12361
12362        InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
12363                int installFlags, String installerPackageName, String volumeUuid,
12364                VerificationInfo verificationInfo, UserHandle user, String packageAbiOverride,
12365                String[] grantedPermissions, Certificate[][] certificates) {
12366            super(user);
12367            this.origin = origin;
12368            this.move = move;
12369            this.observer = observer;
12370            this.installFlags = installFlags;
12371            this.installerPackageName = installerPackageName;
12372            this.volumeUuid = volumeUuid;
12373            this.verificationInfo = verificationInfo;
12374            this.packageAbiOverride = packageAbiOverride;
12375            this.grantedRuntimePermissions = grantedPermissions;
12376            this.certificates = certificates;
12377        }
12378
12379        @Override
12380        public String toString() {
12381            return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
12382                    + " file=" + origin.file + " cid=" + origin.cid + "}";
12383        }
12384
12385        private int installLocationPolicy(PackageInfoLite pkgLite) {
12386            String packageName = pkgLite.packageName;
12387            int installLocation = pkgLite.installLocation;
12388            boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
12389            // reader
12390            synchronized (mPackages) {
12391                // Currently installed package which the new package is attempting to replace or
12392                // null if no such package is installed.
12393                PackageParser.Package installedPkg = mPackages.get(packageName);
12394                // Package which currently owns the data which the new package will own if installed.
12395                // If an app is unstalled while keeping data (e.g., adb uninstall -k), installedPkg
12396                // will be null whereas dataOwnerPkg will contain information about the package
12397                // which was uninstalled while keeping its data.
12398                PackageParser.Package dataOwnerPkg = installedPkg;
12399                if (dataOwnerPkg  == null) {
12400                    PackageSetting ps = mSettings.mPackages.get(packageName);
12401                    if (ps != null) {
12402                        dataOwnerPkg = ps.pkg;
12403                    }
12404                }
12405
12406                if (dataOwnerPkg != null) {
12407                    // If installed, the package will get access to data left on the device by its
12408                    // predecessor. As a security measure, this is permited only if this is not a
12409                    // version downgrade or if the predecessor package is marked as debuggable and
12410                    // a downgrade is explicitly requested.
12411                    //
12412                    // On debuggable platform builds, downgrades are permitted even for
12413                    // non-debuggable packages to make testing easier. Debuggable platform builds do
12414                    // not offer security guarantees and thus it's OK to disable some security
12415                    // mechanisms to make debugging/testing easier on those builds. However, even on
12416                    // debuggable builds downgrades of packages are permitted only if requested via
12417                    // installFlags. This is because we aim to keep the behavior of debuggable
12418                    // platform builds as close as possible to the behavior of non-debuggable
12419                    // platform builds.
12420                    final boolean downgradeRequested =
12421                            (installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) != 0;
12422                    final boolean packageDebuggable =
12423                                (dataOwnerPkg.applicationInfo.flags
12424                                        & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
12425                    final boolean downgradePermitted =
12426                            (downgradeRequested) && ((Build.IS_DEBUGGABLE) || (packageDebuggable));
12427                    if (!downgradePermitted) {
12428                        try {
12429                            checkDowngrade(dataOwnerPkg, pkgLite);
12430                        } catch (PackageManagerException e) {
12431                            Slog.w(TAG, "Downgrade detected: " + e.getMessage());
12432                            return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
12433                        }
12434                    }
12435                }
12436
12437                if (installedPkg != null) {
12438                    if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
12439                        // Check for updated system application.
12440                        if ((installedPkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
12441                            if (onSd) {
12442                                Slog.w(TAG, "Cannot install update to system app on sdcard");
12443                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
12444                            }
12445                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
12446                        } else {
12447                            if (onSd) {
12448                                // Install flag overrides everything.
12449                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
12450                            }
12451                            // If current upgrade specifies particular preference
12452                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
12453                                // Application explicitly specified internal.
12454                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
12455                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
12456                                // App explictly prefers external. Let policy decide
12457                            } else {
12458                                // Prefer previous location
12459                                if (isExternal(installedPkg)) {
12460                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
12461                                }
12462                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
12463                            }
12464                        }
12465                    } else {
12466                        // Invalid install. Return error code
12467                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
12468                    }
12469                }
12470            }
12471            // All the special cases have been taken care of.
12472            // Return result based on recommended install location.
12473            if (onSd) {
12474                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
12475            }
12476            return pkgLite.recommendedInstallLocation;
12477        }
12478
12479        /*
12480         * Invoke remote method to get package information and install
12481         * location values. Override install location based on default
12482         * policy if needed and then create install arguments based
12483         * on the install location.
12484         */
12485        public void handleStartCopy() throws RemoteException {
12486            int ret = PackageManager.INSTALL_SUCCEEDED;
12487
12488            // If we're already staged, we've firmly committed to an install location
12489            if (origin.staged) {
12490                if (origin.file != null) {
12491                    installFlags |= PackageManager.INSTALL_INTERNAL;
12492                    installFlags &= ~PackageManager.INSTALL_EXTERNAL;
12493                } else if (origin.cid != null) {
12494                    installFlags |= PackageManager.INSTALL_EXTERNAL;
12495                    installFlags &= ~PackageManager.INSTALL_INTERNAL;
12496                } else {
12497                    throw new IllegalStateException("Invalid stage location");
12498                }
12499            }
12500
12501            final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
12502            final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
12503            final boolean ephemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0;
12504            PackageInfoLite pkgLite = null;
12505
12506            if (onInt && onSd) {
12507                // Check if both bits are set.
12508                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
12509                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
12510            } else if (onSd && ephemeral) {
12511                Slog.w(TAG,  "Conflicting flags specified for installing ephemeral on external");
12512                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
12513            } else {
12514                pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
12515                        packageAbiOverride);
12516
12517                if (DEBUG_EPHEMERAL && ephemeral) {
12518                    Slog.v(TAG, "pkgLite for install: " + pkgLite);
12519                }
12520
12521                /*
12522                 * If we have too little free space, try to free cache
12523                 * before giving up.
12524                 */
12525                if (!origin.staged && pkgLite.recommendedInstallLocation
12526                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
12527                    // TODO: focus freeing disk space on the target device
12528                    final StorageManager storage = StorageManager.from(mContext);
12529                    final long lowThreshold = storage.getStorageLowBytes(
12530                            Environment.getDataDirectory());
12531
12532                    final long sizeBytes = mContainerService.calculateInstalledSize(
12533                            origin.resolvedPath, isForwardLocked(), packageAbiOverride);
12534
12535                    try {
12536                        mInstaller.freeCache(null, sizeBytes + lowThreshold);
12537                        pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
12538                                installFlags, packageAbiOverride);
12539                    } catch (InstallerException e) {
12540                        Slog.w(TAG, "Failed to free cache", e);
12541                    }
12542
12543                    /*
12544                     * The cache free must have deleted the file we
12545                     * downloaded to install.
12546                     *
12547                     * TODO: fix the "freeCache" call to not delete
12548                     *       the file we care about.
12549                     */
12550                    if (pkgLite.recommendedInstallLocation
12551                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
12552                        pkgLite.recommendedInstallLocation
12553                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
12554                    }
12555                }
12556            }
12557
12558            if (ret == PackageManager.INSTALL_SUCCEEDED) {
12559                int loc = pkgLite.recommendedInstallLocation;
12560                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
12561                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
12562                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
12563                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
12564                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
12565                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
12566                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
12567                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
12568                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
12569                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
12570                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
12571                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
12572                } else {
12573                    // Override with defaults if needed.
12574                    loc = installLocationPolicy(pkgLite);
12575                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
12576                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
12577                    } else if (!onSd && !onInt) {
12578                        // Override install location with flags
12579                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
12580                            // Set the flag to install on external media.
12581                            installFlags |= PackageManager.INSTALL_EXTERNAL;
12582                            installFlags &= ~PackageManager.INSTALL_INTERNAL;
12583                        } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) {
12584                            if (DEBUG_EPHEMERAL) {
12585                                Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag");
12586                            }
12587                            installFlags |= PackageManager.INSTALL_EPHEMERAL;
12588                            installFlags &= ~(PackageManager.INSTALL_EXTERNAL
12589                                    |PackageManager.INSTALL_INTERNAL);
12590                        } else {
12591                            // Make sure the flag for installing on external
12592                            // media is unset
12593                            installFlags |= PackageManager.INSTALL_INTERNAL;
12594                            installFlags &= ~PackageManager.INSTALL_EXTERNAL;
12595                        }
12596                    }
12597                }
12598            }
12599
12600            final InstallArgs args = createInstallArgs(this);
12601            mArgs = args;
12602
12603            if (ret == PackageManager.INSTALL_SUCCEEDED) {
12604                // TODO: http://b/22976637
12605                // Apps installed for "all" users use the device owner to verify the app
12606                UserHandle verifierUser = getUser();
12607                if (verifierUser == UserHandle.ALL) {
12608                    verifierUser = UserHandle.SYSTEM;
12609                }
12610
12611                /*
12612                 * Determine if we have any installed package verifiers. If we
12613                 * do, then we'll defer to them to verify the packages.
12614                 */
12615                final int requiredUid = mRequiredVerifierPackage == null ? -1
12616                        : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
12617                                verifierUser.getIdentifier());
12618                if (!origin.existing && requiredUid != -1
12619                        && isVerificationEnabled(verifierUser.getIdentifier(), installFlags)) {
12620                    final Intent verification = new Intent(
12621                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
12622                    verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
12623                    verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
12624                            PACKAGE_MIME_TYPE);
12625                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
12626
12627                    // Query all live verifiers based on current user state
12628                    final List<ResolveInfo> receivers = queryIntentReceiversInternal(verification,
12629                            PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier());
12630
12631                    if (DEBUG_VERIFY) {
12632                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
12633                                + verification.toString() + " with " + pkgLite.verifiers.length
12634                                + " optional verifiers");
12635                    }
12636
12637                    final int verificationId = mPendingVerificationToken++;
12638
12639                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
12640
12641                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
12642                            installerPackageName);
12643
12644                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
12645                            installFlags);
12646
12647                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
12648                            pkgLite.packageName);
12649
12650                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
12651                            pkgLite.versionCode);
12652
12653                    if (verificationInfo != null) {
12654                        if (verificationInfo.originatingUri != null) {
12655                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
12656                                    verificationInfo.originatingUri);
12657                        }
12658                        if (verificationInfo.referrer != null) {
12659                            verification.putExtra(Intent.EXTRA_REFERRER,
12660                                    verificationInfo.referrer);
12661                        }
12662                        if (verificationInfo.originatingUid >= 0) {
12663                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
12664                                    verificationInfo.originatingUid);
12665                        }
12666                        if (verificationInfo.installerUid >= 0) {
12667                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
12668                                    verificationInfo.installerUid);
12669                        }
12670                    }
12671
12672                    final PackageVerificationState verificationState = new PackageVerificationState(
12673                            requiredUid, args);
12674
12675                    mPendingVerification.append(verificationId, verificationState);
12676
12677                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
12678                            receivers, verificationState);
12679
12680                    /*
12681                     * If any sufficient verifiers were listed in the package
12682                     * manifest, attempt to ask them.
12683                     */
12684                    if (sufficientVerifiers != null) {
12685                        final int N = sufficientVerifiers.size();
12686                        if (N == 0) {
12687                            Slog.i(TAG, "Additional verifiers required, but none installed.");
12688                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
12689                        } else {
12690                            for (int i = 0; i < N; i++) {
12691                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
12692
12693                                final Intent sufficientIntent = new Intent(verification);
12694                                sufficientIntent.setComponent(verifierComponent);
12695                                mContext.sendBroadcastAsUser(sufficientIntent, verifierUser);
12696                            }
12697                        }
12698                    }
12699
12700                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
12701                            mRequiredVerifierPackage, receivers);
12702                    if (ret == PackageManager.INSTALL_SUCCEEDED
12703                            && mRequiredVerifierPackage != null) {
12704                        Trace.asyncTraceBegin(
12705                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
12706                        /*
12707                         * Send the intent to the required verification agent,
12708                         * but only start the verification timeout after the
12709                         * target BroadcastReceivers have run.
12710                         */
12711                        verification.setComponent(requiredVerifierComponent);
12712                        mContext.sendOrderedBroadcastAsUser(verification, verifierUser,
12713                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
12714                                new BroadcastReceiver() {
12715                                    @Override
12716                                    public void onReceive(Context context, Intent intent) {
12717                                        final Message msg = mHandler
12718                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
12719                                        msg.arg1 = verificationId;
12720                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
12721                                    }
12722                                }, null, 0, null, null);
12723
12724                        /*
12725                         * We don't want the copy to proceed until verification
12726                         * succeeds, so null out this field.
12727                         */
12728                        mArgs = null;
12729                    }
12730                } else {
12731                    /*
12732                     * No package verification is enabled, so immediately start
12733                     * the remote call to initiate copy using temporary file.
12734                     */
12735                    ret = args.copyApk(mContainerService, true);
12736                }
12737            }
12738
12739            mRet = ret;
12740        }
12741
12742        @Override
12743        void handleReturnCode() {
12744            // If mArgs is null, then MCS couldn't be reached. When it
12745            // reconnects, it will try again to install. At that point, this
12746            // will succeed.
12747            if (mArgs != null) {
12748                processPendingInstall(mArgs, mRet);
12749            }
12750        }
12751
12752        @Override
12753        void handleServiceError() {
12754            mArgs = createInstallArgs(this);
12755            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
12756        }
12757
12758        public boolean isForwardLocked() {
12759            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
12760        }
12761    }
12762
12763    /**
12764     * Used during creation of InstallArgs
12765     *
12766     * @param installFlags package installation flags
12767     * @return true if should be installed on external storage
12768     */
12769    private static boolean installOnExternalAsec(int installFlags) {
12770        if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) {
12771            return false;
12772        }
12773        if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
12774            return true;
12775        }
12776        return false;
12777    }
12778
12779    /**
12780     * Used during creation of InstallArgs
12781     *
12782     * @param installFlags package installation flags
12783     * @return true if should be installed as forward locked
12784     */
12785    private static boolean installForwardLocked(int installFlags) {
12786        return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
12787    }
12788
12789    private InstallArgs createInstallArgs(InstallParams params) {
12790        if (params.move != null) {
12791            return new MoveInstallArgs(params);
12792        } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) {
12793            return new AsecInstallArgs(params);
12794        } else {
12795            return new FileInstallArgs(params);
12796        }
12797    }
12798
12799    /**
12800     * Create args that describe an existing installed package. Typically used
12801     * when cleaning up old installs, or used as a move source.
12802     */
12803    private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
12804            String resourcePath, String[] instructionSets) {
12805        final boolean isInAsec;
12806        if (installOnExternalAsec(installFlags)) {
12807            /* Apps on SD card are always in ASEC containers. */
12808            isInAsec = true;
12809        } else if (installForwardLocked(installFlags)
12810                && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) {
12811            /*
12812             * Forward-locked apps are only in ASEC containers if they're the
12813             * new style
12814             */
12815            isInAsec = true;
12816        } else {
12817            isInAsec = false;
12818        }
12819
12820        if (isInAsec) {
12821            return new AsecInstallArgs(codePath, instructionSets,
12822                    installOnExternalAsec(installFlags), installForwardLocked(installFlags));
12823        } else {
12824            return new FileInstallArgs(codePath, resourcePath, instructionSets);
12825        }
12826    }
12827
12828    static abstract class InstallArgs {
12829        /** @see InstallParams#origin */
12830        final OriginInfo origin;
12831        /** @see InstallParams#move */
12832        final MoveInfo move;
12833
12834        final IPackageInstallObserver2 observer;
12835        // Always refers to PackageManager flags only
12836        final int installFlags;
12837        final String installerPackageName;
12838        final String volumeUuid;
12839        final UserHandle user;
12840        final String abiOverride;
12841        final String[] installGrantPermissions;
12842        /** If non-null, drop an async trace when the install completes */
12843        final String traceMethod;
12844        final int traceCookie;
12845        final Certificate[][] certificates;
12846
12847        // The list of instruction sets supported by this app. This is currently
12848        // only used during the rmdex() phase to clean up resources. We can get rid of this
12849        // if we move dex files under the common app path.
12850        /* nullable */ String[] instructionSets;
12851
12852        InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
12853                int installFlags, String installerPackageName, String volumeUuid,
12854                UserHandle user, String[] instructionSets,
12855                String abiOverride, String[] installGrantPermissions,
12856                String traceMethod, int traceCookie, Certificate[][] certificates) {
12857            this.origin = origin;
12858            this.move = move;
12859            this.installFlags = installFlags;
12860            this.observer = observer;
12861            this.installerPackageName = installerPackageName;
12862            this.volumeUuid = volumeUuid;
12863            this.user = user;
12864            this.instructionSets = instructionSets;
12865            this.abiOverride = abiOverride;
12866            this.installGrantPermissions = installGrantPermissions;
12867            this.traceMethod = traceMethod;
12868            this.traceCookie = traceCookie;
12869            this.certificates = certificates;
12870        }
12871
12872        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
12873        abstract int doPreInstall(int status);
12874
12875        /**
12876         * Rename package into final resting place. All paths on the given
12877         * scanned package should be updated to reflect the rename.
12878         */
12879        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
12880        abstract int doPostInstall(int status, int uid);
12881
12882        /** @see PackageSettingBase#codePathString */
12883        abstract String getCodePath();
12884        /** @see PackageSettingBase#resourcePathString */
12885        abstract String getResourcePath();
12886
12887        // Need installer lock especially for dex file removal.
12888        abstract void cleanUpResourcesLI();
12889        abstract boolean doPostDeleteLI(boolean delete);
12890
12891        /**
12892         * Called before the source arguments are copied. This is used mostly
12893         * for MoveParams when it needs to read the source file to put it in the
12894         * destination.
12895         */
12896        int doPreCopy() {
12897            return PackageManager.INSTALL_SUCCEEDED;
12898        }
12899
12900        /**
12901         * Called after the source arguments are copied. This is used mostly for
12902         * MoveParams when it needs to read the source file to put it in the
12903         * destination.
12904         */
12905        int doPostCopy(int uid) {
12906            return PackageManager.INSTALL_SUCCEEDED;
12907        }
12908
12909        protected boolean isFwdLocked() {
12910            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
12911        }
12912
12913        protected boolean isExternalAsec() {
12914            return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
12915        }
12916
12917        protected boolean isEphemeral() {
12918            return (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0;
12919        }
12920
12921        UserHandle getUser() {
12922            return user;
12923        }
12924    }
12925
12926    private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) {
12927        if (!allCodePaths.isEmpty()) {
12928            if (instructionSets == null) {
12929                throw new IllegalStateException("instructionSet == null");
12930            }
12931            String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
12932            for (String codePath : allCodePaths) {
12933                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
12934                    try {
12935                        mInstaller.rmdex(codePath, dexCodeInstructionSet);
12936                    } catch (InstallerException ignored) {
12937                    }
12938                }
12939            }
12940        }
12941    }
12942
12943    /**
12944     * Logic to handle installation of non-ASEC applications, including copying
12945     * and renaming logic.
12946     */
12947    class FileInstallArgs extends InstallArgs {
12948        private File codeFile;
12949        private File resourceFile;
12950
12951        // Example topology:
12952        // /data/app/com.example/base.apk
12953        // /data/app/com.example/split_foo.apk
12954        // /data/app/com.example/lib/arm/libfoo.so
12955        // /data/app/com.example/lib/arm64/libfoo.so
12956        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
12957
12958        /** New install */
12959        FileInstallArgs(InstallParams params) {
12960            super(params.origin, params.move, params.observer, params.installFlags,
12961                    params.installerPackageName, params.volumeUuid,
12962                    params.getUser(), null /*instructionSets*/, params.packageAbiOverride,
12963                    params.grantedRuntimePermissions,
12964                    params.traceMethod, params.traceCookie, params.certificates);
12965            if (isFwdLocked()) {
12966                throw new IllegalArgumentException("Forward locking only supported in ASEC");
12967            }
12968        }
12969
12970        /** Existing install */
12971        FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) {
12972            super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets,
12973                    null, null, null, 0, null /*certificates*/);
12974            this.codeFile = (codePath != null) ? new File(codePath) : null;
12975            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
12976        }
12977
12978        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
12979            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk");
12980            try {
12981                return doCopyApk(imcs, temp);
12982            } finally {
12983                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12984            }
12985        }
12986
12987        private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
12988            if (origin.staged) {
12989                if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy");
12990                codeFile = origin.file;
12991                resourceFile = origin.file;
12992                return PackageManager.INSTALL_SUCCEEDED;
12993            }
12994
12995            try {
12996                final boolean isEphemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0;
12997                final File tempDir =
12998                        mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral);
12999                codeFile = tempDir;
13000                resourceFile = tempDir;
13001            } catch (IOException e) {
13002                Slog.w(TAG, "Failed to create copy file: " + e);
13003                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
13004            }
13005
13006            final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
13007                @Override
13008                public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
13009                    if (!FileUtils.isValidExtFilename(name)) {
13010                        throw new IllegalArgumentException("Invalid filename: " + name);
13011                    }
13012                    try {
13013                        final File file = new File(codeFile, name);
13014                        final FileDescriptor fd = Os.open(file.getAbsolutePath(),
13015                                O_RDWR | O_CREAT, 0644);
13016                        Os.chmod(file.getAbsolutePath(), 0644);
13017                        return new ParcelFileDescriptor(fd);
13018                    } catch (ErrnoException e) {
13019                        throw new RemoteException("Failed to open: " + e.getMessage());
13020                    }
13021                }
13022            };
13023
13024            int ret = PackageManager.INSTALL_SUCCEEDED;
13025            ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
13026            if (ret != PackageManager.INSTALL_SUCCEEDED) {
13027                Slog.e(TAG, "Failed to copy package");
13028                return ret;
13029            }
13030
13031            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
13032            NativeLibraryHelper.Handle handle = null;
13033            try {
13034                handle = NativeLibraryHelper.Handle.create(codeFile);
13035                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
13036                        abiOverride);
13037            } catch (IOException e) {
13038                Slog.e(TAG, "Copying native libraries failed", e);
13039                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
13040            } finally {
13041                IoUtils.closeQuietly(handle);
13042            }
13043
13044            return ret;
13045        }
13046
13047        int doPreInstall(int status) {
13048            if (status != PackageManager.INSTALL_SUCCEEDED) {
13049                cleanUp();
13050            }
13051            return status;
13052        }
13053
13054        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
13055            if (status != PackageManager.INSTALL_SUCCEEDED) {
13056                cleanUp();
13057                return false;
13058            }
13059
13060            final File targetDir = codeFile.getParentFile();
13061            final File beforeCodeFile = codeFile;
13062            final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName);
13063
13064            if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
13065            try {
13066                Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
13067            } catch (ErrnoException e) {
13068                Slog.w(TAG, "Failed to rename", e);
13069                return false;
13070            }
13071
13072            if (!SELinux.restoreconRecursive(afterCodeFile)) {
13073                Slog.w(TAG, "Failed to restorecon");
13074                return false;
13075            }
13076
13077            // Reflect the rename internally
13078            codeFile = afterCodeFile;
13079            resourceFile = afterCodeFile;
13080
13081            // Reflect the rename in scanned details
13082            pkg.setCodePath(afterCodeFile.getAbsolutePath());
13083            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
13084                    afterCodeFile, pkg.baseCodePath));
13085            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
13086                    afterCodeFile, pkg.splitCodePaths));
13087
13088            // Reflect the rename in app info
13089            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
13090            pkg.setApplicationInfoCodePath(pkg.codePath);
13091            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
13092            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
13093            pkg.setApplicationInfoResourcePath(pkg.codePath);
13094            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
13095            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
13096
13097            return true;
13098        }
13099
13100        int doPostInstall(int status, int uid) {
13101            if (status != PackageManager.INSTALL_SUCCEEDED) {
13102                cleanUp();
13103            }
13104            return status;
13105        }
13106
13107        @Override
13108        String getCodePath() {
13109            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
13110        }
13111
13112        @Override
13113        String getResourcePath() {
13114            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
13115        }
13116
13117        private boolean cleanUp() {
13118            if (codeFile == null || !codeFile.exists()) {
13119                return false;
13120            }
13121
13122            removeCodePathLI(codeFile);
13123
13124            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
13125                resourceFile.delete();
13126            }
13127
13128            return true;
13129        }
13130
13131        void cleanUpResourcesLI() {
13132            // Try enumerating all code paths before deleting
13133            List<String> allCodePaths = Collections.EMPTY_LIST;
13134            if (codeFile != null && codeFile.exists()) {
13135                try {
13136                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
13137                    allCodePaths = pkg.getAllCodePaths();
13138                } catch (PackageParserException e) {
13139                    // Ignored; we tried our best
13140                }
13141            }
13142
13143            cleanUp();
13144            removeDexFiles(allCodePaths, instructionSets);
13145        }
13146
13147        boolean doPostDeleteLI(boolean delete) {
13148            // XXX err, shouldn't we respect the delete flag?
13149            cleanUpResourcesLI();
13150            return true;
13151        }
13152    }
13153
13154    private boolean isAsecExternal(String cid) {
13155        final String asecPath = PackageHelper.getSdFilesystem(cid);
13156        return !asecPath.startsWith(mAsecInternalPath);
13157    }
13158
13159    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
13160            PackageManagerException {
13161        if (copyRet < 0) {
13162            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
13163                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
13164                throw new PackageManagerException(copyRet, message);
13165            }
13166        }
13167    }
13168
13169    /**
13170     * Extract the MountService "container ID" from the full code path of an
13171     * .apk.
13172     */
13173    static String cidFromCodePath(String fullCodePath) {
13174        int eidx = fullCodePath.lastIndexOf("/");
13175        String subStr1 = fullCodePath.substring(0, eidx);
13176        int sidx = subStr1.lastIndexOf("/");
13177        return subStr1.substring(sidx+1, eidx);
13178    }
13179
13180    /**
13181     * Logic to handle installation of ASEC applications, including copying and
13182     * renaming logic.
13183     */
13184    class AsecInstallArgs extends InstallArgs {
13185        static final String RES_FILE_NAME = "pkg.apk";
13186        static final String PUBLIC_RES_FILE_NAME = "res.zip";
13187
13188        String cid;
13189        String packagePath;
13190        String resourcePath;
13191
13192        /** New install */
13193        AsecInstallArgs(InstallParams params) {
13194            super(params.origin, params.move, params.observer, params.installFlags,
13195                    params.installerPackageName, params.volumeUuid,
13196                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
13197                    params.grantedRuntimePermissions,
13198                    params.traceMethod, params.traceCookie, params.certificates);
13199        }
13200
13201        /** Existing install */
13202        AsecInstallArgs(String fullCodePath, String[] instructionSets,
13203                        boolean isExternal, boolean isForwardLocked) {
13204            super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0)
13205              | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
13206                    instructionSets, null, null, null, 0, null /*certificates*/);
13207            // Hackily pretend we're still looking at a full code path
13208            if (!fullCodePath.endsWith(RES_FILE_NAME)) {
13209                fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath();
13210            }
13211
13212            // Extract cid from fullCodePath
13213            int eidx = fullCodePath.lastIndexOf("/");
13214            String subStr1 = fullCodePath.substring(0, eidx);
13215            int sidx = subStr1.lastIndexOf("/");
13216            cid = subStr1.substring(sidx+1, eidx);
13217            setMountPath(subStr1);
13218        }
13219
13220        AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) {
13221            super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0)
13222              | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
13223                    instructionSets, null, null, null, 0, null /*certificates*/);
13224            this.cid = cid;
13225            setMountPath(PackageHelper.getSdDir(cid));
13226        }
13227
13228        void createCopyFile() {
13229            cid = mInstallerService.allocateExternalStageCidLegacy();
13230        }
13231
13232        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
13233            if (origin.staged && origin.cid != null) {
13234                if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy");
13235                cid = origin.cid;
13236                setMountPath(PackageHelper.getSdDir(cid));
13237                return PackageManager.INSTALL_SUCCEEDED;
13238            }
13239
13240            if (temp) {
13241                createCopyFile();
13242            } else {
13243                /*
13244                 * Pre-emptively destroy the container since it's destroyed if
13245                 * copying fails due to it existing anyway.
13246                 */
13247                PackageHelper.destroySdDir(cid);
13248            }
13249
13250            final String newMountPath = imcs.copyPackageToContainer(
13251                    origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(),
13252                    isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */));
13253
13254            if (newMountPath != null) {
13255                setMountPath(newMountPath);
13256                return PackageManager.INSTALL_SUCCEEDED;
13257            } else {
13258                return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
13259            }
13260        }
13261
13262        @Override
13263        String getCodePath() {
13264            return packagePath;
13265        }
13266
13267        @Override
13268        String getResourcePath() {
13269            return resourcePath;
13270        }
13271
13272        int doPreInstall(int status) {
13273            if (status != PackageManager.INSTALL_SUCCEEDED) {
13274                // Destroy container
13275                PackageHelper.destroySdDir(cid);
13276            } else {
13277                boolean mounted = PackageHelper.isContainerMounted(cid);
13278                if (!mounted) {
13279                    String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(),
13280                            Process.SYSTEM_UID);
13281                    if (newMountPath != null) {
13282                        setMountPath(newMountPath);
13283                    } else {
13284                        return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
13285                    }
13286                }
13287            }
13288            return status;
13289        }
13290
13291        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
13292            String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME);
13293            String newMountPath = null;
13294            if (PackageHelper.isContainerMounted(cid)) {
13295                // Unmount the container
13296                if (!PackageHelper.unMountSdDir(cid)) {
13297                    Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
13298                    return false;
13299                }
13300            }
13301            if (!PackageHelper.renameSdDir(cid, newCacheId)) {
13302                Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
13303                        " which might be stale. Will try to clean up.");
13304                // Clean up the stale container and proceed to recreate.
13305                if (!PackageHelper.destroySdDir(newCacheId)) {
13306                    Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
13307                    return false;
13308                }
13309                // Successfully cleaned up stale container. Try to rename again.
13310                if (!PackageHelper.renameSdDir(cid, newCacheId)) {
13311                    Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
13312                            + " inspite of cleaning it up.");
13313                    return false;
13314                }
13315            }
13316            if (!PackageHelper.isContainerMounted(newCacheId)) {
13317                Slog.w(TAG, "Mounting container " + newCacheId);
13318                newMountPath = PackageHelper.mountSdDir(newCacheId,
13319                        getEncryptKey(), Process.SYSTEM_UID);
13320            } else {
13321                newMountPath = PackageHelper.getSdDir(newCacheId);
13322            }
13323            if (newMountPath == null) {
13324                Slog.w(TAG, "Failed to get cache path for  " + newCacheId);
13325                return false;
13326            }
13327            Log.i(TAG, "Succesfully renamed " + cid +
13328                    " to " + newCacheId +
13329                    " at new path: " + newMountPath);
13330            cid = newCacheId;
13331
13332            final File beforeCodeFile = new File(packagePath);
13333            setMountPath(newMountPath);
13334            final File afterCodeFile = new File(packagePath);
13335
13336            // Reflect the rename in scanned details
13337            pkg.setCodePath(afterCodeFile.getAbsolutePath());
13338            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
13339                    afterCodeFile, pkg.baseCodePath));
13340            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
13341                    afterCodeFile, pkg.splitCodePaths));
13342
13343            // Reflect the rename in app info
13344            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
13345            pkg.setApplicationInfoCodePath(pkg.codePath);
13346            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
13347            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
13348            pkg.setApplicationInfoResourcePath(pkg.codePath);
13349            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
13350            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
13351
13352            return true;
13353        }
13354
13355        private void setMountPath(String mountPath) {
13356            final File mountFile = new File(mountPath);
13357
13358            final File monolithicFile = new File(mountFile, RES_FILE_NAME);
13359            if (monolithicFile.exists()) {
13360                packagePath = monolithicFile.getAbsolutePath();
13361                if (isFwdLocked()) {
13362                    resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath();
13363                } else {
13364                    resourcePath = packagePath;
13365                }
13366            } else {
13367                packagePath = mountFile.getAbsolutePath();
13368                resourcePath = packagePath;
13369            }
13370        }
13371
13372        int doPostInstall(int status, int uid) {
13373            if (status != PackageManager.INSTALL_SUCCEEDED) {
13374                cleanUp();
13375            } else {
13376                final int groupOwner;
13377                final String protectedFile;
13378                if (isFwdLocked()) {
13379                    groupOwner = UserHandle.getSharedAppGid(uid);
13380                    protectedFile = RES_FILE_NAME;
13381                } else {
13382                    groupOwner = -1;
13383                    protectedFile = null;
13384                }
13385
13386                if (uid < Process.FIRST_APPLICATION_UID
13387                        || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) {
13388                    Slog.e(TAG, "Failed to finalize " + cid);
13389                    PackageHelper.destroySdDir(cid);
13390                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
13391                }
13392
13393                boolean mounted = PackageHelper.isContainerMounted(cid);
13394                if (!mounted) {
13395                    PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid());
13396                }
13397            }
13398            return status;
13399        }
13400
13401        private void cleanUp() {
13402            if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp");
13403
13404            // Destroy secure container
13405            PackageHelper.destroySdDir(cid);
13406        }
13407
13408        private List<String> getAllCodePaths() {
13409            final File codeFile = new File(getCodePath());
13410            if (codeFile != null && codeFile.exists()) {
13411                try {
13412                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
13413                    return pkg.getAllCodePaths();
13414                } catch (PackageParserException e) {
13415                    // Ignored; we tried our best
13416                }
13417            }
13418            return Collections.EMPTY_LIST;
13419        }
13420
13421        void cleanUpResourcesLI() {
13422            // Enumerate all code paths before deleting
13423            cleanUpResourcesLI(getAllCodePaths());
13424        }
13425
13426        private void cleanUpResourcesLI(List<String> allCodePaths) {
13427            cleanUp();
13428            removeDexFiles(allCodePaths, instructionSets);
13429        }
13430
13431        String getPackageName() {
13432            return getAsecPackageName(cid);
13433        }
13434
13435        boolean doPostDeleteLI(boolean delete) {
13436            if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete);
13437            final List<String> allCodePaths = getAllCodePaths();
13438            boolean mounted = PackageHelper.isContainerMounted(cid);
13439            if (mounted) {
13440                // Unmount first
13441                if (PackageHelper.unMountSdDir(cid)) {
13442                    mounted = false;
13443                }
13444            }
13445            if (!mounted && delete) {
13446                cleanUpResourcesLI(allCodePaths);
13447            }
13448            return !mounted;
13449        }
13450
13451        @Override
13452        int doPreCopy() {
13453            if (isFwdLocked()) {
13454                if (!PackageHelper.fixSdPermissions(cid, getPackageUid(DEFAULT_CONTAINER_PACKAGE,
13455                        MATCH_SYSTEM_ONLY, UserHandle.USER_SYSTEM), RES_FILE_NAME)) {
13456                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
13457                }
13458            }
13459
13460            return PackageManager.INSTALL_SUCCEEDED;
13461        }
13462
13463        @Override
13464        int doPostCopy(int uid) {
13465            if (isFwdLocked()) {
13466                if (uid < Process.FIRST_APPLICATION_UID
13467                        || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid),
13468                                RES_FILE_NAME)) {
13469                    Slog.e(TAG, "Failed to finalize " + cid);
13470                    PackageHelper.destroySdDir(cid);
13471                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
13472                }
13473            }
13474
13475            return PackageManager.INSTALL_SUCCEEDED;
13476        }
13477    }
13478
13479    /**
13480     * Logic to handle movement of existing installed applications.
13481     */
13482    class MoveInstallArgs extends InstallArgs {
13483        private File codeFile;
13484        private File resourceFile;
13485
13486        /** New install */
13487        MoveInstallArgs(InstallParams params) {
13488            super(params.origin, params.move, params.observer, params.installFlags,
13489                    params.installerPackageName, params.volumeUuid,
13490                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
13491                    params.grantedRuntimePermissions,
13492                    params.traceMethod, params.traceCookie, params.certificates);
13493        }
13494
13495        int copyApk(IMediaContainerService imcs, boolean temp) {
13496            if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from "
13497                    + move.fromUuid + " to " + move.toUuid);
13498            synchronized (mInstaller) {
13499                try {
13500                    mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName,
13501                            move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion);
13502                } catch (InstallerException e) {
13503                    Slog.w(TAG, "Failed to move app", e);
13504                    return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
13505                }
13506            }
13507
13508            codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName);
13509            resourceFile = codeFile;
13510            if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile);
13511
13512            return PackageManager.INSTALL_SUCCEEDED;
13513        }
13514
13515        int doPreInstall(int status) {
13516            if (status != PackageManager.INSTALL_SUCCEEDED) {
13517                cleanUp(move.toUuid);
13518            }
13519            return status;
13520        }
13521
13522        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
13523            if (status != PackageManager.INSTALL_SUCCEEDED) {
13524                cleanUp(move.toUuid);
13525                return false;
13526            }
13527
13528            // Reflect the move in app info
13529            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
13530            pkg.setApplicationInfoCodePath(pkg.codePath);
13531            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
13532            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
13533            pkg.setApplicationInfoResourcePath(pkg.codePath);
13534            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
13535            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
13536
13537            return true;
13538        }
13539
13540        int doPostInstall(int status, int uid) {
13541            if (status == PackageManager.INSTALL_SUCCEEDED) {
13542                cleanUp(move.fromUuid);
13543            } else {
13544                cleanUp(move.toUuid);
13545            }
13546            return status;
13547        }
13548
13549        @Override
13550        String getCodePath() {
13551            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
13552        }
13553
13554        @Override
13555        String getResourcePath() {
13556            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
13557        }
13558
13559        private boolean cleanUp(String volumeUuid) {
13560            final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid),
13561                    move.dataAppName);
13562            Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid);
13563            final int[] userIds = sUserManager.getUserIds();
13564            synchronized (mInstallLock) {
13565                // Clean up both app data and code
13566                // All package moves are frozen until finished
13567                for (int userId : userIds) {
13568                    try {
13569                        mInstaller.destroyAppData(volumeUuid, move.packageName, userId,
13570                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 0);
13571                    } catch (InstallerException e) {
13572                        Slog.w(TAG, String.valueOf(e));
13573                    }
13574                }
13575                removeCodePathLI(codeFile);
13576            }
13577            return true;
13578        }
13579
13580        void cleanUpResourcesLI() {
13581            throw new UnsupportedOperationException();
13582        }
13583
13584        boolean doPostDeleteLI(boolean delete) {
13585            throw new UnsupportedOperationException();
13586        }
13587    }
13588
13589    static String getAsecPackageName(String packageCid) {
13590        int idx = packageCid.lastIndexOf("-");
13591        if (idx == -1) {
13592            return packageCid;
13593        }
13594        return packageCid.substring(0, idx);
13595    }
13596
13597    // Utility method used to create code paths based on package name and available index.
13598    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
13599        String idxStr = "";
13600        int idx = 1;
13601        // Fall back to default value of idx=1 if prefix is not
13602        // part of oldCodePath
13603        if (oldCodePath != null) {
13604            String subStr = oldCodePath;
13605            // Drop the suffix right away
13606            if (suffix != null && subStr.endsWith(suffix)) {
13607                subStr = subStr.substring(0, subStr.length() - suffix.length());
13608            }
13609            // If oldCodePath already contains prefix find out the
13610            // ending index to either increment or decrement.
13611            int sidx = subStr.lastIndexOf(prefix);
13612            if (sidx != -1) {
13613                subStr = subStr.substring(sidx + prefix.length());
13614                if (subStr != null) {
13615                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
13616                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
13617                    }
13618                    try {
13619                        idx = Integer.parseInt(subStr);
13620                        if (idx <= 1) {
13621                            idx++;
13622                        } else {
13623                            idx--;
13624                        }
13625                    } catch(NumberFormatException e) {
13626                    }
13627                }
13628            }
13629        }
13630        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
13631        return prefix + idxStr;
13632    }
13633
13634    private File getNextCodePath(File targetDir, String packageName) {
13635        int suffix = 1;
13636        File result;
13637        do {
13638            result = new File(targetDir, packageName + "-" + suffix);
13639            suffix++;
13640        } while (result.exists());
13641        return result;
13642    }
13643
13644    // Utility method that returns the relative package path with respect
13645    // to the installation directory. Like say for /data/data/com.test-1.apk
13646    // string com.test-1 is returned.
13647    static String deriveCodePathName(String codePath) {
13648        if (codePath == null) {
13649            return null;
13650        }
13651        final File codeFile = new File(codePath);
13652        final String name = codeFile.getName();
13653        if (codeFile.isDirectory()) {
13654            return name;
13655        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
13656            final int lastDot = name.lastIndexOf('.');
13657            return name.substring(0, lastDot);
13658        } else {
13659            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
13660            return null;
13661        }
13662    }
13663
13664    static class PackageInstalledInfo {
13665        String name;
13666        int uid;
13667        // The set of users that originally had this package installed.
13668        int[] origUsers;
13669        // The set of users that now have this package installed.
13670        int[] newUsers;
13671        PackageParser.Package pkg;
13672        int returnCode;
13673        String returnMsg;
13674        PackageRemovedInfo removedInfo;
13675        ArrayMap<String, PackageInstalledInfo> addedChildPackages;
13676
13677        public void setError(int code, String msg) {
13678            setReturnCode(code);
13679            setReturnMessage(msg);
13680            Slog.w(TAG, msg);
13681        }
13682
13683        public void setError(String msg, PackageParserException e) {
13684            setReturnCode(e.error);
13685            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
13686            Slog.w(TAG, msg, e);
13687        }
13688
13689        public void setError(String msg, PackageManagerException e) {
13690            returnCode = e.error;
13691            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
13692            Slog.w(TAG, msg, e);
13693        }
13694
13695        public void setReturnCode(int returnCode) {
13696            this.returnCode = returnCode;
13697            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
13698            for (int i = 0; i < childCount; i++) {
13699                addedChildPackages.valueAt(i).returnCode = returnCode;
13700            }
13701        }
13702
13703        private void setReturnMessage(String returnMsg) {
13704            this.returnMsg = returnMsg;
13705            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
13706            for (int i = 0; i < childCount; i++) {
13707                addedChildPackages.valueAt(i).returnMsg = returnMsg;
13708            }
13709        }
13710
13711        // In some error cases we want to convey more info back to the observer
13712        String origPackage;
13713        String origPermission;
13714    }
13715
13716    /*
13717     * Install a non-existing package.
13718     */
13719    private void installNewPackageLIF(PackageParser.Package pkg, final int policyFlags,
13720            int scanFlags, UserHandle user, String installerPackageName, String volumeUuid,
13721            PackageInstalledInfo res) {
13722        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage");
13723
13724        // Remember this for later, in case we need to rollback this install
13725        String pkgName = pkg.packageName;
13726
13727        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
13728
13729        synchronized(mPackages) {
13730            if (mSettings.mRenamedPackages.containsKey(pkgName)) {
13731                // A package with the same name is already installed, though
13732                // it has been renamed to an older name.  The package we
13733                // are trying to install should be installed as an update to
13734                // the existing one, but that has not been requested, so bail.
13735                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
13736                        + " without first uninstalling package running as "
13737                        + mSettings.mRenamedPackages.get(pkgName));
13738                return;
13739            }
13740            if (mPackages.containsKey(pkgName)) {
13741                // Don't allow installation over an existing package with the same name.
13742                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
13743                        + " without first uninstalling.");
13744                return;
13745            }
13746        }
13747
13748        try {
13749            PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags,
13750                    System.currentTimeMillis(), user);
13751
13752            updateSettingsLI(newPackage, installerPackageName, null, res, user);
13753
13754            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
13755                prepareAppDataAfterInstallLIF(newPackage);
13756
13757            } else {
13758                // Remove package from internal structures, but keep around any
13759                // data that might have already existed
13760                deletePackageLIF(pkgName, UserHandle.ALL, false, null,
13761                        PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null);
13762            }
13763        } catch (PackageManagerException e) {
13764            res.setError("Package couldn't be installed in " + pkg.codePath, e);
13765        }
13766
13767        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
13768    }
13769
13770    private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) {
13771        // Can't rotate keys during boot or if sharedUser.
13772        if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null
13773                || !oldPs.keySetData.isUsingUpgradeKeySets()) {
13774            return false;
13775        }
13776        // app is using upgradeKeySets; make sure all are valid
13777        KeySetManagerService ksms = mSettings.mKeySetManagerService;
13778        long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets();
13779        for (int i = 0; i < upgradeKeySets.length; i++) {
13780            if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) {
13781                Slog.wtf(TAG, "Package "
13782                         + (oldPs.name != null ? oldPs.name : "<null>")
13783                         + " contains upgrade-key-set reference to unknown key-set: "
13784                         + upgradeKeySets[i]
13785                         + " reverting to signatures check.");
13786                return false;
13787            }
13788        }
13789        return true;
13790    }
13791
13792    private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) {
13793        // Upgrade keysets are being used.  Determine if new package has a superset of the
13794        // required keys.
13795        long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets();
13796        KeySetManagerService ksms = mSettings.mKeySetManagerService;
13797        for (int i = 0; i < upgradeKeySets.length; i++) {
13798            Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]);
13799            if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) {
13800                return true;
13801            }
13802        }
13803        return false;
13804    }
13805
13806    private void replacePackageLIF(PackageParser.Package pkg, final int policyFlags, int scanFlags,
13807            UserHandle user, String installerPackageName, PackageInstalledInfo res) {
13808        final boolean isEphemeral = (policyFlags & PackageParser.PARSE_IS_EPHEMERAL) != 0;
13809
13810        final PackageParser.Package oldPackage;
13811        final String pkgName = pkg.packageName;
13812        final int[] allUsers;
13813        final int[] installedUsers;
13814
13815        synchronized(mPackages) {
13816            oldPackage = mPackages.get(pkgName);
13817            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
13818
13819            // don't allow upgrade to target a release SDK from a pre-release SDK
13820            final boolean oldTargetsPreRelease = oldPackage.applicationInfo.targetSdkVersion
13821                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
13822            final boolean newTargetsPreRelease = pkg.applicationInfo.targetSdkVersion
13823                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
13824            if (oldTargetsPreRelease
13825                    && !newTargetsPreRelease
13826                    && ((policyFlags & PackageParser.PARSE_FORCE_SDK) == 0)) {
13827                Slog.w(TAG, "Can't install package targeting released sdk");
13828                res.setReturnCode(PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE);
13829                return;
13830            }
13831
13832            // don't allow an upgrade from full to ephemeral
13833            final boolean oldIsEphemeral = oldPackage.applicationInfo.isEphemeralApp();
13834            if (isEphemeral && !oldIsEphemeral) {
13835                // can't downgrade from full to ephemeral
13836                Slog.w(TAG, "Can't replace app with ephemeral: " + pkgName);
13837                res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID);
13838                return;
13839            }
13840
13841            // verify signatures are valid
13842            final PackageSetting ps = mSettings.mPackages.get(pkgName);
13843            if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
13844                if (!checkUpgradeKeySetLP(ps, pkg)) {
13845                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
13846                            "New package not signed by keys specified by upgrade-keysets: "
13847                                    + pkgName);
13848                    return;
13849                }
13850            } else {
13851                // default to original signature matching
13852                if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
13853                        != PackageManager.SIGNATURE_MATCH) {
13854                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
13855                            "New package has a different signature: " + pkgName);
13856                    return;
13857                }
13858            }
13859
13860            // Check for shared user id changes
13861            String invalidPackageName =
13862                    getParentOrChildPackageChangedSharedUser(oldPackage, pkg);
13863            if (invalidPackageName != null) {
13864                res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
13865                        "Package " + invalidPackageName + " tried to change user "
13866                                + oldPackage.mSharedUserId);
13867                return;
13868            }
13869
13870            // In case of rollback, remember per-user/profile install state
13871            allUsers = sUserManager.getUserIds();
13872            installedUsers = ps.queryInstalledUsers(allUsers, true);
13873        }
13874
13875        // Update what is removed
13876        res.removedInfo = new PackageRemovedInfo();
13877        res.removedInfo.uid = oldPackage.applicationInfo.uid;
13878        res.removedInfo.removedPackage = oldPackage.packageName;
13879        res.removedInfo.isUpdate = true;
13880        res.removedInfo.origUsers = installedUsers;
13881        final int childCount = (oldPackage.childPackages != null)
13882                ? oldPackage.childPackages.size() : 0;
13883        for (int i = 0; i < childCount; i++) {
13884            boolean childPackageUpdated = false;
13885            PackageParser.Package childPkg = oldPackage.childPackages.get(i);
13886            if (res.addedChildPackages != null) {
13887                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
13888                if (childRes != null) {
13889                    childRes.removedInfo.uid = childPkg.applicationInfo.uid;
13890                    childRes.removedInfo.removedPackage = childPkg.packageName;
13891                    childRes.removedInfo.isUpdate = true;
13892                    childPackageUpdated = true;
13893                }
13894            }
13895            if (!childPackageUpdated) {
13896                PackageRemovedInfo childRemovedRes = new PackageRemovedInfo();
13897                childRemovedRes.removedPackage = childPkg.packageName;
13898                childRemovedRes.isUpdate = false;
13899                childRemovedRes.dataRemoved = true;
13900                synchronized (mPackages) {
13901                    PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName);
13902                    if (childPs != null) {
13903                        childRemovedRes.origUsers = childPs.queryInstalledUsers(allUsers, true);
13904                    }
13905                }
13906                if (res.removedInfo.removedChildPackages == null) {
13907                    res.removedInfo.removedChildPackages = new ArrayMap<>();
13908                }
13909                res.removedInfo.removedChildPackages.put(childPkg.packageName, childRemovedRes);
13910            }
13911        }
13912
13913        boolean sysPkg = (isSystemApp(oldPackage));
13914        if (sysPkg) {
13915            // Set the system/privileged flags as needed
13916            final boolean privileged =
13917                    (oldPackage.applicationInfo.privateFlags
13918                            & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
13919            final int systemPolicyFlags = policyFlags
13920                    | PackageParser.PARSE_IS_SYSTEM
13921                    | (privileged ? PackageParser.PARSE_IS_PRIVILEGED : 0);
13922
13923            replaceSystemPackageLIF(oldPackage, pkg, systemPolicyFlags, scanFlags,
13924                    user, allUsers, installerPackageName, res);
13925        } else {
13926            replaceNonSystemPackageLIF(oldPackage, pkg, policyFlags, scanFlags,
13927                    user, allUsers, installerPackageName, res);
13928        }
13929    }
13930
13931    public List<String> getPreviousCodePaths(String packageName) {
13932        final PackageSetting ps = mSettings.mPackages.get(packageName);
13933        final List<String> result = new ArrayList<String>();
13934        if (ps != null && ps.oldCodePaths != null) {
13935            result.addAll(ps.oldCodePaths);
13936        }
13937        return result;
13938    }
13939
13940    private void replaceNonSystemPackageLIF(PackageParser.Package deletedPackage,
13941            PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user,
13942            int[] allUsers, String installerPackageName, PackageInstalledInfo res) {
13943        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
13944                + deletedPackage);
13945
13946        String pkgName = deletedPackage.packageName;
13947        boolean deletedPkg = true;
13948        boolean addedPkg = false;
13949        boolean updatedSettings = false;
13950        final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0;
13951        final int deleteFlags = PackageManager.DELETE_KEEP_DATA
13952                | (killApp ? 0 : PackageManager.DELETE_DONT_KILL_APP);
13953
13954        final long origUpdateTime = (pkg.mExtras != null)
13955                ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0;
13956
13957        // First delete the existing package while retaining the data directory
13958        if (!deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
13959                res.removedInfo, true, pkg)) {
13960            // If the existing package wasn't successfully deleted
13961            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
13962            deletedPkg = false;
13963        } else {
13964            // Successfully deleted the old package; proceed with replace.
13965
13966            // If deleted package lived in a container, give users a chance to
13967            // relinquish resources before killing.
13968            if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) {
13969                if (DEBUG_INSTALL) {
13970                    Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
13971                }
13972                final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
13973                final ArrayList<String> pkgList = new ArrayList<String>(1);
13974                pkgList.add(deletedPackage.applicationInfo.packageName);
13975                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
13976            }
13977
13978            clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
13979                    | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
13980            clearAppProfilesLIF(pkg);
13981
13982            try {
13983                final PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags,
13984                        scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
13985                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user);
13986
13987                // Update the in-memory copy of the previous code paths.
13988                PackageSetting ps = mSettings.mPackages.get(pkgName);
13989                if (!killApp) {
13990                    if (ps.oldCodePaths == null) {
13991                        ps.oldCodePaths = new ArraySet<>();
13992                    }
13993                    Collections.addAll(ps.oldCodePaths, deletedPackage.baseCodePath);
13994                    if (deletedPackage.splitCodePaths != null) {
13995                        Collections.addAll(ps.oldCodePaths, deletedPackage.splitCodePaths);
13996                    }
13997                } else {
13998                    ps.oldCodePaths = null;
13999                }
14000                if (ps.childPackageNames != null) {
14001                    for (int i = ps.childPackageNames.size() - 1; i >= 0; --i) {
14002                        final String childPkgName = ps.childPackageNames.get(i);
14003                        final PackageSetting childPs = mSettings.mPackages.get(childPkgName);
14004                        childPs.oldCodePaths = ps.oldCodePaths;
14005                    }
14006                }
14007                prepareAppDataAfterInstallLIF(newPackage);
14008                addedPkg = true;
14009            } catch (PackageManagerException e) {
14010                res.setError("Package couldn't be installed in " + pkg.codePath, e);
14011            }
14012        }
14013
14014        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
14015            if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
14016
14017            // Revert all internal state mutations and added folders for the failed install
14018            if (addedPkg) {
14019                deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
14020                        res.removedInfo, true, null);
14021            }
14022
14023            // Restore the old package
14024            if (deletedPkg) {
14025                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
14026                File restoreFile = new File(deletedPackage.codePath);
14027                // Parse old package
14028                boolean oldExternal = isExternal(deletedPackage);
14029                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
14030                        (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) |
14031                        (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
14032                int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
14033                try {
14034                    scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime,
14035                            null);
14036                } catch (PackageManagerException e) {
14037                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
14038                            + e.getMessage());
14039                    return;
14040                }
14041
14042                synchronized (mPackages) {
14043                    // Ensure the installer package name up to date
14044                    setInstallerPackageNameLPw(deletedPackage, installerPackageName);
14045
14046                    // Update permissions for restored package
14047                    updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
14048
14049                    mSettings.writeLPr();
14050                }
14051
14052                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
14053            }
14054        } else {
14055            synchronized (mPackages) {
14056                PackageSetting ps = mSettings.peekPackageLPr(pkg.packageName);
14057                if (ps != null) {
14058                    res.removedInfo.removedForAllUsers = mPackages.get(ps.name) == null;
14059                    if (res.removedInfo.removedChildPackages != null) {
14060                        final int childCount = res.removedInfo.removedChildPackages.size();
14061                        // Iterate in reverse as we may modify the collection
14062                        for (int i = childCount - 1; i >= 0; i--) {
14063                            String childPackageName = res.removedInfo.removedChildPackages.keyAt(i);
14064                            if (res.addedChildPackages.containsKey(childPackageName)) {
14065                                res.removedInfo.removedChildPackages.removeAt(i);
14066                            } else {
14067                                PackageRemovedInfo childInfo = res.removedInfo
14068                                        .removedChildPackages.valueAt(i);
14069                                childInfo.removedForAllUsers = mPackages.get(
14070                                        childInfo.removedPackage) == null;
14071                            }
14072                        }
14073                    }
14074                }
14075            }
14076        }
14077    }
14078
14079    private void replaceSystemPackageLIF(PackageParser.Package deletedPackage,
14080            PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user,
14081            int[] allUsers, String installerPackageName, PackageInstalledInfo res) {
14082        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
14083                + ", old=" + deletedPackage);
14084
14085        final boolean disabledSystem;
14086
14087        // Remove existing system package
14088        removePackageLI(deletedPackage, true);
14089
14090        disabledSystem = disableSystemPackageLPw(deletedPackage, pkg);
14091        if (!disabledSystem) {
14092            // We didn't need to disable the .apk as a current system package,
14093            // which means we are replacing another update that is already
14094            // installed.  We need to make sure to delete the older one's .apk.
14095            res.removedInfo.args = createInstallArgsForExisting(0,
14096                    deletedPackage.applicationInfo.getCodePath(),
14097                    deletedPackage.applicationInfo.getResourcePath(),
14098                    getAppDexInstructionSets(deletedPackage.applicationInfo));
14099        } else {
14100            res.removedInfo.args = null;
14101        }
14102
14103        // Successfully disabled the old package. Now proceed with re-installation
14104        clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
14105                | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
14106        clearAppProfilesLIF(pkg);
14107
14108        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
14109        pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP,
14110                ApplicationInfo.FLAG_UPDATED_SYSTEM_APP);
14111
14112        PackageParser.Package newPackage = null;
14113        try {
14114            // Add the package to the internal data structures
14115            newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags, 0, user);
14116
14117            // Set the update and install times
14118            PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras;
14119            setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime,
14120                    System.currentTimeMillis());
14121
14122            // Update the package dynamic state if succeeded
14123            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
14124                // Now that the install succeeded make sure we remove data
14125                // directories for any child package the update removed.
14126                final int deletedChildCount = (deletedPackage.childPackages != null)
14127                        ? deletedPackage.childPackages.size() : 0;
14128                final int newChildCount = (newPackage.childPackages != null)
14129                        ? newPackage.childPackages.size() : 0;
14130                for (int i = 0; i < deletedChildCount; i++) {
14131                    PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i);
14132                    boolean childPackageDeleted = true;
14133                    for (int j = 0; j < newChildCount; j++) {
14134                        PackageParser.Package newChildPkg = newPackage.childPackages.get(j);
14135                        if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) {
14136                            childPackageDeleted = false;
14137                            break;
14138                        }
14139                    }
14140                    if (childPackageDeleted) {
14141                        PackageSetting ps = mSettings.getDisabledSystemPkgLPr(
14142                                deletedChildPkg.packageName);
14143                        if (ps != null && res.removedInfo.removedChildPackages != null) {
14144                            PackageRemovedInfo removedChildRes = res.removedInfo
14145                                    .removedChildPackages.get(deletedChildPkg.packageName);
14146                            removePackageDataLIF(ps, allUsers, removedChildRes, 0, false);
14147                            removedChildRes.removedForAllUsers = mPackages.get(ps.name) == null;
14148                        }
14149                    }
14150                }
14151
14152                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user);
14153                prepareAppDataAfterInstallLIF(newPackage);
14154            }
14155        } catch (PackageManagerException e) {
14156            res.setReturnCode(INSTALL_FAILED_INTERNAL_ERROR);
14157            res.setError("Package couldn't be installed in " + pkg.codePath, e);
14158        }
14159
14160        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
14161            // Re installation failed. Restore old information
14162            // Remove new pkg information
14163            if (newPackage != null) {
14164                removeInstalledPackageLI(newPackage, true);
14165            }
14166            // Add back the old system package
14167            try {
14168                scanPackageTracedLI(deletedPackage, policyFlags, SCAN_UPDATE_SIGNATURE, 0, user);
14169            } catch (PackageManagerException e) {
14170                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
14171            }
14172
14173            synchronized (mPackages) {
14174                if (disabledSystem) {
14175                    enableSystemPackageLPw(deletedPackage);
14176                }
14177
14178                // Ensure the installer package name up to date
14179                setInstallerPackageNameLPw(deletedPackage, installerPackageName);
14180
14181                // Update permissions for restored package
14182                updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
14183
14184                mSettings.writeLPr();
14185            }
14186
14187            Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName
14188                    + " after failed upgrade");
14189        }
14190    }
14191
14192    /**
14193     * Checks whether the parent or any of the child packages have a change shared
14194     * user. For a package to be a valid update the shred users of the parent and
14195     * the children should match. We may later support changing child shared users.
14196     * @param oldPkg The updated package.
14197     * @param newPkg The update package.
14198     * @return The shared user that change between the versions.
14199     */
14200    private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg,
14201            PackageParser.Package newPkg) {
14202        // Check parent shared user
14203        if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) {
14204            return newPkg.packageName;
14205        }
14206        // Check child shared users
14207        final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
14208        final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0;
14209        for (int i = 0; i < newChildCount; i++) {
14210            PackageParser.Package newChildPkg = newPkg.childPackages.get(i);
14211            // If this child was present, did it have the same shared user?
14212            for (int j = 0; j < oldChildCount; j++) {
14213                PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j);
14214                if (newChildPkg.packageName.equals(oldChildPkg.packageName)
14215                        && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) {
14216                    return newChildPkg.packageName;
14217                }
14218            }
14219        }
14220        return null;
14221    }
14222
14223    private void removeNativeBinariesLI(PackageSetting ps) {
14224        // Remove the lib path for the parent package
14225        if (ps != null) {
14226            NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString);
14227            // Remove the lib path for the child packages
14228            final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
14229            for (int i = 0; i < childCount; i++) {
14230                PackageSetting childPs = null;
14231                synchronized (mPackages) {
14232                    childPs = mSettings.peekPackageLPr(ps.childPackageNames.get(i));
14233                }
14234                if (childPs != null) {
14235                    NativeLibraryHelper.removeNativeBinariesLI(childPs
14236                            .legacyNativeLibraryPathString);
14237                }
14238            }
14239        }
14240    }
14241
14242    private void enableSystemPackageLPw(PackageParser.Package pkg) {
14243        // Enable the parent package
14244        mSettings.enableSystemPackageLPw(pkg.packageName);
14245        // Enable the child packages
14246        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
14247        for (int i = 0; i < childCount; i++) {
14248            PackageParser.Package childPkg = pkg.childPackages.get(i);
14249            mSettings.enableSystemPackageLPw(childPkg.packageName);
14250        }
14251    }
14252
14253    private boolean disableSystemPackageLPw(PackageParser.Package oldPkg,
14254            PackageParser.Package newPkg) {
14255        // Disable the parent package (parent always replaced)
14256        boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true);
14257        // Disable the child packages
14258        final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
14259        for (int i = 0; i < childCount; i++) {
14260            PackageParser.Package childPkg = oldPkg.childPackages.get(i);
14261            final boolean replace = newPkg.hasChildPackage(childPkg.packageName);
14262            disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace);
14263        }
14264        return disabled;
14265    }
14266
14267    private void setInstallerPackageNameLPw(PackageParser.Package pkg,
14268            String installerPackageName) {
14269        // Enable the parent package
14270        mSettings.setInstallerPackageName(pkg.packageName, installerPackageName);
14271        // Enable the child packages
14272        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
14273        for (int i = 0; i < childCount; i++) {
14274            PackageParser.Package childPkg = pkg.childPackages.get(i);
14275            mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName);
14276        }
14277    }
14278
14279    private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) {
14280        // Collect all used permissions in the UID
14281        ArraySet<String> usedPermissions = new ArraySet<>();
14282        final int packageCount = su.packages.size();
14283        for (int i = 0; i < packageCount; i++) {
14284            PackageSetting ps = su.packages.valueAt(i);
14285            if (ps.pkg == null) {
14286                continue;
14287            }
14288            final int requestedPermCount = ps.pkg.requestedPermissions.size();
14289            for (int j = 0; j < requestedPermCount; j++) {
14290                String permission = ps.pkg.requestedPermissions.get(j);
14291                BasePermission bp = mSettings.mPermissions.get(permission);
14292                if (bp != null) {
14293                    usedPermissions.add(permission);
14294                }
14295            }
14296        }
14297
14298        PermissionsState permissionsState = su.getPermissionsState();
14299        // Prune install permissions
14300        List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates();
14301        final int installPermCount = installPermStates.size();
14302        for (int i = installPermCount - 1; i >= 0;  i--) {
14303            PermissionState permissionState = installPermStates.get(i);
14304            if (!usedPermissions.contains(permissionState.getName())) {
14305                BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
14306                if (bp != null) {
14307                    permissionsState.revokeInstallPermission(bp);
14308                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
14309                            PackageManager.MASK_PERMISSION_FLAGS, 0);
14310                }
14311            }
14312        }
14313
14314        int[] runtimePermissionChangedUserIds = EmptyArray.INT;
14315
14316        // Prune runtime permissions
14317        for (int userId : allUserIds) {
14318            List<PermissionState> runtimePermStates = permissionsState
14319                    .getRuntimePermissionStates(userId);
14320            final int runtimePermCount = runtimePermStates.size();
14321            for (int i = runtimePermCount - 1; i >= 0; i--) {
14322                PermissionState permissionState = runtimePermStates.get(i);
14323                if (!usedPermissions.contains(permissionState.getName())) {
14324                    BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
14325                    if (bp != null) {
14326                        permissionsState.revokeRuntimePermission(bp, userId);
14327                        permissionsState.updatePermissionFlags(bp, userId,
14328                                PackageManager.MASK_PERMISSION_FLAGS, 0);
14329                        runtimePermissionChangedUserIds = ArrayUtils.appendInt(
14330                                runtimePermissionChangedUserIds, userId);
14331                    }
14332                }
14333            }
14334        }
14335
14336        return runtimePermissionChangedUserIds;
14337    }
14338
14339    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
14340            int[] allUsers, PackageInstalledInfo res, UserHandle user) {
14341        // Update the parent package setting
14342        updateSettingsInternalLI(newPackage, installerPackageName, allUsers, res.origUsers,
14343                res, user);
14344        // Update the child packages setting
14345        final int childCount = (newPackage.childPackages != null)
14346                ? newPackage.childPackages.size() : 0;
14347        for (int i = 0; i < childCount; i++) {
14348            PackageParser.Package childPackage = newPackage.childPackages.get(i);
14349            PackageInstalledInfo childRes = res.addedChildPackages.get(childPackage.packageName);
14350            updateSettingsInternalLI(childPackage, installerPackageName, allUsers,
14351                    childRes.origUsers, childRes, user);
14352        }
14353    }
14354
14355    private void updateSettingsInternalLI(PackageParser.Package newPackage,
14356            String installerPackageName, int[] allUsers, int[] installedForUsers,
14357            PackageInstalledInfo res, UserHandle user) {
14358        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
14359
14360        String pkgName = newPackage.packageName;
14361        synchronized (mPackages) {
14362            //write settings. the installStatus will be incomplete at this stage.
14363            //note that the new package setting would have already been
14364            //added to mPackages. It hasn't been persisted yet.
14365            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
14366            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
14367            mSettings.writeLPr();
14368            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
14369        }
14370
14371        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath);
14372        synchronized (mPackages) {
14373            updatePermissionsLPw(newPackage.packageName, newPackage,
14374                    UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
14375                            ? UPDATE_PERMISSIONS_ALL : 0));
14376            // For system-bundled packages, we assume that installing an upgraded version
14377            // of the package implies that the user actually wants to run that new code,
14378            // so we enable the package.
14379            PackageSetting ps = mSettings.mPackages.get(pkgName);
14380            final int userId = user.getIdentifier();
14381            if (ps != null) {
14382                if (isSystemApp(newPackage)) {
14383                    if (DEBUG_INSTALL) {
14384                        Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
14385                    }
14386                    // Enable system package for requested users
14387                    if (res.origUsers != null) {
14388                        for (int origUserId : res.origUsers) {
14389                            if (userId == UserHandle.USER_ALL || userId == origUserId) {
14390                                ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
14391                                        origUserId, installerPackageName);
14392                            }
14393                        }
14394                    }
14395                    // Also convey the prior install/uninstall state
14396                    if (allUsers != null && installedForUsers != null) {
14397                        for (int currentUserId : allUsers) {
14398                            final boolean installed = ArrayUtils.contains(
14399                                    installedForUsers, currentUserId);
14400                            if (DEBUG_INSTALL) {
14401                                Slog.d(TAG, "    user " + currentUserId + " => " + installed);
14402                            }
14403                            ps.setInstalled(installed, currentUserId);
14404                        }
14405                        // these install state changes will be persisted in the
14406                        // upcoming call to mSettings.writeLPr().
14407                    }
14408                }
14409                // It's implied that when a user requests installation, they want the app to be
14410                // installed and enabled.
14411                if (userId != UserHandle.USER_ALL) {
14412                    ps.setInstalled(true, userId);
14413                    ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName);
14414                }
14415            }
14416            res.name = pkgName;
14417            res.uid = newPackage.applicationInfo.uid;
14418            res.pkg = newPackage;
14419            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
14420            mSettings.setInstallerPackageName(pkgName, installerPackageName);
14421            res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
14422            //to update install status
14423            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
14424            mSettings.writeLPr();
14425            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
14426        }
14427
14428        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
14429    }
14430
14431    private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) {
14432        try {
14433            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage");
14434            installPackageLI(args, res);
14435        } finally {
14436            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
14437        }
14438    }
14439
14440    private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
14441        final int installFlags = args.installFlags;
14442        final String installerPackageName = args.installerPackageName;
14443        final String volumeUuid = args.volumeUuid;
14444        final File tmpPackageFile = new File(args.getCodePath());
14445        final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
14446        final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0)
14447                || (args.volumeUuid != null));
14448        final boolean ephemeral = ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0);
14449        final boolean forceSdk = ((installFlags & PackageManager.INSTALL_FORCE_SDK) != 0);
14450        boolean replace = false;
14451        int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE;
14452        if (args.move != null) {
14453            // moving a complete application; perform an initial scan on the new install location
14454            scanFlags |= SCAN_INITIAL;
14455        }
14456        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
14457            scanFlags |= SCAN_DONT_KILL_APP;
14458        }
14459
14460        // Result object to be returned
14461        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
14462
14463        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
14464
14465        // Sanity check
14466        if (ephemeral && (forwardLocked || onExternal)) {
14467            Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked
14468                    + " external=" + onExternal);
14469            res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID);
14470            return;
14471        }
14472
14473        // Retrieve PackageSettings and parse package
14474        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
14475                | PackageParser.PARSE_ENFORCE_CODE
14476                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
14477                | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0)
14478                | (ephemeral ? PackageParser.PARSE_IS_EPHEMERAL : 0)
14479                | (forceSdk ? PackageParser.PARSE_FORCE_SDK : 0);
14480        PackageParser pp = new PackageParser();
14481        pp.setSeparateProcesses(mSeparateProcesses);
14482        pp.setDisplayMetrics(mMetrics);
14483
14484        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
14485        final PackageParser.Package pkg;
14486        try {
14487            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
14488        } catch (PackageParserException e) {
14489            res.setError("Failed parse during installPackageLI", e);
14490            return;
14491        } finally {
14492            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
14493        }
14494
14495        // If we are installing a clustered package add results for the children
14496        if (pkg.childPackages != null) {
14497            synchronized (mPackages) {
14498                final int childCount = pkg.childPackages.size();
14499                for (int i = 0; i < childCount; i++) {
14500                    PackageParser.Package childPkg = pkg.childPackages.get(i);
14501                    PackageInstalledInfo childRes = new PackageInstalledInfo();
14502                    childRes.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
14503                    childRes.pkg = childPkg;
14504                    childRes.name = childPkg.packageName;
14505                    PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName);
14506                    if (childPs != null) {
14507                        childRes.origUsers = childPs.queryInstalledUsers(
14508                                sUserManager.getUserIds(), true);
14509                    }
14510                    if ((mPackages.containsKey(childPkg.packageName))) {
14511                        childRes.removedInfo = new PackageRemovedInfo();
14512                        childRes.removedInfo.removedPackage = childPkg.packageName;
14513                    }
14514                    if (res.addedChildPackages == null) {
14515                        res.addedChildPackages = new ArrayMap<>();
14516                    }
14517                    res.addedChildPackages.put(childPkg.packageName, childRes);
14518                }
14519            }
14520        }
14521
14522        // If package doesn't declare API override, mark that we have an install
14523        // time CPU ABI override.
14524        if (TextUtils.isEmpty(pkg.cpuAbiOverride)) {
14525            pkg.cpuAbiOverride = args.abiOverride;
14526        }
14527
14528        String pkgName = res.name = pkg.packageName;
14529        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
14530            if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
14531                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
14532                return;
14533            }
14534        }
14535
14536        try {
14537            // either use what we've been given or parse directly from the APK
14538            if (args.certificates != null) {
14539                try {
14540                    PackageParser.populateCertificates(pkg, args.certificates);
14541                } catch (PackageParserException e) {
14542                    // there was something wrong with the certificates we were given;
14543                    // try to pull them from the APK
14544                    PackageParser.collectCertificates(pkg, parseFlags);
14545                }
14546            } else {
14547                PackageParser.collectCertificates(pkg, parseFlags);
14548            }
14549        } catch (PackageParserException e) {
14550            res.setError("Failed collect during installPackageLI", e);
14551            return;
14552        }
14553
14554        // Get rid of all references to package scan path via parser.
14555        pp = null;
14556        String oldCodePath = null;
14557        boolean systemApp = false;
14558        synchronized (mPackages) {
14559            // Check if installing already existing package
14560            if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
14561                String oldName = mSettings.mRenamedPackages.get(pkgName);
14562                if (pkg.mOriginalPackages != null
14563                        && pkg.mOriginalPackages.contains(oldName)
14564                        && mPackages.containsKey(oldName)) {
14565                    // This package is derived from an original package,
14566                    // and this device has been updating from that original
14567                    // name.  We must continue using the original name, so
14568                    // rename the new package here.
14569                    pkg.setPackageName(oldName);
14570                    pkgName = pkg.packageName;
14571                    replace = true;
14572                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
14573                            + oldName + " pkgName=" + pkgName);
14574                } else if (mPackages.containsKey(pkgName)) {
14575                    // This package, under its official name, already exists
14576                    // on the device; we should replace it.
14577                    replace = true;
14578                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
14579                }
14580
14581                // Child packages are installed through the parent package
14582                if (pkg.parentPackage != null) {
14583                    res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
14584                            "Package " + pkg.packageName + " is child of package "
14585                                    + pkg.parentPackage.parentPackage + ". Child packages "
14586                                    + "can be updated only through the parent package.");
14587                    return;
14588                }
14589
14590                if (replace) {
14591                    // Prevent apps opting out from runtime permissions
14592                    PackageParser.Package oldPackage = mPackages.get(pkgName);
14593                    final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion;
14594                    final int newTargetSdk = pkg.applicationInfo.targetSdkVersion;
14595                    if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1
14596                            && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) {
14597                        res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE,
14598                                "Package " + pkg.packageName + " new target SDK " + newTargetSdk
14599                                        + " doesn't support runtime permissions but the old"
14600                                        + " target SDK " + oldTargetSdk + " does.");
14601                        return;
14602                    }
14603
14604                    // Prevent installing of child packages
14605                    if (oldPackage.parentPackage != null) {
14606                        res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
14607                                "Package " + pkg.packageName + " is child of package "
14608                                        + oldPackage.parentPackage + ". Child packages "
14609                                        + "can be updated only through the parent package.");
14610                        return;
14611                    }
14612                }
14613            }
14614
14615            PackageSetting ps = mSettings.mPackages.get(pkgName);
14616            if (ps != null) {
14617                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
14618
14619                // Quick sanity check that we're signed correctly if updating;
14620                // we'll check this again later when scanning, but we want to
14621                // bail early here before tripping over redefined permissions.
14622                if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
14623                    if (!checkUpgradeKeySetLP(ps, pkg)) {
14624                        res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
14625                                + pkg.packageName + " upgrade keys do not match the "
14626                                + "previously installed version");
14627                        return;
14628                    }
14629                } else {
14630                    try {
14631                        verifySignaturesLP(ps, pkg);
14632                    } catch (PackageManagerException e) {
14633                        res.setError(e.error, e.getMessage());
14634                        return;
14635                    }
14636                }
14637
14638                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
14639                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
14640                    systemApp = (ps.pkg.applicationInfo.flags &
14641                            ApplicationInfo.FLAG_SYSTEM) != 0;
14642                }
14643                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
14644            }
14645
14646            // Check whether the newly-scanned package wants to define an already-defined perm
14647            int N = pkg.permissions.size();
14648            for (int i = N-1; i >= 0; i--) {
14649                PackageParser.Permission perm = pkg.permissions.get(i);
14650                BasePermission bp = mSettings.mPermissions.get(perm.info.name);
14651                if (bp != null) {
14652                    // If the defining package is signed with our cert, it's okay.  This
14653                    // also includes the "updating the same package" case, of course.
14654                    // "updating same package" could also involve key-rotation.
14655                    final boolean sigsOk;
14656                    if (bp.sourcePackage.equals(pkg.packageName)
14657                            && (bp.packageSetting instanceof PackageSetting)
14658                            && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting,
14659                                    scanFlags))) {
14660                        sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg);
14661                    } else {
14662                        sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures,
14663                                pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
14664                    }
14665                    if (!sigsOk) {
14666                        // If the owning package is the system itself, we log but allow
14667                        // install to proceed; we fail the install on all other permission
14668                        // redefinitions.
14669                        if (!bp.sourcePackage.equals("android")) {
14670                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
14671                                    + pkg.packageName + " attempting to redeclare permission "
14672                                    + perm.info.name + " already owned by " + bp.sourcePackage);
14673                            res.origPermission = perm.info.name;
14674                            res.origPackage = bp.sourcePackage;
14675                            return;
14676                        } else {
14677                            Slog.w(TAG, "Package " + pkg.packageName
14678                                    + " attempting to redeclare system permission "
14679                                    + perm.info.name + "; ignoring new declaration");
14680                            pkg.permissions.remove(i);
14681                        }
14682                    }
14683                }
14684            }
14685        }
14686
14687        if (systemApp) {
14688            if (onExternal) {
14689                // Abort update; system app can't be replaced with app on sdcard
14690                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
14691                        "Cannot install updates to system apps on sdcard");
14692                return;
14693            } else if (ephemeral) {
14694                // Abort update; system app can't be replaced with an ephemeral app
14695                res.setError(INSTALL_FAILED_EPHEMERAL_INVALID,
14696                        "Cannot update a system app with an ephemeral app");
14697                return;
14698            }
14699        }
14700
14701        if (args.move != null) {
14702            // We did an in-place move, so dex is ready to roll
14703            scanFlags |= SCAN_NO_DEX;
14704            scanFlags |= SCAN_MOVE;
14705
14706            synchronized (mPackages) {
14707                final PackageSetting ps = mSettings.mPackages.get(pkgName);
14708                if (ps == null) {
14709                    res.setError(INSTALL_FAILED_INTERNAL_ERROR,
14710                            "Missing settings for moved package " + pkgName);
14711                }
14712
14713                // We moved the entire application as-is, so bring over the
14714                // previously derived ABI information.
14715                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
14716                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
14717            }
14718
14719        } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) {
14720            // Enable SCAN_NO_DEX flag to skip dexopt at a later stage
14721            scanFlags |= SCAN_NO_DEX;
14722
14723            try {
14724                String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ?
14725                    args.abiOverride : pkg.cpuAbiOverride);
14726                derivePackageAbi(pkg, new File(pkg.codePath), abiOverride,
14727                        true /* extract libs */);
14728            } catch (PackageManagerException pme) {
14729                Slog.e(TAG, "Error deriving application ABI", pme);
14730                res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI");
14731                return;
14732            }
14733
14734            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
14735            // Do not run PackageDexOptimizer through the local performDexOpt
14736            // method because `pkg` is not in `mPackages` yet.
14737            int result = mPackageDexOptimizer.performDexOpt(pkg, null /* instructionSets */,
14738                    false /* checkProfiles */, getCompilerFilterForReason(REASON_INSTALL));
14739            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
14740            if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
14741                String msg = "Extracting package failed for " + pkgName;
14742                res.setError(INSTALL_FAILED_DEXOPT, msg);
14743                return;
14744            }
14745
14746            // Notify BackgroundDexOptService that the package has been changed.
14747            // If this is an update of a package which used to fail to compile,
14748            // BDOS will remove it from its blacklist.
14749            BackgroundDexOptService.notifyPackageChanged(pkg.packageName);
14750        }
14751
14752        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
14753            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
14754            return;
14755        }
14756
14757        startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg);
14758
14759        try (PackageFreezer freezer = freezePackageForInstall(pkgName, installFlags,
14760                "installPackageLI")) {
14761            if (replace) {
14762                replacePackageLIF(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user,
14763                        installerPackageName, res);
14764            } else {
14765                installNewPackageLIF(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
14766                        args.user, installerPackageName, volumeUuid, res);
14767            }
14768        }
14769        synchronized (mPackages) {
14770            final PackageSetting ps = mSettings.mPackages.get(pkgName);
14771            if (ps != null) {
14772                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
14773            }
14774
14775            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
14776            for (int i = 0; i < childCount; i++) {
14777                PackageParser.Package childPkg = pkg.childPackages.get(i);
14778                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
14779                PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName);
14780                if (childPs != null) {
14781                    childRes.newUsers = childPs.queryInstalledUsers(
14782                            sUserManager.getUserIds(), true);
14783                }
14784            }
14785        }
14786    }
14787
14788    private void startIntentFilterVerifications(int userId, boolean replacing,
14789            PackageParser.Package pkg) {
14790        if (mIntentFilterVerifierComponent == null) {
14791            Slog.w(TAG, "No IntentFilter verification will not be done as "
14792                    + "there is no IntentFilterVerifier available!");
14793            return;
14794        }
14795
14796        final int verifierUid = getPackageUid(
14797                mIntentFilterVerifierComponent.getPackageName(),
14798                MATCH_DEBUG_TRIAGED_MISSING,
14799                (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId);
14800
14801        Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
14802        msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid);
14803        mHandler.sendMessage(msg);
14804
14805        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
14806        for (int i = 0; i < childCount; i++) {
14807            PackageParser.Package childPkg = pkg.childPackages.get(i);
14808            msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
14809            msg.obj = new IFVerificationParams(childPkg, replacing, userId, verifierUid);
14810            mHandler.sendMessage(msg);
14811        }
14812    }
14813
14814    private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing,
14815            PackageParser.Package pkg) {
14816        int size = pkg.activities.size();
14817        if (size == 0) {
14818            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
14819                    "No activity, so no need to verify any IntentFilter!");
14820            return;
14821        }
14822
14823        final boolean hasDomainURLs = hasDomainURLs(pkg);
14824        if (!hasDomainURLs) {
14825            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
14826                    "No domain URLs, so no need to verify any IntentFilter!");
14827            return;
14828        }
14829
14830        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId
14831                + " if any IntentFilter from the " + size
14832                + " Activities needs verification ...");
14833
14834        int count = 0;
14835        final String packageName = pkg.packageName;
14836
14837        synchronized (mPackages) {
14838            // If this is a new install and we see that we've already run verification for this
14839            // package, we have nothing to do: it means the state was restored from backup.
14840            if (!replacing) {
14841                IntentFilterVerificationInfo ivi =
14842                        mSettings.getIntentFilterVerificationLPr(packageName);
14843                if (ivi != null) {
14844                    if (DEBUG_DOMAIN_VERIFICATION) {
14845                        Slog.i(TAG, "Package " + packageName+ " already verified: status="
14846                                + ivi.getStatusString());
14847                    }
14848                    return;
14849                }
14850            }
14851
14852            // If any filters need to be verified, then all need to be.
14853            boolean needToVerify = false;
14854            for (PackageParser.Activity a : pkg.activities) {
14855                for (ActivityIntentInfo filter : a.intents) {
14856                    if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) {
14857                        if (DEBUG_DOMAIN_VERIFICATION) {
14858                            Slog.d(TAG, "Intent filter needs verification, so processing all filters");
14859                        }
14860                        needToVerify = true;
14861                        break;
14862                    }
14863                }
14864            }
14865
14866            if (needToVerify) {
14867                final int verificationId = mIntentFilterVerificationToken++;
14868                for (PackageParser.Activity a : pkg.activities) {
14869                    for (ActivityIntentInfo filter : a.intents) {
14870                        if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) {
14871                            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
14872                                    "Verification needed for IntentFilter:" + filter.toString());
14873                            mIntentFilterVerifier.addOneIntentFilterVerification(
14874                                    verifierUid, userId, verificationId, filter, packageName);
14875                            count++;
14876                        }
14877                    }
14878                }
14879            }
14880        }
14881
14882        if (count > 0) {
14883            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count
14884                    + " IntentFilter verification" + (count > 1 ? "s" : "")
14885                    +  " for userId:" + userId);
14886            mIntentFilterVerifier.startVerifications(userId);
14887        } else {
14888            if (DEBUG_DOMAIN_VERIFICATION) {
14889                Slog.d(TAG, "No filters or not all autoVerify for " + packageName);
14890            }
14891        }
14892    }
14893
14894    private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) {
14895        final ComponentName cn  = filter.activity.getComponentName();
14896        final String packageName = cn.getPackageName();
14897
14898        IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr(
14899                packageName);
14900        if (ivi == null) {
14901            return true;
14902        }
14903        int status = ivi.getStatus();
14904        switch (status) {
14905            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
14906            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
14907                return true;
14908
14909            default:
14910                // Nothing to do
14911                return false;
14912        }
14913    }
14914
14915    private static boolean isMultiArch(ApplicationInfo info) {
14916        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
14917    }
14918
14919    private static boolean isExternal(PackageParser.Package pkg) {
14920        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
14921    }
14922
14923    private static boolean isExternal(PackageSetting ps) {
14924        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
14925    }
14926
14927    private static boolean isEphemeral(PackageParser.Package pkg) {
14928        return pkg.applicationInfo.isEphemeralApp();
14929    }
14930
14931    private static boolean isEphemeral(PackageSetting ps) {
14932        return ps.pkg != null && isEphemeral(ps.pkg);
14933    }
14934
14935    private static boolean isSystemApp(PackageParser.Package pkg) {
14936        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
14937    }
14938
14939    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
14940        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
14941    }
14942
14943    private static boolean hasDomainURLs(PackageParser.Package pkg) {
14944        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0;
14945    }
14946
14947    private static boolean isSystemApp(PackageSetting ps) {
14948        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
14949    }
14950
14951    private static boolean isUpdatedSystemApp(PackageSetting ps) {
14952        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
14953    }
14954
14955    private int packageFlagsToInstallFlags(PackageSetting ps) {
14956        int installFlags = 0;
14957        if (isEphemeral(ps)) {
14958            installFlags |= PackageManager.INSTALL_EPHEMERAL;
14959        }
14960        if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) {
14961            // This existing package was an external ASEC install when we have
14962            // the external flag without a UUID
14963            installFlags |= PackageManager.INSTALL_EXTERNAL;
14964        }
14965        if (ps.isForwardLocked()) {
14966            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
14967        }
14968        return installFlags;
14969    }
14970
14971    private String getVolumeUuidForPackage(PackageParser.Package pkg) {
14972        if (isExternal(pkg)) {
14973            if (TextUtils.isEmpty(pkg.volumeUuid)) {
14974                return StorageManager.UUID_PRIMARY_PHYSICAL;
14975            } else {
14976                return pkg.volumeUuid;
14977            }
14978        } else {
14979            return StorageManager.UUID_PRIVATE_INTERNAL;
14980        }
14981    }
14982
14983    private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) {
14984        if (isExternal(pkg)) {
14985            if (TextUtils.isEmpty(pkg.volumeUuid)) {
14986                return mSettings.getExternalVersion();
14987            } else {
14988                return mSettings.findOrCreateVersion(pkg.volumeUuid);
14989            }
14990        } else {
14991            return mSettings.getInternalVersion();
14992        }
14993    }
14994
14995    private void deleteTempPackageFiles() {
14996        final FilenameFilter filter = new FilenameFilter() {
14997            public boolean accept(File dir, String name) {
14998                return name.startsWith("vmdl") && name.endsWith(".tmp");
14999            }
15000        };
15001        for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) {
15002            file.delete();
15003        }
15004    }
15005
15006    @Override
15007    public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId,
15008            int flags) {
15009        deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId,
15010                flags);
15011    }
15012
15013    @Override
15014    public void deletePackage(final String packageName,
15015            final IPackageDeleteObserver2 observer, final int userId, final int deleteFlags) {
15016        mContext.enforceCallingOrSelfPermission(
15017                android.Manifest.permission.DELETE_PACKAGES, null);
15018        Preconditions.checkNotNull(packageName);
15019        Preconditions.checkNotNull(observer);
15020        final int uid = Binder.getCallingUid();
15021        final boolean deleteAllUsers = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0;
15022        final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId };
15023        if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) {
15024            mContext.enforceCallingOrSelfPermission(
15025                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
15026                    "deletePackage for user " + userId);
15027        }
15028
15029        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
15030            try {
15031                observer.onPackageDeleted(packageName,
15032                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
15033            } catch (RemoteException re) {
15034            }
15035            return;
15036        }
15037
15038        if (!deleteAllUsers && getBlockUninstallForUser(packageName, userId)) {
15039            try {
15040                observer.onPackageDeleted(packageName,
15041                        PackageManager.DELETE_FAILED_OWNER_BLOCKED, null);
15042            } catch (RemoteException re) {
15043            }
15044            return;
15045        }
15046
15047        if (DEBUG_REMOVE) {
15048            Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId
15049                    + " deleteAllUsers: " + deleteAllUsers );
15050        }
15051        // Queue up an async operation since the package deletion may take a little while.
15052        mHandler.post(new Runnable() {
15053            public void run() {
15054                mHandler.removeCallbacks(this);
15055                int returnCode;
15056                if (!deleteAllUsers) {
15057                    returnCode = deletePackageX(packageName, userId, deleteFlags);
15058                } else {
15059                    int[] blockUninstallUserIds = getBlockUninstallForUsers(packageName, users);
15060                    // If nobody is blocking uninstall, proceed with delete for all users
15061                    if (ArrayUtils.isEmpty(blockUninstallUserIds)) {
15062                        returnCode = deletePackageX(packageName, userId, deleteFlags);
15063                    } else {
15064                        // Otherwise uninstall individually for users with blockUninstalls=false
15065                        final int userFlags = deleteFlags & ~PackageManager.DELETE_ALL_USERS;
15066                        for (int userId : users) {
15067                            if (!ArrayUtils.contains(blockUninstallUserIds, userId)) {
15068                                returnCode = deletePackageX(packageName, userId, userFlags);
15069                                if (returnCode != PackageManager.DELETE_SUCCEEDED) {
15070                                    Slog.w(TAG, "Package delete failed for user " + userId
15071                                            + ", returnCode " + returnCode);
15072                                }
15073                            }
15074                        }
15075                        // The app has only been marked uninstalled for certain users.
15076                        // We still need to report that delete was blocked
15077                        returnCode = PackageManager.DELETE_FAILED_OWNER_BLOCKED;
15078                    }
15079                }
15080                try {
15081                    observer.onPackageDeleted(packageName, returnCode, null);
15082                } catch (RemoteException e) {
15083                    Log.i(TAG, "Observer no longer exists.");
15084                } //end catch
15085            } //end run
15086        });
15087    }
15088
15089    private int[] getBlockUninstallForUsers(String packageName, int[] userIds) {
15090        int[] result = EMPTY_INT_ARRAY;
15091        for (int userId : userIds) {
15092            if (getBlockUninstallForUser(packageName, userId)) {
15093                result = ArrayUtils.appendInt(result, userId);
15094            }
15095        }
15096        return result;
15097    }
15098
15099    @Override
15100    public boolean isPackageDeviceAdminOnAnyUser(String packageName) {
15101        return isPackageDeviceAdmin(packageName, UserHandle.USER_ALL);
15102    }
15103
15104    private boolean isPackageDeviceAdmin(String packageName, int userId) {
15105        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
15106                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
15107        try {
15108            if (dpm != null) {
15109                final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent(
15110                        /* callingUserOnly =*/ false);
15111                final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null
15112                        : deviceOwnerComponentName.getPackageName();
15113                // Does the package contains the device owner?
15114                // TODO Do we have to do it even if userId != UserHandle.USER_ALL?  Otherwise,
15115                // this check is probably not needed, since DO should be registered as a device
15116                // admin on some user too. (Original bug for this: b/17657954)
15117                if (packageName.equals(deviceOwnerPackageName)) {
15118                    return true;
15119                }
15120                // Does it contain a device admin for any user?
15121                int[] users;
15122                if (userId == UserHandle.USER_ALL) {
15123                    users = sUserManager.getUserIds();
15124                } else {
15125                    users = new int[]{userId};
15126                }
15127                for (int i = 0; i < users.length; ++i) {
15128                    if (dpm.packageHasActiveAdmins(packageName, users[i])) {
15129                        return true;
15130                    }
15131                }
15132            }
15133        } catch (RemoteException e) {
15134        }
15135        return false;
15136    }
15137
15138    private boolean shouldKeepUninstalledPackageLPr(String packageName) {
15139        return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName);
15140    }
15141
15142    /**
15143     *  This method is an internal method that could be get invoked either
15144     *  to delete an installed package or to clean up a failed installation.
15145     *  After deleting an installed package, a broadcast is sent to notify any
15146     *  listeners that the package has been removed. For cleaning up a failed
15147     *  installation, the broadcast is not necessary since the package's
15148     *  installation wouldn't have sent the initial broadcast either
15149     *  The key steps in deleting a package are
15150     *  deleting the package information in internal structures like mPackages,
15151     *  deleting the packages base directories through installd
15152     *  updating mSettings to reflect current status
15153     *  persisting settings for later use
15154     *  sending a broadcast if necessary
15155     */
15156    private int deletePackageX(String packageName, int userId, int deleteFlags) {
15157        final PackageRemovedInfo info = new PackageRemovedInfo();
15158        final boolean res;
15159
15160        final UserHandle removeForUser = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0
15161                ? UserHandle.ALL : new UserHandle(userId);
15162
15163        if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) {
15164            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
15165            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
15166        }
15167
15168        PackageSetting uninstalledPs = null;
15169
15170        // for the uninstall-updates case and restricted profiles, remember the per-
15171        // user handle installed state
15172        int[] allUsers;
15173        synchronized (mPackages) {
15174            uninstalledPs = mSettings.mPackages.get(packageName);
15175            if (uninstalledPs == null) {
15176                Slog.w(TAG, "Not removing non-existent package " + packageName);
15177                return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
15178            }
15179            allUsers = sUserManager.getUserIds();
15180            info.origUsers = uninstalledPs.queryInstalledUsers(allUsers, true);
15181        }
15182
15183        synchronized (mInstallLock) {
15184            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
15185            try (PackageFreezer freezer = freezePackageForDelete(packageName, deleteFlags,
15186                    "deletePackageX")) {
15187                res = deletePackageLIF(packageName, removeForUser, true, allUsers,
15188                        deleteFlags | REMOVE_CHATTY, info, true, null);
15189            }
15190            synchronized (mPackages) {
15191                if (res) {
15192                    mEphemeralApplicationRegistry.onPackageUninstalledLPw(uninstalledPs.pkg);
15193                }
15194            }
15195        }
15196
15197        if (res) {
15198            final boolean killApp = (deleteFlags & PackageManager.DELETE_DONT_KILL_APP) == 0;
15199            info.sendPackageRemovedBroadcasts(killApp);
15200            info.sendSystemPackageUpdatedBroadcasts();
15201            info.sendSystemPackageAppearedBroadcasts();
15202        }
15203        // Force a gc here.
15204        Runtime.getRuntime().gc();
15205        // Delete the resources here after sending the broadcast to let
15206        // other processes clean up before deleting resources.
15207        if (info.args != null) {
15208            synchronized (mInstallLock) {
15209                info.args.doPostDeleteLI(true);
15210            }
15211        }
15212
15213        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
15214    }
15215
15216    class PackageRemovedInfo {
15217        String removedPackage;
15218        int uid = -1;
15219        int removedAppId = -1;
15220        int[] origUsers;
15221        int[] removedUsers = null;
15222        boolean isRemovedPackageSystemUpdate = false;
15223        boolean isUpdate;
15224        boolean dataRemoved;
15225        boolean removedForAllUsers;
15226        // Clean up resources deleted packages.
15227        InstallArgs args = null;
15228        ArrayMap<String, PackageRemovedInfo> removedChildPackages;
15229        ArrayMap<String, PackageInstalledInfo> appearedChildPackages;
15230
15231        void sendPackageRemovedBroadcasts(boolean killApp) {
15232            sendPackageRemovedBroadcastInternal(killApp);
15233            final int childCount = removedChildPackages != null ? removedChildPackages.size() : 0;
15234            for (int i = 0; i < childCount; i++) {
15235                PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
15236                childInfo.sendPackageRemovedBroadcastInternal(killApp);
15237            }
15238        }
15239
15240        void sendSystemPackageUpdatedBroadcasts() {
15241            if (isRemovedPackageSystemUpdate) {
15242                sendSystemPackageUpdatedBroadcastsInternal();
15243                final int childCount = (removedChildPackages != null)
15244                        ? removedChildPackages.size() : 0;
15245                for (int i = 0; i < childCount; i++) {
15246                    PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
15247                    if (childInfo.isRemovedPackageSystemUpdate) {
15248                        childInfo.sendSystemPackageUpdatedBroadcastsInternal();
15249                    }
15250                }
15251            }
15252        }
15253
15254        void sendSystemPackageAppearedBroadcasts() {
15255            final int packageCount = (appearedChildPackages != null)
15256                    ? appearedChildPackages.size() : 0;
15257            for (int i = 0; i < packageCount; i++) {
15258                PackageInstalledInfo installedInfo = appearedChildPackages.valueAt(i);
15259                for (int userId : installedInfo.newUsers) {
15260                    sendPackageAddedForUser(installedInfo.name, true,
15261                            UserHandle.getAppId(installedInfo.uid), userId);
15262                }
15263            }
15264        }
15265
15266        private void sendSystemPackageUpdatedBroadcastsInternal() {
15267            Bundle extras = new Bundle(2);
15268            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
15269            extras.putBoolean(Intent.EXTRA_REPLACING, true);
15270            sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, removedPackage,
15271                    extras, 0, null, null, null);
15272            sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, removedPackage,
15273                    extras, 0, null, null, null);
15274            sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null,
15275                    null, 0, removedPackage, null, null);
15276        }
15277
15278        private void sendPackageRemovedBroadcastInternal(boolean killApp) {
15279            Bundle extras = new Bundle(2);
15280            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0  ? removedAppId : uid);
15281            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, dataRemoved);
15282            extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, !killApp);
15283            if (isUpdate || isRemovedPackageSystemUpdate) {
15284                extras.putBoolean(Intent.EXTRA_REPLACING, true);
15285            }
15286            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
15287            if (removedPackage != null) {
15288                sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
15289                        extras, 0, null, null, removedUsers);
15290                if (dataRemoved && !isRemovedPackageSystemUpdate) {
15291                    sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED,
15292                            removedPackage, extras, 0, null, null, removedUsers);
15293                }
15294            }
15295            if (removedAppId >= 0) {
15296                sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, 0, null, null,
15297                        removedUsers);
15298            }
15299        }
15300    }
15301
15302    /*
15303     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
15304     * flag is not set, the data directory is removed as well.
15305     * make sure this flag is set for partially installed apps. If not its meaningless to
15306     * delete a partially installed application.
15307     */
15308    private void removePackageDataLIF(PackageSetting ps, int[] allUserHandles,
15309            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
15310        String packageName = ps.name;
15311        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
15312        // Retrieve object to delete permissions for shared user later on
15313        final PackageParser.Package deletedPkg;
15314        final PackageSetting deletedPs;
15315        // reader
15316        synchronized (mPackages) {
15317            deletedPkg = mPackages.get(packageName);
15318            deletedPs = mSettings.mPackages.get(packageName);
15319            if (outInfo != null) {
15320                outInfo.removedPackage = packageName;
15321                outInfo.removedUsers = deletedPs != null
15322                        ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true)
15323                        : null;
15324            }
15325        }
15326
15327        removePackageLI(ps, (flags & REMOVE_CHATTY) != 0);
15328
15329        if ((flags & PackageManager.DELETE_KEEP_DATA) == 0) {
15330            destroyAppDataLIF(deletedPkg, UserHandle.USER_ALL,
15331                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
15332            destroyAppProfilesLIF(deletedPkg);
15333            if (outInfo != null) {
15334                outInfo.dataRemoved = true;
15335            }
15336            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
15337        }
15338
15339        // writer
15340        synchronized (mPackages) {
15341            if (deletedPs != null) {
15342                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
15343                    clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL);
15344                    clearDefaultBrowserIfNeeded(packageName);
15345                    if (outInfo != null) {
15346                        mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
15347                        outInfo.removedAppId = mSettings.removePackageLPw(packageName);
15348                    }
15349                    updatePermissionsLPw(deletedPs.name, null, 0);
15350                    if (deletedPs.sharedUser != null) {
15351                        // Remove permissions associated with package. Since runtime
15352                        // permissions are per user we have to kill the removed package
15353                        // or packages running under the shared user of the removed
15354                        // package if revoking the permissions requested only by the removed
15355                        // package is successful and this causes a change in gids.
15356                        for (int userId : UserManagerService.getInstance().getUserIds()) {
15357                            final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs,
15358                                    userId);
15359                            if (userIdToKill == UserHandle.USER_ALL
15360                                    || userIdToKill >= UserHandle.USER_SYSTEM) {
15361                                // If gids changed for this user, kill all affected packages.
15362                                mHandler.post(new Runnable() {
15363                                    @Override
15364                                    public void run() {
15365                                        // This has to happen with no lock held.
15366                                        killApplication(deletedPs.name, deletedPs.appId,
15367                                                KILL_APP_REASON_GIDS_CHANGED);
15368                                    }
15369                                });
15370                                break;
15371                            }
15372                        }
15373                    }
15374                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
15375                }
15376                // make sure to preserve per-user disabled state if this removal was just
15377                // a downgrade of a system app to the factory package
15378                if (allUserHandles != null && outInfo != null && outInfo.origUsers != null) {
15379                    if (DEBUG_REMOVE) {
15380                        Slog.d(TAG, "Propagating install state across downgrade");
15381                    }
15382                    for (int userId : allUserHandles) {
15383                        final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
15384                        if (DEBUG_REMOVE) {
15385                            Slog.d(TAG, "    user " + userId + " => " + installed);
15386                        }
15387                        ps.setInstalled(installed, userId);
15388                    }
15389                }
15390            }
15391            // can downgrade to reader
15392            if (writeSettings) {
15393                // Save settings now
15394                mSettings.writeLPr();
15395            }
15396        }
15397        if (outInfo != null) {
15398            // A user ID was deleted here. Go through all users and remove it
15399            // from KeyStore.
15400            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId);
15401        }
15402    }
15403
15404    static boolean locationIsPrivileged(File path) {
15405        try {
15406            final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
15407                    .getCanonicalPath();
15408            return path.getCanonicalPath().startsWith(privilegedAppDir);
15409        } catch (IOException e) {
15410            Slog.e(TAG, "Unable to access code path " + path);
15411        }
15412        return false;
15413    }
15414
15415    /*
15416     * Tries to delete system package.
15417     */
15418    private boolean deleteSystemPackageLIF(PackageParser.Package deletedPkg,
15419            PackageSetting deletedPs, int[] allUserHandles, int flags, PackageRemovedInfo outInfo,
15420            boolean writeSettings) {
15421        if (deletedPs.parentPackageName != null) {
15422            Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName);
15423            return false;
15424        }
15425
15426        final boolean applyUserRestrictions
15427                = (allUserHandles != null) && (outInfo.origUsers != null);
15428        final PackageSetting disabledPs;
15429        // Confirm if the system package has been updated
15430        // An updated system app can be deleted. This will also have to restore
15431        // the system pkg from system partition
15432        // reader
15433        synchronized (mPackages) {
15434            disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPs.name);
15435        }
15436
15437        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName
15438                + " disabledPs=" + disabledPs);
15439
15440        if (disabledPs == null) {
15441            Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName);
15442            return false;
15443        } else if (DEBUG_REMOVE) {
15444            Slog.d(TAG, "Deleting system pkg from data partition");
15445        }
15446
15447        if (DEBUG_REMOVE) {
15448            if (applyUserRestrictions) {
15449                Slog.d(TAG, "Remembering install states:");
15450                for (int userId : allUserHandles) {
15451                    final boolean finstalled = ArrayUtils.contains(outInfo.origUsers, userId);
15452                    Slog.d(TAG, "   u=" + userId + " inst=" + finstalled);
15453                }
15454            }
15455        }
15456
15457        // Delete the updated package
15458        outInfo.isRemovedPackageSystemUpdate = true;
15459        if (outInfo.removedChildPackages != null) {
15460            final int childCount = (deletedPs.childPackageNames != null)
15461                    ? deletedPs.childPackageNames.size() : 0;
15462            for (int i = 0; i < childCount; i++) {
15463                String childPackageName = deletedPs.childPackageNames.get(i);
15464                if (disabledPs.childPackageNames != null && disabledPs.childPackageNames
15465                        .contains(childPackageName)) {
15466                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
15467                            childPackageName);
15468                    if (childInfo != null) {
15469                        childInfo.isRemovedPackageSystemUpdate = true;
15470                    }
15471                }
15472            }
15473        }
15474
15475        if (disabledPs.versionCode < deletedPs.versionCode) {
15476            // Delete data for downgrades
15477            flags &= ~PackageManager.DELETE_KEEP_DATA;
15478        } else {
15479            // Preserve data by setting flag
15480            flags |= PackageManager.DELETE_KEEP_DATA;
15481        }
15482
15483        boolean ret = deleteInstalledPackageLIF(deletedPs, true, flags, allUserHandles,
15484                outInfo, writeSettings, disabledPs.pkg);
15485        if (!ret) {
15486            return false;
15487        }
15488
15489        // writer
15490        synchronized (mPackages) {
15491            // Reinstate the old system package
15492            enableSystemPackageLPw(disabledPs.pkg);
15493            // Remove any native libraries from the upgraded package.
15494            removeNativeBinariesLI(deletedPs);
15495        }
15496
15497        // Install the system package
15498        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
15499        int parseFlags = mDefParseFlags
15500                | PackageParser.PARSE_MUST_BE_APK
15501                | PackageParser.PARSE_IS_SYSTEM
15502                | PackageParser.PARSE_IS_SYSTEM_DIR;
15503        if (locationIsPrivileged(disabledPs.codePath)) {
15504            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
15505        }
15506
15507        final PackageParser.Package newPkg;
15508        try {
15509            newPkg = scanPackageTracedLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null);
15510        } catch (PackageManagerException e) {
15511            Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": "
15512                    + e.getMessage());
15513            return false;
15514        }
15515
15516        prepareAppDataAfterInstallLIF(newPkg);
15517
15518        // writer
15519        synchronized (mPackages) {
15520            PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
15521
15522            // Propagate the permissions state as we do not want to drop on the floor
15523            // runtime permissions. The update permissions method below will take
15524            // care of removing obsolete permissions and grant install permissions.
15525            ps.getPermissionsState().copyFrom(deletedPs.getPermissionsState());
15526            updatePermissionsLPw(newPkg.packageName, newPkg,
15527                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
15528
15529            if (applyUserRestrictions) {
15530                if (DEBUG_REMOVE) {
15531                    Slog.d(TAG, "Propagating install state across reinstall");
15532                }
15533                for (int userId : allUserHandles) {
15534                    final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
15535                    if (DEBUG_REMOVE) {
15536                        Slog.d(TAG, "    user " + userId + " => " + installed);
15537                    }
15538                    ps.setInstalled(installed, userId);
15539
15540                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
15541                }
15542                // Regardless of writeSettings we need to ensure that this restriction
15543                // state propagation is persisted
15544                mSettings.writeAllUsersPackageRestrictionsLPr();
15545            }
15546            // can downgrade to reader here
15547            if (writeSettings) {
15548                mSettings.writeLPr();
15549            }
15550        }
15551        return true;
15552    }
15553
15554    private boolean deleteInstalledPackageLIF(PackageSetting ps,
15555            boolean deleteCodeAndResources, int flags, int[] allUserHandles,
15556            PackageRemovedInfo outInfo, boolean writeSettings,
15557            PackageParser.Package replacingPackage) {
15558        synchronized (mPackages) {
15559            if (outInfo != null) {
15560                outInfo.uid = ps.appId;
15561            }
15562
15563            if (outInfo != null && outInfo.removedChildPackages != null) {
15564                final int childCount = (ps.childPackageNames != null)
15565                        ? ps.childPackageNames.size() : 0;
15566                for (int i = 0; i < childCount; i++) {
15567                    String childPackageName = ps.childPackageNames.get(i);
15568                    PackageSetting childPs = mSettings.mPackages.get(childPackageName);
15569                    if (childPs == null) {
15570                        return false;
15571                    }
15572                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
15573                            childPackageName);
15574                    if (childInfo != null) {
15575                        childInfo.uid = childPs.appId;
15576                    }
15577                }
15578            }
15579        }
15580
15581        // Delete package data from internal structures and also remove data if flag is set
15582        removePackageDataLIF(ps, allUserHandles, outInfo, flags, writeSettings);
15583
15584        // Delete the child packages data
15585        final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
15586        for (int i = 0; i < childCount; i++) {
15587            PackageSetting childPs;
15588            synchronized (mPackages) {
15589                childPs = mSettings.peekPackageLPr(ps.childPackageNames.get(i));
15590            }
15591            if (childPs != null) {
15592                PackageRemovedInfo childOutInfo = (outInfo != null
15593                        && outInfo.removedChildPackages != null)
15594                        ? outInfo.removedChildPackages.get(childPs.name) : null;
15595                final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0
15596                        && (replacingPackage != null
15597                        && !replacingPackage.hasChildPackage(childPs.name))
15598                        ? flags & ~DELETE_KEEP_DATA : flags;
15599                removePackageDataLIF(childPs, allUserHandles, childOutInfo,
15600                        deleteFlags, writeSettings);
15601            }
15602        }
15603
15604        // Delete application code and resources only for parent packages
15605        if (ps.parentPackageName == null) {
15606            if (deleteCodeAndResources && (outInfo != null)) {
15607                outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
15608                        ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
15609                if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
15610            }
15611        }
15612
15613        return true;
15614    }
15615
15616    @Override
15617    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
15618            int userId) {
15619        mContext.enforceCallingOrSelfPermission(
15620                android.Manifest.permission.DELETE_PACKAGES, null);
15621        synchronized (mPackages) {
15622            PackageSetting ps = mSettings.mPackages.get(packageName);
15623            if (ps == null) {
15624                Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName);
15625                return false;
15626            }
15627            if (!ps.getInstalled(userId)) {
15628                // Can't block uninstall for an app that is not installed or enabled.
15629                Log.i(TAG, "Package not installed in set block uninstall " + packageName);
15630                return false;
15631            }
15632            ps.setBlockUninstall(blockUninstall, userId);
15633            mSettings.writePackageRestrictionsLPr(userId);
15634        }
15635        return true;
15636    }
15637
15638    @Override
15639    public boolean getBlockUninstallForUser(String packageName, int userId) {
15640        synchronized (mPackages) {
15641            PackageSetting ps = mSettings.mPackages.get(packageName);
15642            if (ps == null) {
15643                Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName);
15644                return false;
15645            }
15646            return ps.getBlockUninstall(userId);
15647        }
15648    }
15649
15650    @Override
15651    public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) {
15652        int callingUid = Binder.getCallingUid();
15653        if (callingUid != Process.SYSTEM_UID && callingUid != Process.ROOT_UID) {
15654            throw new SecurityException(
15655                    "setRequiredForSystemUser can only be run by the system or root");
15656        }
15657        synchronized (mPackages) {
15658            PackageSetting ps = mSettings.mPackages.get(packageName);
15659            if (ps == null) {
15660                Log.w(TAG, "Package doesn't exist: " + packageName);
15661                return false;
15662            }
15663            if (systemUserApp) {
15664                ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
15665            } else {
15666                ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
15667            }
15668            mSettings.writeLPr();
15669        }
15670        return true;
15671    }
15672
15673    /*
15674     * This method handles package deletion in general
15675     */
15676    private boolean deletePackageLIF(String packageName, UserHandle user,
15677            boolean deleteCodeAndResources, int[] allUserHandles, int flags,
15678            PackageRemovedInfo outInfo, boolean writeSettings,
15679            PackageParser.Package replacingPackage) {
15680        if (packageName == null) {
15681            Slog.w(TAG, "Attempt to delete null packageName.");
15682            return false;
15683        }
15684
15685        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
15686
15687        PackageSetting ps;
15688
15689        synchronized (mPackages) {
15690            ps = mSettings.mPackages.get(packageName);
15691            if (ps == null) {
15692                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
15693                return false;
15694            }
15695
15696            if (ps.parentPackageName != null && (!isSystemApp(ps)
15697                    || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) {
15698                if (DEBUG_REMOVE) {
15699                    Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:"
15700                            + ((user == null) ? UserHandle.USER_ALL : user));
15701                }
15702                final int removedUserId = (user != null) ? user.getIdentifier()
15703                        : UserHandle.USER_ALL;
15704                if (!clearPackageStateForUserLIF(ps, removedUserId, outInfo)) {
15705                    return false;
15706                }
15707                markPackageUninstalledForUserLPw(ps, user);
15708                scheduleWritePackageRestrictionsLocked(user);
15709                return true;
15710            }
15711        }
15712
15713        if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
15714                && user.getIdentifier() != UserHandle.USER_ALL)) {
15715            // The caller is asking that the package only be deleted for a single
15716            // user.  To do this, we just mark its uninstalled state and delete
15717            // its data. If this is a system app, we only allow this to happen if
15718            // they have set the special DELETE_SYSTEM_APP which requests different
15719            // semantics than normal for uninstalling system apps.
15720            markPackageUninstalledForUserLPw(ps, user);
15721
15722            if (!isSystemApp(ps)) {
15723                // Do not uninstall the APK if an app should be cached
15724                boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName);
15725                if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) {
15726                    // Other user still have this package installed, so all
15727                    // we need to do is clear this user's data and save that
15728                    // it is uninstalled.
15729                    if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
15730                    if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
15731                        return false;
15732                    }
15733                    scheduleWritePackageRestrictionsLocked(user);
15734                    return true;
15735                } else {
15736                    // We need to set it back to 'installed' so the uninstall
15737                    // broadcasts will be sent correctly.
15738                    if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
15739                    ps.setInstalled(true, user.getIdentifier());
15740                }
15741            } else {
15742                // This is a system app, so we assume that the
15743                // other users still have this package installed, so all
15744                // we need to do is clear this user's data and save that
15745                // it is uninstalled.
15746                if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
15747                if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
15748                    return false;
15749                }
15750                scheduleWritePackageRestrictionsLocked(user);
15751                return true;
15752            }
15753        }
15754
15755        // If we are deleting a composite package for all users, keep track
15756        // of result for each child.
15757        if (ps.childPackageNames != null && outInfo != null) {
15758            synchronized (mPackages) {
15759                final int childCount = ps.childPackageNames.size();
15760                outInfo.removedChildPackages = new ArrayMap<>(childCount);
15761                for (int i = 0; i < childCount; i++) {
15762                    String childPackageName = ps.childPackageNames.get(i);
15763                    PackageRemovedInfo childInfo = new PackageRemovedInfo();
15764                    childInfo.removedPackage = childPackageName;
15765                    outInfo.removedChildPackages.put(childPackageName, childInfo);
15766                    PackageSetting childPs = mSettings.peekPackageLPr(childPackageName);
15767                    if (childPs != null) {
15768                        childInfo.origUsers = childPs.queryInstalledUsers(allUserHandles, true);
15769                    }
15770                }
15771            }
15772        }
15773
15774        boolean ret = false;
15775        if (isSystemApp(ps)) {
15776            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name);
15777            // When an updated system application is deleted we delete the existing resources
15778            // as well and fall back to existing code in system partition
15779            ret = deleteSystemPackageLIF(ps.pkg, ps, allUserHandles, flags, outInfo, writeSettings);
15780        } else {
15781            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name);
15782            ret = deleteInstalledPackageLIF(ps, deleteCodeAndResources, flags, allUserHandles,
15783                    outInfo, writeSettings, replacingPackage);
15784        }
15785
15786        // Take a note whether we deleted the package for all users
15787        if (outInfo != null) {
15788            outInfo.removedForAllUsers = mPackages.get(ps.name) == null;
15789            if (outInfo.removedChildPackages != null) {
15790                synchronized (mPackages) {
15791                    final int childCount = outInfo.removedChildPackages.size();
15792                    for (int i = 0; i < childCount; i++) {
15793                        PackageRemovedInfo childInfo = outInfo.removedChildPackages.valueAt(i);
15794                        if (childInfo != null) {
15795                            childInfo.removedForAllUsers = mPackages.get(
15796                                    childInfo.removedPackage) == null;
15797                        }
15798                    }
15799                }
15800            }
15801            // If we uninstalled an update to a system app there may be some
15802            // child packages that appeared as they are declared in the system
15803            // app but were not declared in the update.
15804            if (isSystemApp(ps)) {
15805                synchronized (mPackages) {
15806                    PackageSetting updatedPs = mSettings.peekPackageLPr(ps.name);
15807                    final int childCount = (updatedPs.childPackageNames != null)
15808                            ? updatedPs.childPackageNames.size() : 0;
15809                    for (int i = 0; i < childCount; i++) {
15810                        String childPackageName = updatedPs.childPackageNames.get(i);
15811                        if (outInfo.removedChildPackages == null
15812                                || outInfo.removedChildPackages.indexOfKey(childPackageName) < 0) {
15813                            PackageSetting childPs = mSettings.peekPackageLPr(childPackageName);
15814                            if (childPs == null) {
15815                                continue;
15816                            }
15817                            PackageInstalledInfo installRes = new PackageInstalledInfo();
15818                            installRes.name = childPackageName;
15819                            installRes.newUsers = childPs.queryInstalledUsers(allUserHandles, true);
15820                            installRes.pkg = mPackages.get(childPackageName);
15821                            installRes.uid = childPs.pkg.applicationInfo.uid;
15822                            if (outInfo.appearedChildPackages == null) {
15823                                outInfo.appearedChildPackages = new ArrayMap<>();
15824                            }
15825                            outInfo.appearedChildPackages.put(childPackageName, installRes);
15826                        }
15827                    }
15828                }
15829            }
15830        }
15831
15832        return ret;
15833    }
15834
15835    private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) {
15836        final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL)
15837                ? sUserManager.getUserIds() : new int[] {user.getIdentifier()};
15838        for (int nextUserId : userIds) {
15839            if (DEBUG_REMOVE) {
15840                Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId);
15841            }
15842            ps.setUserState(nextUserId, 0, COMPONENT_ENABLED_STATE_DEFAULT,
15843                    false /*installed*/, true /*stopped*/, true /*notLaunched*/,
15844                    false /*hidden*/, false /*suspended*/, null, null, null,
15845                    false /*blockUninstall*/,
15846                    ps.readUserState(nextUserId).domainVerificationStatus, 0);
15847        }
15848    }
15849
15850    private boolean clearPackageStateForUserLIF(PackageSetting ps, int userId,
15851            PackageRemovedInfo outInfo) {
15852        final PackageParser.Package pkg;
15853        synchronized (mPackages) {
15854            pkg = mPackages.get(ps.name);
15855        }
15856
15857        final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds()
15858                : new int[] {userId};
15859        for (int nextUserId : userIds) {
15860            if (DEBUG_REMOVE) {
15861                Slog.d(TAG, "Updating package:" + ps.name + " install state for user:"
15862                        + nextUserId);
15863            }
15864
15865            destroyAppDataLIF(pkg, userId,
15866                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
15867            removeKeystoreDataIfNeeded(nextUserId, ps.appId);
15868            schedulePackageCleaning(ps.name, nextUserId, false);
15869            synchronized (mPackages) {
15870                if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) {
15871                    scheduleWritePackageRestrictionsLocked(nextUserId);
15872                }
15873                resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId);
15874            }
15875        }
15876
15877        if (outInfo != null) {
15878            outInfo.removedPackage = ps.name;
15879            outInfo.removedAppId = ps.appId;
15880            outInfo.removedUsers = userIds;
15881        }
15882
15883        return true;
15884    }
15885
15886    private final class ClearStorageConnection implements ServiceConnection {
15887        IMediaContainerService mContainerService;
15888
15889        @Override
15890        public void onServiceConnected(ComponentName name, IBinder service) {
15891            synchronized (this) {
15892                mContainerService = IMediaContainerService.Stub.asInterface(service);
15893                notifyAll();
15894            }
15895        }
15896
15897        @Override
15898        public void onServiceDisconnected(ComponentName name) {
15899        }
15900    }
15901
15902    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
15903        if (DEFAULT_CONTAINER_PACKAGE.equals(packageName)) return;
15904
15905        final boolean mounted;
15906        if (Environment.isExternalStorageEmulated()) {
15907            mounted = true;
15908        } else {
15909            final String status = Environment.getExternalStorageState();
15910
15911            mounted = status.equals(Environment.MEDIA_MOUNTED)
15912                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
15913        }
15914
15915        if (!mounted) {
15916            return;
15917        }
15918
15919        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
15920        int[] users;
15921        if (userId == UserHandle.USER_ALL) {
15922            users = sUserManager.getUserIds();
15923        } else {
15924            users = new int[] { userId };
15925        }
15926        final ClearStorageConnection conn = new ClearStorageConnection();
15927        if (mContext.bindServiceAsUser(
15928                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
15929            try {
15930                for (int curUser : users) {
15931                    long timeout = SystemClock.uptimeMillis() + 5000;
15932                    synchronized (conn) {
15933                        long now = SystemClock.uptimeMillis();
15934                        while (conn.mContainerService == null && now < timeout) {
15935                            try {
15936                                conn.wait(timeout - now);
15937                            } catch (InterruptedException e) {
15938                            }
15939                        }
15940                    }
15941                    if (conn.mContainerService == null) {
15942                        return;
15943                    }
15944
15945                    final UserEnvironment userEnv = new UserEnvironment(curUser);
15946                    clearDirectory(conn.mContainerService,
15947                            userEnv.buildExternalStorageAppCacheDirs(packageName));
15948                    if (allData) {
15949                        clearDirectory(conn.mContainerService,
15950                                userEnv.buildExternalStorageAppDataDirs(packageName));
15951                        clearDirectory(conn.mContainerService,
15952                                userEnv.buildExternalStorageAppMediaDirs(packageName));
15953                    }
15954                }
15955            } finally {
15956                mContext.unbindService(conn);
15957            }
15958        }
15959    }
15960
15961    @Override
15962    public void clearApplicationProfileData(String packageName) {
15963        enforceSystemOrRoot("Only the system can clear all profile data");
15964
15965        final PackageParser.Package pkg;
15966        synchronized (mPackages) {
15967            pkg = mPackages.get(packageName);
15968        }
15969
15970        try (PackageFreezer freezer = freezePackage(packageName, "clearApplicationProfileData")) {
15971            synchronized (mInstallLock) {
15972                clearAppProfilesLIF(pkg);
15973            }
15974        }
15975    }
15976
15977    @Override
15978    public void clearApplicationUserData(final String packageName,
15979            final IPackageDataObserver observer, final int userId) {
15980        mContext.enforceCallingOrSelfPermission(
15981                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
15982
15983        enforceCrossUserPermission(Binder.getCallingUid(), userId,
15984                true /* requireFullPermission */, false /* checkShell */, "clear application data");
15985
15986        final DevicePolicyManagerInternal dpmi = LocalServices
15987                .getService(DevicePolicyManagerInternal.class);
15988        if (dpmi != null && dpmi.hasDeviceOwnerOrProfileOwner(packageName, userId)) {
15989            throw new SecurityException("Cannot clear data for a device owner or a profile owner");
15990        }
15991        // Queue up an async operation since the package deletion may take a little while.
15992        mHandler.post(new Runnable() {
15993            public void run() {
15994                mHandler.removeCallbacks(this);
15995                final boolean succeeded;
15996                try (PackageFreezer freezer = freezePackage(packageName,
15997                        "clearApplicationUserData")) {
15998                    synchronized (mInstallLock) {
15999                        succeeded = clearApplicationUserDataLIF(packageName, userId);
16000                    }
16001                    clearExternalStorageDataSync(packageName, userId, true);
16002                }
16003                if (succeeded) {
16004                    // invoke DeviceStorageMonitor's update method to clear any notifications
16005                    DeviceStorageMonitorInternal dsm = LocalServices
16006                            .getService(DeviceStorageMonitorInternal.class);
16007                    if (dsm != null) {
16008                        dsm.checkMemory();
16009                    }
16010                }
16011                if(observer != null) {
16012                    try {
16013                        observer.onRemoveCompleted(packageName, succeeded);
16014                    } catch (RemoteException e) {
16015                        Log.i(TAG, "Observer no longer exists.");
16016                    }
16017                } //end if observer
16018            } //end run
16019        });
16020    }
16021
16022    private boolean clearApplicationUserDataLIF(String packageName, int userId) {
16023        if (packageName == null) {
16024            Slog.w(TAG, "Attempt to delete null packageName.");
16025            return false;
16026        }
16027
16028        // Try finding details about the requested package
16029        PackageParser.Package pkg;
16030        synchronized (mPackages) {
16031            pkg = mPackages.get(packageName);
16032            if (pkg == null) {
16033                final PackageSetting ps = mSettings.mPackages.get(packageName);
16034                if (ps != null) {
16035                    pkg = ps.pkg;
16036                }
16037            }
16038
16039            if (pkg == null) {
16040                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
16041                return false;
16042            }
16043
16044            PackageSetting ps = (PackageSetting) pkg.mExtras;
16045            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
16046        }
16047
16048        clearAppDataLIF(pkg, userId,
16049                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
16050
16051        final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
16052        removeKeystoreDataIfNeeded(userId, appId);
16053
16054        final UserManager um = mContext.getSystemService(UserManager.class);
16055        final int flags;
16056        if (um.isUserUnlocked(userId)) {
16057            flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
16058        } else if (um.isUserRunning(userId)) {
16059            flags = StorageManager.FLAG_STORAGE_DE;
16060        } else {
16061            flags = 0;
16062        }
16063        prepareAppDataContentsLIF(pkg, userId, flags);
16064
16065        return true;
16066    }
16067
16068    /**
16069     * Reverts user permission state changes (permissions and flags) in
16070     * all packages for a given user.
16071     *
16072     * @param userId The device user for which to do a reset.
16073     */
16074    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) {
16075        final int packageCount = mPackages.size();
16076        for (int i = 0; i < packageCount; i++) {
16077            PackageParser.Package pkg = mPackages.valueAt(i);
16078            PackageSetting ps = (PackageSetting) pkg.mExtras;
16079            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
16080        }
16081    }
16082
16083    /**
16084     * Reverts user permission state changes (permissions and flags).
16085     *
16086     * @param ps The package for which to reset.
16087     * @param userId The device user for which to do a reset.
16088     */
16089    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(
16090            final PackageSetting ps, final int userId) {
16091        if (ps.pkg == null) {
16092            return;
16093        }
16094
16095        // These are flags that can change base on user actions.
16096        final int userSettableMask = FLAG_PERMISSION_USER_SET
16097                | FLAG_PERMISSION_USER_FIXED
16098                | FLAG_PERMISSION_REVOKE_ON_UPGRADE
16099                | FLAG_PERMISSION_REVIEW_REQUIRED;
16100
16101        final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED
16102                | FLAG_PERMISSION_POLICY_FIXED;
16103
16104        boolean writeInstallPermissions = false;
16105        boolean writeRuntimePermissions = false;
16106
16107        final int permissionCount = ps.pkg.requestedPermissions.size();
16108        for (int i = 0; i < permissionCount; i++) {
16109            String permission = ps.pkg.requestedPermissions.get(i);
16110
16111            BasePermission bp = mSettings.mPermissions.get(permission);
16112            if (bp == null) {
16113                continue;
16114            }
16115
16116            // If shared user we just reset the state to which only this app contributed.
16117            if (ps.sharedUser != null) {
16118                boolean used = false;
16119                final int packageCount = ps.sharedUser.packages.size();
16120                for (int j = 0; j < packageCount; j++) {
16121                    PackageSetting pkg = ps.sharedUser.packages.valueAt(j);
16122                    if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName)
16123                            && pkg.pkg.requestedPermissions.contains(permission)) {
16124                        used = true;
16125                        break;
16126                    }
16127                }
16128                if (used) {
16129                    continue;
16130                }
16131            }
16132
16133            PermissionsState permissionsState = ps.getPermissionsState();
16134
16135            final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId);
16136
16137            // Always clear the user settable flags.
16138            final boolean hasInstallState = permissionsState.getInstallPermissionState(
16139                    bp.name) != null;
16140            // If permission review is enabled and this is a legacy app, mark the
16141            // permission as requiring a review as this is the initial state.
16142            int flags = 0;
16143            if (Build.PERMISSIONS_REVIEW_REQUIRED
16144                    && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
16145                flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
16146            }
16147            if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) {
16148                if (hasInstallState) {
16149                    writeInstallPermissions = true;
16150                } else {
16151                    writeRuntimePermissions = true;
16152                }
16153            }
16154
16155            // Below is only runtime permission handling.
16156            if (!bp.isRuntime()) {
16157                continue;
16158            }
16159
16160            // Never clobber system or policy.
16161            if ((oldFlags & policyOrSystemFlags) != 0) {
16162                continue;
16163            }
16164
16165            // If this permission was granted by default, make sure it is.
16166            if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) {
16167                if (permissionsState.grantRuntimePermission(bp, userId)
16168                        != PERMISSION_OPERATION_FAILURE) {
16169                    writeRuntimePermissions = true;
16170                }
16171            // If permission review is enabled the permissions for a legacy apps
16172            // are represented as constantly granted runtime ones, so don't revoke.
16173            } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
16174                // Otherwise, reset the permission.
16175                final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId);
16176                switch (revokeResult) {
16177                    case PERMISSION_OPERATION_SUCCESS:
16178                    case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
16179                        writeRuntimePermissions = true;
16180                        final int appId = ps.appId;
16181                        mHandler.post(new Runnable() {
16182                            @Override
16183                            public void run() {
16184                                killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
16185                            }
16186                        });
16187                    } break;
16188                }
16189            }
16190        }
16191
16192        // Synchronously write as we are taking permissions away.
16193        if (writeRuntimePermissions) {
16194            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
16195        }
16196
16197        // Synchronously write as we are taking permissions away.
16198        if (writeInstallPermissions) {
16199            mSettings.writeLPr();
16200        }
16201    }
16202
16203    /**
16204     * Remove entries from the keystore daemon. Will only remove it if the
16205     * {@code appId} is valid.
16206     */
16207    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
16208        if (appId < 0) {
16209            return;
16210        }
16211
16212        final KeyStore keyStore = KeyStore.getInstance();
16213        if (keyStore != null) {
16214            if (userId == UserHandle.USER_ALL) {
16215                for (final int individual : sUserManager.getUserIds()) {
16216                    keyStore.clearUid(UserHandle.getUid(individual, appId));
16217                }
16218            } else {
16219                keyStore.clearUid(UserHandle.getUid(userId, appId));
16220            }
16221        } else {
16222            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
16223        }
16224    }
16225
16226    @Override
16227    public void deleteApplicationCacheFiles(final String packageName,
16228            final IPackageDataObserver observer) {
16229        final int userId = UserHandle.getCallingUserId();
16230        deleteApplicationCacheFilesAsUser(packageName, userId, observer);
16231    }
16232
16233    @Override
16234    public void deleteApplicationCacheFilesAsUser(final String packageName, final int userId,
16235            final IPackageDataObserver observer) {
16236        mContext.enforceCallingOrSelfPermission(
16237                android.Manifest.permission.DELETE_CACHE_FILES, null);
16238        enforceCrossUserPermission(Binder.getCallingUid(), userId,
16239                /* requireFullPermission= */ true, /* checkShell= */ false,
16240                "delete application cache files");
16241
16242        final PackageParser.Package pkg;
16243        synchronized (mPackages) {
16244            pkg = mPackages.get(packageName);
16245        }
16246
16247        // Queue up an async operation since the package deletion may take a little while.
16248        mHandler.post(new Runnable() {
16249            public void run() {
16250                synchronized (mInstallLock) {
16251                    final int flags = StorageManager.FLAG_STORAGE_DE
16252                            | StorageManager.FLAG_STORAGE_CE;
16253                    // We're only clearing cache files, so we don't care if the
16254                    // app is unfrozen and still able to run
16255                    clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CACHE_ONLY);
16256                    clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
16257                }
16258                clearExternalStorageDataSync(packageName, userId, false);
16259                if (observer != null) {
16260                    try {
16261                        observer.onRemoveCompleted(packageName, true);
16262                    } catch (RemoteException e) {
16263                        Log.i(TAG, "Observer no longer exists.");
16264                    }
16265                }
16266            }
16267        });
16268    }
16269
16270    @Override
16271    public void getPackageSizeInfo(final String packageName, int userHandle,
16272            final IPackageStatsObserver observer) {
16273        mContext.enforceCallingOrSelfPermission(
16274                android.Manifest.permission.GET_PACKAGE_SIZE, null);
16275        if (packageName == null) {
16276            throw new IllegalArgumentException("Attempt to get size of null packageName");
16277        }
16278
16279        PackageStats stats = new PackageStats(packageName, userHandle);
16280
16281        /*
16282         * Queue up an async operation since the package measurement may take a
16283         * little while.
16284         */
16285        Message msg = mHandler.obtainMessage(INIT_COPY);
16286        msg.obj = new MeasureParams(stats, observer);
16287        mHandler.sendMessage(msg);
16288    }
16289
16290    private boolean getPackageSizeInfoLI(String packageName, int userId, PackageStats stats) {
16291        final PackageSetting ps;
16292        synchronized (mPackages) {
16293            ps = mSettings.mPackages.get(packageName);
16294            if (ps == null) {
16295                Slog.w(TAG, "Failed to find settings for " + packageName);
16296                return false;
16297            }
16298        }
16299        try {
16300            mInstaller.getAppSize(ps.volumeUuid, packageName, userId,
16301                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE,
16302                    ps.getCeDataInode(userId), ps.codePathString, stats);
16303        } catch (InstallerException e) {
16304            Slog.w(TAG, String.valueOf(e));
16305            return false;
16306        }
16307
16308        // For now, ignore code size of packages on system partition
16309        if (isSystemApp(ps) && !isUpdatedSystemApp(ps)) {
16310            stats.codeSize = 0;
16311        }
16312
16313        return true;
16314    }
16315
16316    private int getUidTargetSdkVersionLockedLPr(int uid) {
16317        Object obj = mSettings.getUserIdLPr(uid);
16318        if (obj instanceof SharedUserSetting) {
16319            final SharedUserSetting sus = (SharedUserSetting) obj;
16320            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
16321            final Iterator<PackageSetting> it = sus.packages.iterator();
16322            while (it.hasNext()) {
16323                final PackageSetting ps = it.next();
16324                if (ps.pkg != null) {
16325                    int v = ps.pkg.applicationInfo.targetSdkVersion;
16326                    if (v < vers) vers = v;
16327                }
16328            }
16329            return vers;
16330        } else if (obj instanceof PackageSetting) {
16331            final PackageSetting ps = (PackageSetting) obj;
16332            if (ps.pkg != null) {
16333                return ps.pkg.applicationInfo.targetSdkVersion;
16334            }
16335        }
16336        return Build.VERSION_CODES.CUR_DEVELOPMENT;
16337    }
16338
16339    @Override
16340    public void addPreferredActivity(IntentFilter filter, int match,
16341            ComponentName[] set, ComponentName activity, int userId) {
16342        addPreferredActivityInternal(filter, match, set, activity, true, userId,
16343                "Adding preferred");
16344    }
16345
16346    private void addPreferredActivityInternal(IntentFilter filter, int match,
16347            ComponentName[] set, ComponentName activity, boolean always, int userId,
16348            String opname) {
16349        // writer
16350        int callingUid = Binder.getCallingUid();
16351        enforceCrossUserPermission(callingUid, userId,
16352                true /* requireFullPermission */, false /* checkShell */, "add preferred activity");
16353        if (filter.countActions() == 0) {
16354            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
16355            return;
16356        }
16357        synchronized (mPackages) {
16358            if (mContext.checkCallingOrSelfPermission(
16359                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
16360                    != PackageManager.PERMISSION_GRANTED) {
16361                if (getUidTargetSdkVersionLockedLPr(callingUid)
16362                        < Build.VERSION_CODES.FROYO) {
16363                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
16364                            + callingUid);
16365                    return;
16366                }
16367                mContext.enforceCallingOrSelfPermission(
16368                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
16369            }
16370
16371            PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
16372            Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
16373                    + userId + ":");
16374            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
16375            pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
16376            scheduleWritePackageRestrictionsLocked(userId);
16377        }
16378    }
16379
16380    @Override
16381    public void replacePreferredActivity(IntentFilter filter, int match,
16382            ComponentName[] set, ComponentName activity, int userId) {
16383        if (filter.countActions() != 1) {
16384            throw new IllegalArgumentException(
16385                    "replacePreferredActivity expects filter to have only 1 action.");
16386        }
16387        if (filter.countDataAuthorities() != 0
16388                || filter.countDataPaths() != 0
16389                || filter.countDataSchemes() > 1
16390                || filter.countDataTypes() != 0) {
16391            throw new IllegalArgumentException(
16392                    "replacePreferredActivity expects filter to have no data authorities, " +
16393                    "paths, or types; and at most one scheme.");
16394        }
16395
16396        final int callingUid = Binder.getCallingUid();
16397        enforceCrossUserPermission(callingUid, userId,
16398                true /* requireFullPermission */, false /* checkShell */,
16399                "replace preferred activity");
16400        synchronized (mPackages) {
16401            if (mContext.checkCallingOrSelfPermission(
16402                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
16403                    != PackageManager.PERMISSION_GRANTED) {
16404                if (getUidTargetSdkVersionLockedLPr(callingUid)
16405                        < Build.VERSION_CODES.FROYO) {
16406                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
16407                            + Binder.getCallingUid());
16408                    return;
16409                }
16410                mContext.enforceCallingOrSelfPermission(
16411                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
16412            }
16413
16414            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
16415            if (pir != null) {
16416                // Get all of the existing entries that exactly match this filter.
16417                ArrayList<PreferredActivity> existing = pir.findFilters(filter);
16418                if (existing != null && existing.size() == 1) {
16419                    PreferredActivity cur = existing.get(0);
16420                    if (DEBUG_PREFERRED) {
16421                        Slog.i(TAG, "Checking replace of preferred:");
16422                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
16423                        if (!cur.mPref.mAlways) {
16424                            Slog.i(TAG, "  -- CUR; not mAlways!");
16425                        } else {
16426                            Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
16427                            Slog.i(TAG, "  -- CUR: mSet="
16428                                    + Arrays.toString(cur.mPref.mSetComponents));
16429                            Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
16430                            Slog.i(TAG, "  -- NEW: mMatch="
16431                                    + (match&IntentFilter.MATCH_CATEGORY_MASK));
16432                            Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
16433                            Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
16434                        }
16435                    }
16436                    if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
16437                            && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
16438                            && cur.mPref.sameSet(set)) {
16439                        // Setting the preferred activity to what it happens to be already
16440                        if (DEBUG_PREFERRED) {
16441                            Slog.i(TAG, "Replacing with same preferred activity "
16442                                    + cur.mPref.mShortComponent + " for user "
16443                                    + userId + ":");
16444                            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
16445                        }
16446                        return;
16447                    }
16448                }
16449
16450                if (existing != null) {
16451                    if (DEBUG_PREFERRED) {
16452                        Slog.i(TAG, existing.size() + " existing preferred matches for:");
16453                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
16454                    }
16455                    for (int i = 0; i < existing.size(); i++) {
16456                        PreferredActivity pa = existing.get(i);
16457                        if (DEBUG_PREFERRED) {
16458                            Slog.i(TAG, "Removing existing preferred activity "
16459                                    + pa.mPref.mComponent + ":");
16460                            pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
16461                        }
16462                        pir.removeFilter(pa);
16463                    }
16464                }
16465            }
16466            addPreferredActivityInternal(filter, match, set, activity, true, userId,
16467                    "Replacing preferred");
16468        }
16469    }
16470
16471    @Override
16472    public void clearPackagePreferredActivities(String packageName) {
16473        final int uid = Binder.getCallingUid();
16474        // writer
16475        synchronized (mPackages) {
16476            PackageParser.Package pkg = mPackages.get(packageName);
16477            if (pkg == null || pkg.applicationInfo.uid != uid) {
16478                if (mContext.checkCallingOrSelfPermission(
16479                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
16480                        != PackageManager.PERMISSION_GRANTED) {
16481                    if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid())
16482                            < Build.VERSION_CODES.FROYO) {
16483                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
16484                                + Binder.getCallingUid());
16485                        return;
16486                    }
16487                    mContext.enforceCallingOrSelfPermission(
16488                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
16489                }
16490            }
16491
16492            int user = UserHandle.getCallingUserId();
16493            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
16494                scheduleWritePackageRestrictionsLocked(user);
16495            }
16496        }
16497    }
16498
16499    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
16500    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
16501        ArrayList<PreferredActivity> removed = null;
16502        boolean changed = false;
16503        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
16504            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
16505            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
16506            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
16507                continue;
16508            }
16509            Iterator<PreferredActivity> it = pir.filterIterator();
16510            while (it.hasNext()) {
16511                PreferredActivity pa = it.next();
16512                // Mark entry for removal only if it matches the package name
16513                // and the entry is of type "always".
16514                if (packageName == null ||
16515                        (pa.mPref.mComponent.getPackageName().equals(packageName)
16516                                && pa.mPref.mAlways)) {
16517                    if (removed == null) {
16518                        removed = new ArrayList<PreferredActivity>();
16519                    }
16520                    removed.add(pa);
16521                }
16522            }
16523            if (removed != null) {
16524                for (int j=0; j<removed.size(); j++) {
16525                    PreferredActivity pa = removed.get(j);
16526                    pir.removeFilter(pa);
16527                }
16528                changed = true;
16529            }
16530        }
16531        return changed;
16532    }
16533
16534    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
16535    private void clearIntentFilterVerificationsLPw(int userId) {
16536        final int packageCount = mPackages.size();
16537        for (int i = 0; i < packageCount; i++) {
16538            PackageParser.Package pkg = mPackages.valueAt(i);
16539            clearIntentFilterVerificationsLPw(pkg.packageName, userId);
16540        }
16541    }
16542
16543    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
16544    void clearIntentFilterVerificationsLPw(String packageName, int userId) {
16545        if (userId == UserHandle.USER_ALL) {
16546            if (mSettings.removeIntentFilterVerificationLPw(packageName,
16547                    sUserManager.getUserIds())) {
16548                for (int oneUserId : sUserManager.getUserIds()) {
16549                    scheduleWritePackageRestrictionsLocked(oneUserId);
16550                }
16551            }
16552        } else {
16553            if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) {
16554                scheduleWritePackageRestrictionsLocked(userId);
16555            }
16556        }
16557    }
16558
16559    void clearDefaultBrowserIfNeeded(String packageName) {
16560        for (int oneUserId : sUserManager.getUserIds()) {
16561            String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId);
16562            if (TextUtils.isEmpty(defaultBrowserPackageName)) continue;
16563            if (packageName.equals(defaultBrowserPackageName)) {
16564                setDefaultBrowserPackageName(null, oneUserId);
16565            }
16566        }
16567    }
16568
16569    @Override
16570    public void resetApplicationPreferences(int userId) {
16571        mContext.enforceCallingOrSelfPermission(
16572                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
16573        // writer
16574        synchronized (mPackages) {
16575            final long identity = Binder.clearCallingIdentity();
16576            try {
16577                clearPackagePreferredActivitiesLPw(null, userId);
16578                mSettings.applyDefaultPreferredAppsLPw(this, userId);
16579                // TODO: We have to reset the default SMS and Phone. This requires
16580                // significant refactoring to keep all default apps in the package
16581                // manager (cleaner but more work) or have the services provide
16582                // callbacks to the package manager to request a default app reset.
16583                applyFactoryDefaultBrowserLPw(userId);
16584                clearIntentFilterVerificationsLPw(userId);
16585                primeDomainVerificationsLPw(userId);
16586                resetUserChangesToRuntimePermissionsAndFlagsLPw(userId);
16587                scheduleWritePackageRestrictionsLocked(userId);
16588            } finally {
16589                Binder.restoreCallingIdentity(identity);
16590            }
16591        }
16592    }
16593
16594    @Override
16595    public int getPreferredActivities(List<IntentFilter> outFilters,
16596            List<ComponentName> outActivities, String packageName) {
16597
16598        int num = 0;
16599        final int userId = UserHandle.getCallingUserId();
16600        // reader
16601        synchronized (mPackages) {
16602            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
16603            if (pir != null) {
16604                final Iterator<PreferredActivity> it = pir.filterIterator();
16605                while (it.hasNext()) {
16606                    final PreferredActivity pa = it.next();
16607                    if (packageName == null
16608                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
16609                                    && pa.mPref.mAlways)) {
16610                        if (outFilters != null) {
16611                            outFilters.add(new IntentFilter(pa));
16612                        }
16613                        if (outActivities != null) {
16614                            outActivities.add(pa.mPref.mComponent);
16615                        }
16616                    }
16617                }
16618            }
16619        }
16620
16621        return num;
16622    }
16623
16624    @Override
16625    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
16626            int userId) {
16627        int callingUid = Binder.getCallingUid();
16628        if (callingUid != Process.SYSTEM_UID) {
16629            throw new SecurityException(
16630                    "addPersistentPreferredActivity can only be run by the system");
16631        }
16632        if (filter.countActions() == 0) {
16633            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
16634            return;
16635        }
16636        synchronized (mPackages) {
16637            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
16638                    ":");
16639            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
16640            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
16641                    new PersistentPreferredActivity(filter, activity));
16642            scheduleWritePackageRestrictionsLocked(userId);
16643        }
16644    }
16645
16646    @Override
16647    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
16648        int callingUid = Binder.getCallingUid();
16649        if (callingUid != Process.SYSTEM_UID) {
16650            throw new SecurityException(
16651                    "clearPackagePersistentPreferredActivities can only be run by the system");
16652        }
16653        ArrayList<PersistentPreferredActivity> removed = null;
16654        boolean changed = false;
16655        synchronized (mPackages) {
16656            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
16657                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
16658                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
16659                        .valueAt(i);
16660                if (userId != thisUserId) {
16661                    continue;
16662                }
16663                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
16664                while (it.hasNext()) {
16665                    PersistentPreferredActivity ppa = it.next();
16666                    // Mark entry for removal only if it matches the package name.
16667                    if (ppa.mComponent.getPackageName().equals(packageName)) {
16668                        if (removed == null) {
16669                            removed = new ArrayList<PersistentPreferredActivity>();
16670                        }
16671                        removed.add(ppa);
16672                    }
16673                }
16674                if (removed != null) {
16675                    for (int j=0; j<removed.size(); j++) {
16676                        PersistentPreferredActivity ppa = removed.get(j);
16677                        ppir.removeFilter(ppa);
16678                    }
16679                    changed = true;
16680                }
16681            }
16682
16683            if (changed) {
16684                scheduleWritePackageRestrictionsLocked(userId);
16685            }
16686        }
16687    }
16688
16689    /**
16690     * Common machinery for picking apart a restored XML blob and passing
16691     * it to a caller-supplied functor to be applied to the running system.
16692     */
16693    private void restoreFromXml(XmlPullParser parser, int userId,
16694            String expectedStartTag, BlobXmlRestorer functor)
16695            throws IOException, XmlPullParserException {
16696        int type;
16697        while ((type = parser.next()) != XmlPullParser.START_TAG
16698                && type != XmlPullParser.END_DOCUMENT) {
16699        }
16700        if (type != XmlPullParser.START_TAG) {
16701            // oops didn't find a start tag?!
16702            if (DEBUG_BACKUP) {
16703                Slog.e(TAG, "Didn't find start tag during restore");
16704            }
16705            return;
16706        }
16707Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName());
16708        // this is supposed to be TAG_PREFERRED_BACKUP
16709        if (!expectedStartTag.equals(parser.getName())) {
16710            if (DEBUG_BACKUP) {
16711                Slog.e(TAG, "Found unexpected tag " + parser.getName());
16712            }
16713            return;
16714        }
16715
16716        // skip interfering stuff, then we're aligned with the backing implementation
16717        while ((type = parser.next()) == XmlPullParser.TEXT) { }
16718Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName());
16719        functor.apply(parser, userId);
16720    }
16721
16722    private interface BlobXmlRestorer {
16723        public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException;
16724    }
16725
16726    /**
16727     * Non-Binder method, support for the backup/restore mechanism: write the
16728     * full set of preferred activities in its canonical XML format.  Returns the
16729     * XML output as a byte array, or null if there is none.
16730     */
16731    @Override
16732    public byte[] getPreferredActivityBackup(int userId) {
16733        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
16734            throw new SecurityException("Only the system may call getPreferredActivityBackup()");
16735        }
16736
16737        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
16738        try {
16739            final XmlSerializer serializer = new FastXmlSerializer();
16740            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
16741            serializer.startDocument(null, true);
16742            serializer.startTag(null, TAG_PREFERRED_BACKUP);
16743
16744            synchronized (mPackages) {
16745                mSettings.writePreferredActivitiesLPr(serializer, userId, true);
16746            }
16747
16748            serializer.endTag(null, TAG_PREFERRED_BACKUP);
16749            serializer.endDocument();
16750            serializer.flush();
16751        } catch (Exception e) {
16752            if (DEBUG_BACKUP) {
16753                Slog.e(TAG, "Unable to write preferred activities for backup", e);
16754            }
16755            return null;
16756        }
16757
16758        return dataStream.toByteArray();
16759    }
16760
16761    @Override
16762    public void restorePreferredActivities(byte[] backup, int userId) {
16763        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
16764            throw new SecurityException("Only the system may call restorePreferredActivities()");
16765        }
16766
16767        try {
16768            final XmlPullParser parser = Xml.newPullParser();
16769            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
16770            restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP,
16771                    new BlobXmlRestorer() {
16772                        @Override
16773                        public void apply(XmlPullParser parser, int userId)
16774                                throws XmlPullParserException, IOException {
16775                            synchronized (mPackages) {
16776                                mSettings.readPreferredActivitiesLPw(parser, userId);
16777                            }
16778                        }
16779                    } );
16780        } catch (Exception e) {
16781            if (DEBUG_BACKUP) {
16782                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
16783            }
16784        }
16785    }
16786
16787    /**
16788     * Non-Binder method, support for the backup/restore mechanism: write the
16789     * default browser (etc) settings in its canonical XML format.  Returns the default
16790     * browser XML representation as a byte array, or null if there is none.
16791     */
16792    @Override
16793    public byte[] getDefaultAppsBackup(int userId) {
16794        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
16795            throw new SecurityException("Only the system may call getDefaultAppsBackup()");
16796        }
16797
16798        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
16799        try {
16800            final XmlSerializer serializer = new FastXmlSerializer();
16801            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
16802            serializer.startDocument(null, true);
16803            serializer.startTag(null, TAG_DEFAULT_APPS);
16804
16805            synchronized (mPackages) {
16806                mSettings.writeDefaultAppsLPr(serializer, userId);
16807            }
16808
16809            serializer.endTag(null, TAG_DEFAULT_APPS);
16810            serializer.endDocument();
16811            serializer.flush();
16812        } catch (Exception e) {
16813            if (DEBUG_BACKUP) {
16814                Slog.e(TAG, "Unable to write default apps for backup", e);
16815            }
16816            return null;
16817        }
16818
16819        return dataStream.toByteArray();
16820    }
16821
16822    @Override
16823    public void restoreDefaultApps(byte[] backup, int userId) {
16824        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
16825            throw new SecurityException("Only the system may call restoreDefaultApps()");
16826        }
16827
16828        try {
16829            final XmlPullParser parser = Xml.newPullParser();
16830            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
16831            restoreFromXml(parser, userId, TAG_DEFAULT_APPS,
16832                    new BlobXmlRestorer() {
16833                        @Override
16834                        public void apply(XmlPullParser parser, int userId)
16835                                throws XmlPullParserException, IOException {
16836                            synchronized (mPackages) {
16837                                mSettings.readDefaultAppsLPw(parser, userId);
16838                            }
16839                        }
16840                    } );
16841        } catch (Exception e) {
16842            if (DEBUG_BACKUP) {
16843                Slog.e(TAG, "Exception restoring default apps: " + e.getMessage());
16844            }
16845        }
16846    }
16847
16848    @Override
16849    public byte[] getIntentFilterVerificationBackup(int userId) {
16850        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
16851            throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()");
16852        }
16853
16854        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
16855        try {
16856            final XmlSerializer serializer = new FastXmlSerializer();
16857            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
16858            serializer.startDocument(null, true);
16859            serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION);
16860
16861            synchronized (mPackages) {
16862                mSettings.writeAllDomainVerificationsLPr(serializer, userId);
16863            }
16864
16865            serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION);
16866            serializer.endDocument();
16867            serializer.flush();
16868        } catch (Exception e) {
16869            if (DEBUG_BACKUP) {
16870                Slog.e(TAG, "Unable to write default apps for backup", e);
16871            }
16872            return null;
16873        }
16874
16875        return dataStream.toByteArray();
16876    }
16877
16878    @Override
16879    public void restoreIntentFilterVerification(byte[] backup, int userId) {
16880        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
16881            throw new SecurityException("Only the system may call restorePreferredActivities()");
16882        }
16883
16884        try {
16885            final XmlPullParser parser = Xml.newPullParser();
16886            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
16887            restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION,
16888                    new BlobXmlRestorer() {
16889                        @Override
16890                        public void apply(XmlPullParser parser, int userId)
16891                                throws XmlPullParserException, IOException {
16892                            synchronized (mPackages) {
16893                                mSettings.readAllDomainVerificationsLPr(parser, userId);
16894                                mSettings.writeLPr();
16895                            }
16896                        }
16897                    } );
16898        } catch (Exception e) {
16899            if (DEBUG_BACKUP) {
16900                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
16901            }
16902        }
16903    }
16904
16905    @Override
16906    public byte[] getPermissionGrantBackup(int userId) {
16907        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
16908            throw new SecurityException("Only the system may call getPermissionGrantBackup()");
16909        }
16910
16911        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
16912        try {
16913            final XmlSerializer serializer = new FastXmlSerializer();
16914            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
16915            serializer.startDocument(null, true);
16916            serializer.startTag(null, TAG_PERMISSION_BACKUP);
16917
16918            synchronized (mPackages) {
16919                serializeRuntimePermissionGrantsLPr(serializer, userId);
16920            }
16921
16922            serializer.endTag(null, TAG_PERMISSION_BACKUP);
16923            serializer.endDocument();
16924            serializer.flush();
16925        } catch (Exception e) {
16926            if (DEBUG_BACKUP) {
16927                Slog.e(TAG, "Unable to write default apps for backup", e);
16928            }
16929            return null;
16930        }
16931
16932        return dataStream.toByteArray();
16933    }
16934
16935    @Override
16936    public void restorePermissionGrants(byte[] backup, int userId) {
16937        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
16938            throw new SecurityException("Only the system may call restorePermissionGrants()");
16939        }
16940
16941        try {
16942            final XmlPullParser parser = Xml.newPullParser();
16943            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
16944            restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP,
16945                    new BlobXmlRestorer() {
16946                        @Override
16947                        public void apply(XmlPullParser parser, int userId)
16948                                throws XmlPullParserException, IOException {
16949                            synchronized (mPackages) {
16950                                processRestoredPermissionGrantsLPr(parser, userId);
16951                            }
16952                        }
16953                    } );
16954        } catch (Exception e) {
16955            if (DEBUG_BACKUP) {
16956                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
16957            }
16958        }
16959    }
16960
16961    private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId)
16962            throws IOException {
16963        serializer.startTag(null, TAG_ALL_GRANTS);
16964
16965        final int N = mSettings.mPackages.size();
16966        for (int i = 0; i < N; i++) {
16967            final PackageSetting ps = mSettings.mPackages.valueAt(i);
16968            boolean pkgGrantsKnown = false;
16969
16970            PermissionsState packagePerms = ps.getPermissionsState();
16971
16972            for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) {
16973                final int grantFlags = state.getFlags();
16974                // only look at grants that are not system/policy fixed
16975                if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) {
16976                    final boolean isGranted = state.isGranted();
16977                    // And only back up the user-twiddled state bits
16978                    if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) {
16979                        final String packageName = mSettings.mPackages.keyAt(i);
16980                        if (!pkgGrantsKnown) {
16981                            serializer.startTag(null, TAG_GRANT);
16982                            serializer.attribute(null, ATTR_PACKAGE_NAME, packageName);
16983                            pkgGrantsKnown = true;
16984                        }
16985
16986                        final boolean userSet =
16987                                (grantFlags & FLAG_PERMISSION_USER_SET) != 0;
16988                        final boolean userFixed =
16989                                (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0;
16990                        final boolean revoke =
16991                                (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0;
16992
16993                        serializer.startTag(null, TAG_PERMISSION);
16994                        serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName());
16995                        if (isGranted) {
16996                            serializer.attribute(null, ATTR_IS_GRANTED, "true");
16997                        }
16998                        if (userSet) {
16999                            serializer.attribute(null, ATTR_USER_SET, "true");
17000                        }
17001                        if (userFixed) {
17002                            serializer.attribute(null, ATTR_USER_FIXED, "true");
17003                        }
17004                        if (revoke) {
17005                            serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true");
17006                        }
17007                        serializer.endTag(null, TAG_PERMISSION);
17008                    }
17009                }
17010            }
17011
17012            if (pkgGrantsKnown) {
17013                serializer.endTag(null, TAG_GRANT);
17014            }
17015        }
17016
17017        serializer.endTag(null, TAG_ALL_GRANTS);
17018    }
17019
17020    private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId)
17021            throws XmlPullParserException, IOException {
17022        String pkgName = null;
17023        int outerDepth = parser.getDepth();
17024        int type;
17025        while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
17026                && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
17027            if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
17028                continue;
17029            }
17030
17031            final String tagName = parser.getName();
17032            if (tagName.equals(TAG_GRANT)) {
17033                pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME);
17034                if (DEBUG_BACKUP) {
17035                    Slog.v(TAG, "+++ Restoring grants for package " + pkgName);
17036                }
17037            } else if (tagName.equals(TAG_PERMISSION)) {
17038
17039                final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED));
17040                final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME);
17041
17042                int newFlagSet = 0;
17043                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) {
17044                    newFlagSet |= FLAG_PERMISSION_USER_SET;
17045                }
17046                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) {
17047                    newFlagSet |= FLAG_PERMISSION_USER_FIXED;
17048                }
17049                if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) {
17050                    newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE;
17051                }
17052                if (DEBUG_BACKUP) {
17053                    Slog.v(TAG, "  + Restoring grant: pkg=" + pkgName + " perm=" + permName
17054                            + " granted=" + isGranted + " bits=0x" + Integer.toHexString(newFlagSet));
17055                }
17056                final PackageSetting ps = mSettings.mPackages.get(pkgName);
17057                if (ps != null) {
17058                    // Already installed so we apply the grant immediately
17059                    if (DEBUG_BACKUP) {
17060                        Slog.v(TAG, "        + already installed; applying");
17061                    }
17062                    PermissionsState perms = ps.getPermissionsState();
17063                    BasePermission bp = mSettings.mPermissions.get(permName);
17064                    if (bp != null) {
17065                        if (isGranted) {
17066                            perms.grantRuntimePermission(bp, userId);
17067                        }
17068                        if (newFlagSet != 0) {
17069                            perms.updatePermissionFlags(bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet);
17070                        }
17071                    }
17072                } else {
17073                    // Need to wait for post-restore install to apply the grant
17074                    if (DEBUG_BACKUP) {
17075                        Slog.v(TAG, "        - not yet installed; saving for later");
17076                    }
17077                    mSettings.processRestoredPermissionGrantLPr(pkgName, permName,
17078                            isGranted, newFlagSet, userId);
17079                }
17080            } else {
17081                PackageManagerService.reportSettingsProblem(Log.WARN,
17082                        "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName);
17083                XmlUtils.skipCurrentTag(parser);
17084            }
17085        }
17086
17087        scheduleWriteSettingsLocked();
17088        mSettings.writeRuntimePermissionsForUserLPr(userId, false);
17089    }
17090
17091    @Override
17092    public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
17093            int sourceUserId, int targetUserId, int flags) {
17094        mContext.enforceCallingOrSelfPermission(
17095                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
17096        int callingUid = Binder.getCallingUid();
17097        enforceOwnerRights(ownerPackage, callingUid);
17098        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
17099        if (intentFilter.countActions() == 0) {
17100            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
17101            return;
17102        }
17103        synchronized (mPackages) {
17104            CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter,
17105                    ownerPackage, targetUserId, flags);
17106            CrossProfileIntentResolver resolver =
17107                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
17108            ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter);
17109            // We have all those whose filter is equal. Now checking if the rest is equal as well.
17110            if (existing != null) {
17111                int size = existing.size();
17112                for (int i = 0; i < size; i++) {
17113                    if (newFilter.equalsIgnoreFilter(existing.get(i))) {
17114                        return;
17115                    }
17116                }
17117            }
17118            resolver.addFilter(newFilter);
17119            scheduleWritePackageRestrictionsLocked(sourceUserId);
17120        }
17121    }
17122
17123    @Override
17124    public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) {
17125        mContext.enforceCallingOrSelfPermission(
17126                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
17127        int callingUid = Binder.getCallingUid();
17128        enforceOwnerRights(ownerPackage, callingUid);
17129        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
17130        synchronized (mPackages) {
17131            CrossProfileIntentResolver resolver =
17132                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
17133            ArraySet<CrossProfileIntentFilter> set =
17134                    new ArraySet<CrossProfileIntentFilter>(resolver.filterSet());
17135            for (CrossProfileIntentFilter filter : set) {
17136                if (filter.getOwnerPackage().equals(ownerPackage)) {
17137                    resolver.removeFilter(filter);
17138                }
17139            }
17140            scheduleWritePackageRestrictionsLocked(sourceUserId);
17141        }
17142    }
17143
17144    // Enforcing that callingUid is owning pkg on userId
17145    private void enforceOwnerRights(String pkg, int callingUid) {
17146        // The system owns everything.
17147        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
17148            return;
17149        }
17150        int callingUserId = UserHandle.getUserId(callingUid);
17151        PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
17152        if (pi == null) {
17153            throw new IllegalArgumentException("Unknown package " + pkg + " on user "
17154                    + callingUserId);
17155        }
17156        if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
17157            throw new SecurityException("Calling uid " + callingUid
17158                    + " does not own package " + pkg);
17159        }
17160    }
17161
17162    @Override
17163    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
17164        return getHomeActivitiesAsUser(allHomeCandidates, UserHandle.getCallingUserId());
17165    }
17166
17167    private Intent getHomeIntent() {
17168        Intent intent = new Intent(Intent.ACTION_MAIN);
17169        intent.addCategory(Intent.CATEGORY_HOME);
17170        return intent;
17171    }
17172
17173    private IntentFilter getHomeFilter() {
17174        IntentFilter filter = new IntentFilter(Intent.ACTION_MAIN);
17175        filter.addCategory(Intent.CATEGORY_HOME);
17176        filter.addCategory(Intent.CATEGORY_DEFAULT);
17177        return filter;
17178    }
17179
17180    ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
17181            int userId) {
17182        Intent intent  = getHomeIntent();
17183        List<ResolveInfo> list = queryIntentActivitiesInternal(intent, null,
17184                PackageManager.GET_META_DATA, userId);
17185        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
17186                true, false, false, userId);
17187
17188        allHomeCandidates.clear();
17189        if (list != null) {
17190            for (ResolveInfo ri : list) {
17191                allHomeCandidates.add(ri);
17192            }
17193        }
17194        return (preferred == null || preferred.activityInfo == null)
17195                ? null
17196                : new ComponentName(preferred.activityInfo.packageName,
17197                        preferred.activityInfo.name);
17198    }
17199
17200    @Override
17201    public void setHomeActivity(ComponentName comp, int userId) {
17202        ArrayList<ResolveInfo> homeActivities = new ArrayList<>();
17203        getHomeActivitiesAsUser(homeActivities, userId);
17204
17205        boolean found = false;
17206
17207        final int size = homeActivities.size();
17208        final ComponentName[] set = new ComponentName[size];
17209        for (int i = 0; i < size; i++) {
17210            final ResolveInfo candidate = homeActivities.get(i);
17211            final ActivityInfo info = candidate.activityInfo;
17212            final ComponentName activityName = new ComponentName(info.packageName, info.name);
17213            set[i] = activityName;
17214            if (!found && activityName.equals(comp)) {
17215                found = true;
17216            }
17217        }
17218        if (!found) {
17219            throw new IllegalArgumentException("Component " + comp + " cannot be home on user "
17220                    + userId);
17221        }
17222        replacePreferredActivity(getHomeFilter(), IntentFilter.MATCH_CATEGORY_EMPTY,
17223                set, comp, userId);
17224    }
17225
17226    private @Nullable String getSetupWizardPackageName() {
17227        final Intent intent = new Intent(Intent.ACTION_MAIN);
17228        intent.addCategory(Intent.CATEGORY_SETUP_WIZARD);
17229
17230        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
17231                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
17232                        | MATCH_DISABLED_COMPONENTS,
17233                UserHandle.myUserId());
17234        if (matches.size() == 1) {
17235            return matches.get(0).getComponentInfo().packageName;
17236        } else {
17237            Slog.e(TAG, "There should probably be exactly one setup wizard; found " + matches.size()
17238                    + ": matches=" + matches);
17239            return null;
17240        }
17241    }
17242
17243    @Override
17244    public void setApplicationEnabledSetting(String appPackageName,
17245            int newState, int flags, int userId, String callingPackage) {
17246        if (!sUserManager.exists(userId)) return;
17247        if (callingPackage == null) {
17248            callingPackage = Integer.toString(Binder.getCallingUid());
17249        }
17250        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
17251    }
17252
17253    @Override
17254    public void setComponentEnabledSetting(ComponentName componentName,
17255            int newState, int flags, int userId) {
17256        if (!sUserManager.exists(userId)) return;
17257        setEnabledSetting(componentName.getPackageName(),
17258                componentName.getClassName(), newState, flags, userId, null);
17259    }
17260
17261    private void setEnabledSetting(final String packageName, String className, int newState,
17262            final int flags, int userId, String callingPackage) {
17263        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
17264              || newState == COMPONENT_ENABLED_STATE_ENABLED
17265              || newState == COMPONENT_ENABLED_STATE_DISABLED
17266              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
17267              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
17268            throw new IllegalArgumentException("Invalid new component state: "
17269                    + newState);
17270        }
17271        PackageSetting pkgSetting;
17272        final int uid = Binder.getCallingUid();
17273        final int permission;
17274        if (uid == Process.SYSTEM_UID) {
17275            permission = PackageManager.PERMISSION_GRANTED;
17276        } else {
17277            permission = mContext.checkCallingOrSelfPermission(
17278                    android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
17279        }
17280        enforceCrossUserPermission(uid, userId,
17281                false /* requireFullPermission */, true /* checkShell */, "set enabled");
17282        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
17283        boolean sendNow = false;
17284        boolean isApp = (className == null);
17285        String componentName = isApp ? packageName : className;
17286        int packageUid = -1;
17287        ArrayList<String> components;
17288
17289        // writer
17290        synchronized (mPackages) {
17291            pkgSetting = mSettings.mPackages.get(packageName);
17292            if (pkgSetting == null) {
17293                if (className == null) {
17294                    throw new IllegalArgumentException("Unknown package: " + packageName);
17295                }
17296                throw new IllegalArgumentException(
17297                        "Unknown component: " + packageName + "/" + className);
17298            }
17299            // Allow root and verify that userId is not being specified by a different user
17300            if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) {
17301                throw new SecurityException(
17302                        "Permission Denial: attempt to change component state from pid="
17303                        + Binder.getCallingPid()
17304                        + ", uid=" + uid + ", package uid=" + pkgSetting.appId);
17305            }
17306            if (className == null) {
17307                // We're dealing with an application/package level state change
17308                if (pkgSetting.getEnabled(userId) == newState) {
17309                    // Nothing to do
17310                    return;
17311                }
17312                if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
17313                    || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
17314                    // Don't care about who enables an app.
17315                    callingPackage = null;
17316                }
17317                pkgSetting.setEnabled(newState, userId, callingPackage);
17318                // pkgSetting.pkg.mSetEnabled = newState;
17319            } else {
17320                // We're dealing with a component level state change
17321                // First, verify that this is a valid class name.
17322                PackageParser.Package pkg = pkgSetting.pkg;
17323                if (pkg == null || !pkg.hasComponentClassName(className)) {
17324                    if (pkg != null &&
17325                            pkg.applicationInfo.targetSdkVersion >=
17326                                    Build.VERSION_CODES.JELLY_BEAN) {
17327                        throw new IllegalArgumentException("Component class " + className
17328                                + " does not exist in " + packageName);
17329                    } else {
17330                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
17331                                + className + " does not exist in " + packageName);
17332                    }
17333                }
17334                switch (newState) {
17335                case COMPONENT_ENABLED_STATE_ENABLED:
17336                    if (!pkgSetting.enableComponentLPw(className, userId)) {
17337                        return;
17338                    }
17339                    break;
17340                case COMPONENT_ENABLED_STATE_DISABLED:
17341                    if (!pkgSetting.disableComponentLPw(className, userId)) {
17342                        return;
17343                    }
17344                    break;
17345                case COMPONENT_ENABLED_STATE_DEFAULT:
17346                    if (!pkgSetting.restoreComponentLPw(className, userId)) {
17347                        return;
17348                    }
17349                    break;
17350                default:
17351                    Slog.e(TAG, "Invalid new component state: " + newState);
17352                    return;
17353                }
17354            }
17355            scheduleWritePackageRestrictionsLocked(userId);
17356            components = mPendingBroadcasts.get(userId, packageName);
17357            final boolean newPackage = components == null;
17358            if (newPackage) {
17359                components = new ArrayList<String>();
17360            }
17361            if (!components.contains(componentName)) {
17362                components.add(componentName);
17363            }
17364            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
17365                sendNow = true;
17366                // Purge entry from pending broadcast list if another one exists already
17367                // since we are sending one right away.
17368                mPendingBroadcasts.remove(userId, packageName);
17369            } else {
17370                if (newPackage) {
17371                    mPendingBroadcasts.put(userId, packageName, components);
17372                }
17373                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
17374                    // Schedule a message
17375                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
17376                }
17377            }
17378        }
17379
17380        long callingId = Binder.clearCallingIdentity();
17381        try {
17382            if (sendNow) {
17383                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
17384                sendPackageChangedBroadcast(packageName,
17385                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
17386            }
17387        } finally {
17388            Binder.restoreCallingIdentity(callingId);
17389        }
17390    }
17391
17392    @Override
17393    public void flushPackageRestrictionsAsUser(int userId) {
17394        if (!sUserManager.exists(userId)) {
17395            return;
17396        }
17397        enforceCrossUserPermission(Binder.getCallingUid(), userId, false /* requireFullPermission*/,
17398                false /* checkShell */, "flushPackageRestrictions");
17399        synchronized (mPackages) {
17400            mSettings.writePackageRestrictionsLPr(userId);
17401            mDirtyUsers.remove(userId);
17402            if (mDirtyUsers.isEmpty()) {
17403                mHandler.removeMessages(WRITE_PACKAGE_RESTRICTIONS);
17404            }
17405        }
17406    }
17407
17408    private void sendPackageChangedBroadcast(String packageName,
17409            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
17410        if (DEBUG_INSTALL)
17411            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
17412                    + componentNames);
17413        Bundle extras = new Bundle(4);
17414        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
17415        String nameList[] = new String[componentNames.size()];
17416        componentNames.toArray(nameList);
17417        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
17418        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
17419        extras.putInt(Intent.EXTRA_UID, packageUid);
17420        // If this is not reporting a change of the overall package, then only send it
17421        // to registered receivers.  We don't want to launch a swath of apps for every
17422        // little component state change.
17423        final int flags = !componentNames.contains(packageName)
17424                ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0;
17425        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, flags, null, null,
17426                new int[] {UserHandle.getUserId(packageUid)});
17427    }
17428
17429    @Override
17430    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
17431        if (!sUserManager.exists(userId)) return;
17432        final int uid = Binder.getCallingUid();
17433        final int permission = mContext.checkCallingOrSelfPermission(
17434                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
17435        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
17436        enforceCrossUserPermission(uid, userId,
17437                true /* requireFullPermission */, true /* checkShell */, "stop package");
17438        // writer
17439        synchronized (mPackages) {
17440            if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped,
17441                    allowedByPermission, uid, userId)) {
17442                scheduleWritePackageRestrictionsLocked(userId);
17443            }
17444        }
17445    }
17446
17447    @Override
17448    public String getInstallerPackageName(String packageName) {
17449        // reader
17450        synchronized (mPackages) {
17451            return mSettings.getInstallerPackageNameLPr(packageName);
17452        }
17453    }
17454
17455    @Override
17456    public int getApplicationEnabledSetting(String packageName, int userId) {
17457        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
17458        int uid = Binder.getCallingUid();
17459        enforceCrossUserPermission(uid, userId,
17460                false /* requireFullPermission */, false /* checkShell */, "get enabled");
17461        // reader
17462        synchronized (mPackages) {
17463            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
17464        }
17465    }
17466
17467    @Override
17468    public int getComponentEnabledSetting(ComponentName componentName, int userId) {
17469        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
17470        int uid = Binder.getCallingUid();
17471        enforceCrossUserPermission(uid, userId,
17472                false /* requireFullPermission */, false /* checkShell */, "get component enabled");
17473        // reader
17474        synchronized (mPackages) {
17475            return mSettings.getComponentEnabledSettingLPr(componentName, userId);
17476        }
17477    }
17478
17479    @Override
17480    public void enterSafeMode() {
17481        enforceSystemOrRoot("Only the system can request entering safe mode");
17482
17483        if (!mSystemReady) {
17484            mSafeMode = true;
17485        }
17486    }
17487
17488    @Override
17489    public void systemReady() {
17490        mSystemReady = true;
17491
17492        // Read the compatibilty setting when the system is ready.
17493        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
17494                mContext.getContentResolver(),
17495                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
17496        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
17497        if (DEBUG_SETTINGS) {
17498            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
17499        }
17500
17501        int[] grantPermissionsUserIds = EMPTY_INT_ARRAY;
17502
17503        synchronized (mPackages) {
17504            // Verify that all of the preferred activity components actually
17505            // exist.  It is possible for applications to be updated and at
17506            // that point remove a previously declared activity component that
17507            // had been set as a preferred activity.  We try to clean this up
17508            // the next time we encounter that preferred activity, but it is
17509            // possible for the user flow to never be able to return to that
17510            // situation so here we do a sanity check to make sure we haven't
17511            // left any junk around.
17512            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
17513            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
17514                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
17515                removed.clear();
17516                for (PreferredActivity pa : pir.filterSet()) {
17517                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
17518                        removed.add(pa);
17519                    }
17520                }
17521                if (removed.size() > 0) {
17522                    for (int r=0; r<removed.size(); r++) {
17523                        PreferredActivity pa = removed.get(r);
17524                        Slog.w(TAG, "Removing dangling preferred activity: "
17525                                + pa.mPref.mComponent);
17526                        pir.removeFilter(pa);
17527                    }
17528                    mSettings.writePackageRestrictionsLPr(
17529                            mSettings.mPreferredActivities.keyAt(i));
17530                }
17531            }
17532
17533            for (int userId : UserManagerService.getInstance().getUserIds()) {
17534                if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) {
17535                    grantPermissionsUserIds = ArrayUtils.appendInt(
17536                            grantPermissionsUserIds, userId);
17537                }
17538            }
17539        }
17540        sUserManager.systemReady();
17541
17542        // If we upgraded grant all default permissions before kicking off.
17543        for (int userId : grantPermissionsUserIds) {
17544            mDefaultPermissionPolicy.grantDefaultPermissions(userId);
17545        }
17546
17547        // Kick off any messages waiting for system ready
17548        if (mPostSystemReadyMessages != null) {
17549            for (Message msg : mPostSystemReadyMessages) {
17550                msg.sendToTarget();
17551            }
17552            mPostSystemReadyMessages = null;
17553        }
17554
17555        // Watch for external volumes that come and go over time
17556        final StorageManager storage = mContext.getSystemService(StorageManager.class);
17557        storage.registerListener(mStorageListener);
17558
17559        mInstallerService.systemReady();
17560        mPackageDexOptimizer.systemReady();
17561
17562        MountServiceInternal mountServiceInternal = LocalServices.getService(
17563                MountServiceInternal.class);
17564        mountServiceInternal.addExternalStoragePolicy(
17565                new MountServiceInternal.ExternalStorageMountPolicy() {
17566            @Override
17567            public int getMountMode(int uid, String packageName) {
17568                if (Process.isIsolated(uid)) {
17569                    return Zygote.MOUNT_EXTERNAL_NONE;
17570                }
17571                if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) {
17572                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
17573                }
17574                if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
17575                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
17576                }
17577                if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
17578                    return Zygote.MOUNT_EXTERNAL_READ;
17579                }
17580                return Zygote.MOUNT_EXTERNAL_WRITE;
17581            }
17582
17583            @Override
17584            public boolean hasExternalStorage(int uid, String packageName) {
17585                return true;
17586            }
17587        });
17588
17589        // Now that we're mostly running, clean up stale users and apps
17590        reconcileUsers(StorageManager.UUID_PRIVATE_INTERNAL);
17591        reconcileApps(StorageManager.UUID_PRIVATE_INTERNAL);
17592    }
17593
17594    @Override
17595    public boolean isSafeMode() {
17596        return mSafeMode;
17597    }
17598
17599    @Override
17600    public boolean hasSystemUidErrors() {
17601        return mHasSystemUidErrors;
17602    }
17603
17604    static String arrayToString(int[] array) {
17605        StringBuffer buf = new StringBuffer(128);
17606        buf.append('[');
17607        if (array != null) {
17608            for (int i=0; i<array.length; i++) {
17609                if (i > 0) buf.append(", ");
17610                buf.append(array[i]);
17611            }
17612        }
17613        buf.append(']');
17614        return buf.toString();
17615    }
17616
17617    static class DumpState {
17618        public static final int DUMP_LIBS = 1 << 0;
17619        public static final int DUMP_FEATURES = 1 << 1;
17620        public static final int DUMP_ACTIVITY_RESOLVERS = 1 << 2;
17621        public static final int DUMP_SERVICE_RESOLVERS = 1 << 3;
17622        public static final int DUMP_RECEIVER_RESOLVERS = 1 << 4;
17623        public static final int DUMP_CONTENT_RESOLVERS = 1 << 5;
17624        public static final int DUMP_PERMISSIONS = 1 << 6;
17625        public static final int DUMP_PACKAGES = 1 << 7;
17626        public static final int DUMP_SHARED_USERS = 1 << 8;
17627        public static final int DUMP_MESSAGES = 1 << 9;
17628        public static final int DUMP_PROVIDERS = 1 << 10;
17629        public static final int DUMP_VERIFIERS = 1 << 11;
17630        public static final int DUMP_PREFERRED = 1 << 12;
17631        public static final int DUMP_PREFERRED_XML = 1 << 13;
17632        public static final int DUMP_KEYSETS = 1 << 14;
17633        public static final int DUMP_VERSION = 1 << 15;
17634        public static final int DUMP_INSTALLS = 1 << 16;
17635        public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 17;
17636        public static final int DUMP_DOMAIN_PREFERRED = 1 << 18;
17637        public static final int DUMP_FROZEN = 1 << 19;
17638
17639        public static final int OPTION_SHOW_FILTERS = 1 << 0;
17640
17641        private int mTypes;
17642
17643        private int mOptions;
17644
17645        private boolean mTitlePrinted;
17646
17647        private SharedUserSetting mSharedUser;
17648
17649        public boolean isDumping(int type) {
17650            if (mTypes == 0 && type != DUMP_PREFERRED_XML) {
17651                return true;
17652            }
17653
17654            return (mTypes & type) != 0;
17655        }
17656
17657        public void setDump(int type) {
17658            mTypes |= type;
17659        }
17660
17661        public boolean isOptionEnabled(int option) {
17662            return (mOptions & option) != 0;
17663        }
17664
17665        public void setOptionEnabled(int option) {
17666            mOptions |= option;
17667        }
17668
17669        public boolean onTitlePrinted() {
17670            final boolean printed = mTitlePrinted;
17671            mTitlePrinted = true;
17672            return printed;
17673        }
17674
17675        public boolean getTitlePrinted() {
17676            return mTitlePrinted;
17677        }
17678
17679        public void setTitlePrinted(boolean enabled) {
17680            mTitlePrinted = enabled;
17681        }
17682
17683        public SharedUserSetting getSharedUser() {
17684            return mSharedUser;
17685        }
17686
17687        public void setSharedUser(SharedUserSetting user) {
17688            mSharedUser = user;
17689        }
17690    }
17691
17692    @Override
17693    public void onShellCommand(FileDescriptor in, FileDescriptor out,
17694            FileDescriptor err, String[] args, ResultReceiver resultReceiver) {
17695        (new PackageManagerShellCommand(this)).exec(
17696                this, in, out, err, args, resultReceiver);
17697    }
17698
17699    @Override
17700    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
17701        if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
17702                != PackageManager.PERMISSION_GRANTED) {
17703            pw.println("Permission Denial: can't dump ActivityManager from from pid="
17704                    + Binder.getCallingPid()
17705                    + ", uid=" + Binder.getCallingUid()
17706                    + " without permission "
17707                    + android.Manifest.permission.DUMP);
17708            return;
17709        }
17710
17711        DumpState dumpState = new DumpState();
17712        boolean fullPreferred = false;
17713        boolean checkin = false;
17714
17715        String packageName = null;
17716        ArraySet<String> permissionNames = null;
17717
17718        int opti = 0;
17719        while (opti < args.length) {
17720            String opt = args[opti];
17721            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
17722                break;
17723            }
17724            opti++;
17725
17726            if ("-a".equals(opt)) {
17727                // Right now we only know how to print all.
17728            } else if ("-h".equals(opt)) {
17729                pw.println("Package manager dump options:");
17730                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
17731                pw.println("    --checkin: dump for a checkin");
17732                pw.println("    -f: print details of intent filters");
17733                pw.println("    -h: print this help");
17734                pw.println("  cmd may be one of:");
17735                pw.println("    l[ibraries]: list known shared libraries");
17736                pw.println("    f[eatures]: list device features");
17737                pw.println("    k[eysets]: print known keysets");
17738                pw.println("    r[esolvers] [activity|service|receiver|content]: dump intent resolvers");
17739                pw.println("    perm[issions]: dump permissions");
17740                pw.println("    permission [name ...]: dump declaration and use of given permission");
17741                pw.println("    pref[erred]: print preferred package settings");
17742                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
17743                pw.println("    prov[iders]: dump content providers");
17744                pw.println("    p[ackages]: dump installed packages");
17745                pw.println("    s[hared-users]: dump shared user IDs");
17746                pw.println("    m[essages]: print collected runtime messages");
17747                pw.println("    v[erifiers]: print package verifier info");
17748                pw.println("    d[omain-preferred-apps]: print domains preferred apps");
17749                pw.println("    i[ntent-filter-verifiers]|ifv: print intent filter verifier info");
17750                pw.println("    version: print database version info");
17751                pw.println("    write: write current settings now");
17752                pw.println("    installs: details about install sessions");
17753                pw.println("    check-permission <permission> <package> [<user>]: does pkg hold perm?");
17754                pw.println("    <package.name>: info about given package");
17755                return;
17756            } else if ("--checkin".equals(opt)) {
17757                checkin = true;
17758            } else if ("-f".equals(opt)) {
17759                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
17760            } else {
17761                pw.println("Unknown argument: " + opt + "; use -h for help");
17762            }
17763        }
17764
17765        // Is the caller requesting to dump a particular piece of data?
17766        if (opti < args.length) {
17767            String cmd = args[opti];
17768            opti++;
17769            // Is this a package name?
17770            if ("android".equals(cmd) || cmd.contains(".")) {
17771                packageName = cmd;
17772                // When dumping a single package, we always dump all of its
17773                // filter information since the amount of data will be reasonable.
17774                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
17775            } else if ("check-permission".equals(cmd)) {
17776                if (opti >= args.length) {
17777                    pw.println("Error: check-permission missing permission argument");
17778                    return;
17779                }
17780                String perm = args[opti];
17781                opti++;
17782                if (opti >= args.length) {
17783                    pw.println("Error: check-permission missing package argument");
17784                    return;
17785                }
17786                String pkg = args[opti];
17787                opti++;
17788                int user = UserHandle.getUserId(Binder.getCallingUid());
17789                if (opti < args.length) {
17790                    try {
17791                        user = Integer.parseInt(args[opti]);
17792                    } catch (NumberFormatException e) {
17793                        pw.println("Error: check-permission user argument is not a number: "
17794                                + args[opti]);
17795                        return;
17796                    }
17797                }
17798                pw.println(checkPermission(perm, pkg, user));
17799                return;
17800            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
17801                dumpState.setDump(DumpState.DUMP_LIBS);
17802            } else if ("f".equals(cmd) || "features".equals(cmd)) {
17803                dumpState.setDump(DumpState.DUMP_FEATURES);
17804            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
17805                if (opti >= args.length) {
17806                    dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS
17807                            | DumpState.DUMP_SERVICE_RESOLVERS
17808                            | DumpState.DUMP_RECEIVER_RESOLVERS
17809                            | DumpState.DUMP_CONTENT_RESOLVERS);
17810                } else {
17811                    while (opti < args.length) {
17812                        String name = args[opti];
17813                        if ("a".equals(name) || "activity".equals(name)) {
17814                            dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS);
17815                        } else if ("s".equals(name) || "service".equals(name)) {
17816                            dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS);
17817                        } else if ("r".equals(name) || "receiver".equals(name)) {
17818                            dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS);
17819                        } else if ("c".equals(name) || "content".equals(name)) {
17820                            dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS);
17821                        } else {
17822                            pw.println("Error: unknown resolver table type: " + name);
17823                            return;
17824                        }
17825                        opti++;
17826                    }
17827                }
17828            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
17829                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
17830            } else if ("permission".equals(cmd)) {
17831                if (opti >= args.length) {
17832                    pw.println("Error: permission requires permission name");
17833                    return;
17834                }
17835                permissionNames = new ArraySet<>();
17836                while (opti < args.length) {
17837                    permissionNames.add(args[opti]);
17838                    opti++;
17839                }
17840                dumpState.setDump(DumpState.DUMP_PERMISSIONS
17841                        | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS);
17842            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
17843                dumpState.setDump(DumpState.DUMP_PREFERRED);
17844            } else if ("preferred-xml".equals(cmd)) {
17845                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
17846                if (opti < args.length && "--full".equals(args[opti])) {
17847                    fullPreferred = true;
17848                    opti++;
17849                }
17850            } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) {
17851                dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED);
17852            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
17853                dumpState.setDump(DumpState.DUMP_PACKAGES);
17854            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
17855                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
17856            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
17857                dumpState.setDump(DumpState.DUMP_PROVIDERS);
17858            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
17859                dumpState.setDump(DumpState.DUMP_MESSAGES);
17860            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
17861                dumpState.setDump(DumpState.DUMP_VERIFIERS);
17862            } else if ("i".equals(cmd) || "ifv".equals(cmd)
17863                    || "intent-filter-verifiers".equals(cmd)) {
17864                dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS);
17865            } else if ("version".equals(cmd)) {
17866                dumpState.setDump(DumpState.DUMP_VERSION);
17867            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
17868                dumpState.setDump(DumpState.DUMP_KEYSETS);
17869            } else if ("installs".equals(cmd)) {
17870                dumpState.setDump(DumpState.DUMP_INSTALLS);
17871            } else if ("frozen".equals(cmd)) {
17872                dumpState.setDump(DumpState.DUMP_FROZEN);
17873            } else if ("write".equals(cmd)) {
17874                synchronized (mPackages) {
17875                    mSettings.writeLPr();
17876                    pw.println("Settings written.");
17877                    return;
17878                }
17879            }
17880        }
17881
17882        if (checkin) {
17883            pw.println("vers,1");
17884        }
17885
17886        // reader
17887        synchronized (mPackages) {
17888            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
17889                if (!checkin) {
17890                    if (dumpState.onTitlePrinted())
17891                        pw.println();
17892                    pw.println("Database versions:");
17893                    mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, "  "));
17894                }
17895            }
17896
17897            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
17898                if (!checkin) {
17899                    if (dumpState.onTitlePrinted())
17900                        pw.println();
17901                    pw.println("Verifiers:");
17902                    pw.print("  Required: ");
17903                    pw.print(mRequiredVerifierPackage);
17904                    pw.print(" (uid=");
17905                    pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
17906                            UserHandle.USER_SYSTEM));
17907                    pw.println(")");
17908                } else if (mRequiredVerifierPackage != null) {
17909                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
17910                    pw.print(",");
17911                    pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
17912                            UserHandle.USER_SYSTEM));
17913                }
17914            }
17915
17916            if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) &&
17917                    packageName == null) {
17918                if (mIntentFilterVerifierComponent != null) {
17919                    String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
17920                    if (!checkin) {
17921                        if (dumpState.onTitlePrinted())
17922                            pw.println();
17923                        pw.println("Intent Filter Verifier:");
17924                        pw.print("  Using: ");
17925                        pw.print(verifierPackageName);
17926                        pw.print(" (uid=");
17927                        pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
17928                                UserHandle.USER_SYSTEM));
17929                        pw.println(")");
17930                    } else if (verifierPackageName != null) {
17931                        pw.print("ifv,"); pw.print(verifierPackageName);
17932                        pw.print(",");
17933                        pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
17934                                UserHandle.USER_SYSTEM));
17935                    }
17936                } else {
17937                    pw.println();
17938                    pw.println("No Intent Filter Verifier available!");
17939                }
17940            }
17941
17942            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
17943                boolean printedHeader = false;
17944                final Iterator<String> it = mSharedLibraries.keySet().iterator();
17945                while (it.hasNext()) {
17946                    String name = it.next();
17947                    SharedLibraryEntry ent = mSharedLibraries.get(name);
17948                    if (!checkin) {
17949                        if (!printedHeader) {
17950                            if (dumpState.onTitlePrinted())
17951                                pw.println();
17952                            pw.println("Libraries:");
17953                            printedHeader = true;
17954                        }
17955                        pw.print("  ");
17956                    } else {
17957                        pw.print("lib,");
17958                    }
17959                    pw.print(name);
17960                    if (!checkin) {
17961                        pw.print(" -> ");
17962                    }
17963                    if (ent.path != null) {
17964                        if (!checkin) {
17965                            pw.print("(jar) ");
17966                            pw.print(ent.path);
17967                        } else {
17968                            pw.print(",jar,");
17969                            pw.print(ent.path);
17970                        }
17971                    } else {
17972                        if (!checkin) {
17973                            pw.print("(apk) ");
17974                            pw.print(ent.apk);
17975                        } else {
17976                            pw.print(",apk,");
17977                            pw.print(ent.apk);
17978                        }
17979                    }
17980                    pw.println();
17981                }
17982            }
17983
17984            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
17985                if (dumpState.onTitlePrinted())
17986                    pw.println();
17987                if (!checkin) {
17988                    pw.println("Features:");
17989                }
17990
17991                for (FeatureInfo feat : mAvailableFeatures.values()) {
17992                    if (checkin) {
17993                        pw.print("feat,");
17994                        pw.print(feat.name);
17995                        pw.print(",");
17996                        pw.println(feat.version);
17997                    } else {
17998                        pw.print("  ");
17999                        pw.print(feat.name);
18000                        if (feat.version > 0) {
18001                            pw.print(" version=");
18002                            pw.print(feat.version);
18003                        }
18004                        pw.println();
18005                    }
18006                }
18007            }
18008
18009            if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) {
18010                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
18011                        : "Activity Resolver Table:", "  ", packageName,
18012                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
18013                    dumpState.setTitlePrinted(true);
18014                }
18015            }
18016            if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) {
18017                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
18018                        : "Receiver Resolver Table:", "  ", packageName,
18019                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
18020                    dumpState.setTitlePrinted(true);
18021                }
18022            }
18023            if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) {
18024                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
18025                        : "Service Resolver Table:", "  ", packageName,
18026                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
18027                    dumpState.setTitlePrinted(true);
18028                }
18029            }
18030            if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) {
18031                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
18032                        : "Provider Resolver Table:", "  ", packageName,
18033                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
18034                    dumpState.setTitlePrinted(true);
18035                }
18036            }
18037
18038            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
18039                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
18040                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
18041                    int user = mSettings.mPreferredActivities.keyAt(i);
18042                    if (pir.dump(pw,
18043                            dumpState.getTitlePrinted()
18044                                ? "\nPreferred Activities User " + user + ":"
18045                                : "Preferred Activities User " + user + ":", "  ",
18046                            packageName, true, false)) {
18047                        dumpState.setTitlePrinted(true);
18048                    }
18049                }
18050            }
18051
18052            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
18053                pw.flush();
18054                FileOutputStream fout = new FileOutputStream(fd);
18055                BufferedOutputStream str = new BufferedOutputStream(fout);
18056                XmlSerializer serializer = new FastXmlSerializer();
18057                try {
18058                    serializer.setOutput(str, StandardCharsets.UTF_8.name());
18059                    serializer.startDocument(null, true);
18060                    serializer.setFeature(
18061                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
18062                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
18063                    serializer.endDocument();
18064                    serializer.flush();
18065                } catch (IllegalArgumentException e) {
18066                    pw.println("Failed writing: " + e);
18067                } catch (IllegalStateException e) {
18068                    pw.println("Failed writing: " + e);
18069                } catch (IOException e) {
18070                    pw.println("Failed writing: " + e);
18071                }
18072            }
18073
18074            if (!checkin
18075                    && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)
18076                    && packageName == null) {
18077                pw.println();
18078                int count = mSettings.mPackages.size();
18079                if (count == 0) {
18080                    pw.println("No applications!");
18081                    pw.println();
18082                } else {
18083                    final String prefix = "  ";
18084                    Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values();
18085                    if (allPackageSettings.size() == 0) {
18086                        pw.println("No domain preferred apps!");
18087                        pw.println();
18088                    } else {
18089                        pw.println("App verification status:");
18090                        pw.println();
18091                        count = 0;
18092                        for (PackageSetting ps : allPackageSettings) {
18093                            IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
18094                            if (ivi == null || ivi.getPackageName() == null) continue;
18095                            pw.println(prefix + "Package: " + ivi.getPackageName());
18096                            pw.println(prefix + "Domains: " + ivi.getDomainsString());
18097                            pw.println(prefix + "Status:  " + ivi.getStatusString());
18098                            pw.println();
18099                            count++;
18100                        }
18101                        if (count == 0) {
18102                            pw.println(prefix + "No app verification established.");
18103                            pw.println();
18104                        }
18105                        for (int userId : sUserManager.getUserIds()) {
18106                            pw.println("App linkages for user " + userId + ":");
18107                            pw.println();
18108                            count = 0;
18109                            for (PackageSetting ps : allPackageSettings) {
18110                                final long status = ps.getDomainVerificationStatusForUser(userId);
18111                                if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
18112                                    continue;
18113                                }
18114                                pw.println(prefix + "Package: " + ps.name);
18115                                pw.println(prefix + "Domains: " + dumpDomainString(ps.name));
18116                                String statusStr = IntentFilterVerificationInfo.
18117                                        getStatusStringFromValue(status);
18118                                pw.println(prefix + "Status:  " + statusStr);
18119                                pw.println();
18120                                count++;
18121                            }
18122                            if (count == 0) {
18123                                pw.println(prefix + "No configured app linkages.");
18124                                pw.println();
18125                            }
18126                        }
18127                    }
18128                }
18129            }
18130
18131            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
18132                mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState);
18133                if (packageName == null && permissionNames == null) {
18134                    for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) {
18135                        if (iperm == 0) {
18136                            if (dumpState.onTitlePrinted())
18137                                pw.println();
18138                            pw.println("AppOp Permissions:");
18139                        }
18140                        pw.print("  AppOp Permission ");
18141                        pw.print(mAppOpPermissionPackages.keyAt(iperm));
18142                        pw.println(":");
18143                        ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm);
18144                        for (int ipkg=0; ipkg<pkgs.size(); ipkg++) {
18145                            pw.print("    "); pw.println(pkgs.valueAt(ipkg));
18146                        }
18147                    }
18148                }
18149            }
18150
18151            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
18152                boolean printedSomething = false;
18153                for (PackageParser.Provider p : mProviders.mProviders.values()) {
18154                    if (packageName != null && !packageName.equals(p.info.packageName)) {
18155                        continue;
18156                    }
18157                    if (!printedSomething) {
18158                        if (dumpState.onTitlePrinted())
18159                            pw.println();
18160                        pw.println("Registered ContentProviders:");
18161                        printedSomething = true;
18162                    }
18163                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
18164                    pw.print("    "); pw.println(p.toString());
18165                }
18166                printedSomething = false;
18167                for (Map.Entry<String, PackageParser.Provider> entry :
18168                        mProvidersByAuthority.entrySet()) {
18169                    PackageParser.Provider p = entry.getValue();
18170                    if (packageName != null && !packageName.equals(p.info.packageName)) {
18171                        continue;
18172                    }
18173                    if (!printedSomething) {
18174                        if (dumpState.onTitlePrinted())
18175                            pw.println();
18176                        pw.println("ContentProvider Authorities:");
18177                        printedSomething = true;
18178                    }
18179                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
18180                    pw.print("    "); pw.println(p.toString());
18181                    if (p.info != null && p.info.applicationInfo != null) {
18182                        final String appInfo = p.info.applicationInfo.toString();
18183                        pw.print("      applicationInfo="); pw.println(appInfo);
18184                    }
18185                }
18186            }
18187
18188            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
18189                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
18190            }
18191
18192            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
18193                mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin);
18194            }
18195
18196            if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
18197                mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin);
18198            }
18199
18200            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) {
18201                mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState);
18202            }
18203
18204            if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
18205                // XXX should handle packageName != null by dumping only install data that
18206                // the given package is involved with.
18207                if (dumpState.onTitlePrinted()) pw.println();
18208                mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
18209            }
18210
18211            if (!checkin && dumpState.isDumping(DumpState.DUMP_FROZEN) && packageName == null) {
18212                // XXX should handle packageName != null by dumping only install data that
18213                // the given package is involved with.
18214                if (dumpState.onTitlePrinted()) pw.println();
18215
18216                final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
18217                ipw.println();
18218                ipw.println("Frozen packages:");
18219                ipw.increaseIndent();
18220                if (mFrozenPackages.size() == 0) {
18221                    ipw.println("(none)");
18222                } else {
18223                    for (int i = 0; i < mFrozenPackages.size(); i++) {
18224                        ipw.println(mFrozenPackages.valueAt(i));
18225                    }
18226                }
18227                ipw.decreaseIndent();
18228            }
18229
18230            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
18231                if (dumpState.onTitlePrinted()) pw.println();
18232                mSettings.dumpReadMessagesLPr(pw, dumpState);
18233
18234                pw.println();
18235                pw.println("Package warning messages:");
18236                BufferedReader in = null;
18237                String line = null;
18238                try {
18239                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
18240                    while ((line = in.readLine()) != null) {
18241                        if (line.contains("ignored: updated version")) continue;
18242                        pw.println(line);
18243                    }
18244                } catch (IOException ignored) {
18245                } finally {
18246                    IoUtils.closeQuietly(in);
18247                }
18248            }
18249
18250            if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) {
18251                BufferedReader in = null;
18252                String line = null;
18253                try {
18254                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
18255                    while ((line = in.readLine()) != null) {
18256                        if (line.contains("ignored: updated version")) continue;
18257                        pw.print("msg,");
18258                        pw.println(line);
18259                    }
18260                } catch (IOException ignored) {
18261                } finally {
18262                    IoUtils.closeQuietly(in);
18263                }
18264            }
18265        }
18266    }
18267
18268    private String dumpDomainString(String packageName) {
18269        List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName)
18270                .getList();
18271        List<IntentFilter> filters = getAllIntentFilters(packageName).getList();
18272
18273        ArraySet<String> result = new ArraySet<>();
18274        if (iviList.size() > 0) {
18275            for (IntentFilterVerificationInfo ivi : iviList) {
18276                for (String host : ivi.getDomains()) {
18277                    result.add(host);
18278                }
18279            }
18280        }
18281        if (filters != null && filters.size() > 0) {
18282            for (IntentFilter filter : filters) {
18283                if (filter.hasCategory(Intent.CATEGORY_BROWSABLE)
18284                        && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
18285                                filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) {
18286                    result.addAll(filter.getHostsList());
18287                }
18288            }
18289        }
18290
18291        StringBuilder sb = new StringBuilder(result.size() * 16);
18292        for (String domain : result) {
18293            if (sb.length() > 0) sb.append(" ");
18294            sb.append(domain);
18295        }
18296        return sb.toString();
18297    }
18298
18299    // ------- apps on sdcard specific code -------
18300    static final boolean DEBUG_SD_INSTALL = false;
18301
18302    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
18303
18304    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
18305
18306    private boolean mMediaMounted = false;
18307
18308    static String getEncryptKey() {
18309        try {
18310            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
18311                    SD_ENCRYPTION_KEYSTORE_NAME);
18312            if (sdEncKey == null) {
18313                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
18314                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
18315                if (sdEncKey == null) {
18316                    Slog.e(TAG, "Failed to create encryption keys");
18317                    return null;
18318                }
18319            }
18320            return sdEncKey;
18321        } catch (NoSuchAlgorithmException nsae) {
18322            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
18323            return null;
18324        } catch (IOException ioe) {
18325            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
18326            return null;
18327        }
18328    }
18329
18330    /*
18331     * Update media status on PackageManager.
18332     */
18333    @Override
18334    public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
18335        int callingUid = Binder.getCallingUid();
18336        if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
18337            throw new SecurityException("Media status can only be updated by the system");
18338        }
18339        // reader; this apparently protects mMediaMounted, but should probably
18340        // be a different lock in that case.
18341        synchronized (mPackages) {
18342            Log.i(TAG, "Updating external media status from "
18343                    + (mMediaMounted ? "mounted" : "unmounted") + " to "
18344                    + (mediaStatus ? "mounted" : "unmounted"));
18345            if (DEBUG_SD_INSTALL)
18346                Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
18347                        + ", mMediaMounted=" + mMediaMounted);
18348            if (mediaStatus == mMediaMounted) {
18349                final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
18350                        : 0, -1);
18351                mHandler.sendMessage(msg);
18352                return;
18353            }
18354            mMediaMounted = mediaStatus;
18355        }
18356        // Queue up an async operation since the package installation may take a
18357        // little while.
18358        mHandler.post(new Runnable() {
18359            public void run() {
18360                updateExternalMediaStatusInner(mediaStatus, reportStatus, true);
18361            }
18362        });
18363    }
18364
18365    /**
18366     * Called by MountService when the initial ASECs to scan are available.
18367     * Should block until all the ASEC containers are finished being scanned.
18368     */
18369    public void scanAvailableAsecs() {
18370        updateExternalMediaStatusInner(true, false, false);
18371    }
18372
18373    /*
18374     * Collect information of applications on external media, map them against
18375     * existing containers and update information based on current mount status.
18376     * Please note that we always have to report status if reportStatus has been
18377     * set to true especially when unloading packages.
18378     */
18379    private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus,
18380            boolean externalStorage) {
18381        ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>();
18382        int[] uidArr = EmptyArray.INT;
18383
18384        final String[] list = PackageHelper.getSecureContainerList();
18385        if (ArrayUtils.isEmpty(list)) {
18386            Log.i(TAG, "No secure containers found");
18387        } else {
18388            // Process list of secure containers and categorize them
18389            // as active or stale based on their package internal state.
18390
18391            // reader
18392            synchronized (mPackages) {
18393                for (String cid : list) {
18394                    // Leave stages untouched for now; installer service owns them
18395                    if (PackageInstallerService.isStageName(cid)) continue;
18396
18397                    if (DEBUG_SD_INSTALL)
18398                        Log.i(TAG, "Processing container " + cid);
18399                    String pkgName = getAsecPackageName(cid);
18400                    if (pkgName == null) {
18401                        Slog.i(TAG, "Found stale container " + cid + " with no package name");
18402                        continue;
18403                    }
18404                    if (DEBUG_SD_INSTALL)
18405                        Log.i(TAG, "Looking for pkg : " + pkgName);
18406
18407                    final PackageSetting ps = mSettings.mPackages.get(pkgName);
18408                    if (ps == null) {
18409                        Slog.i(TAG, "Found stale container " + cid + " with no matching settings");
18410                        continue;
18411                    }
18412
18413                    /*
18414                     * Skip packages that are not external if we're unmounting
18415                     * external storage.
18416                     */
18417                    if (externalStorage && !isMounted && !isExternal(ps)) {
18418                        continue;
18419                    }
18420
18421                    final AsecInstallArgs args = new AsecInstallArgs(cid,
18422                            getAppDexInstructionSets(ps), ps.isForwardLocked());
18423                    // The package status is changed only if the code path
18424                    // matches between settings and the container id.
18425                    if (ps.codePathString != null
18426                            && ps.codePathString.startsWith(args.getCodePath())) {
18427                        if (DEBUG_SD_INSTALL) {
18428                            Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
18429                                    + " at code path: " + ps.codePathString);
18430                        }
18431
18432                        // We do have a valid package installed on sdcard
18433                        processCids.put(args, ps.codePathString);
18434                        final int uid = ps.appId;
18435                        if (uid != -1) {
18436                            uidArr = ArrayUtils.appendInt(uidArr, uid);
18437                        }
18438                    } else {
18439                        Slog.i(TAG, "Found stale container " + cid + ": expected codePath="
18440                                + ps.codePathString);
18441                    }
18442                }
18443            }
18444
18445            Arrays.sort(uidArr);
18446        }
18447
18448        // Process packages with valid entries.
18449        if (isMounted) {
18450            if (DEBUG_SD_INSTALL)
18451                Log.i(TAG, "Loading packages");
18452            loadMediaPackages(processCids, uidArr, externalStorage);
18453            startCleaningPackages();
18454            mInstallerService.onSecureContainersAvailable();
18455        } else {
18456            if (DEBUG_SD_INSTALL)
18457                Log.i(TAG, "Unloading packages");
18458            unloadMediaPackages(processCids, uidArr, reportStatus);
18459        }
18460    }
18461
18462    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
18463            ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) {
18464        final int size = infos.size();
18465        final String[] packageNames = new String[size];
18466        final int[] packageUids = new int[size];
18467        for (int i = 0; i < size; i++) {
18468            final ApplicationInfo info = infos.get(i);
18469            packageNames[i] = info.packageName;
18470            packageUids[i] = info.uid;
18471        }
18472        sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids,
18473                finishedReceiver);
18474    }
18475
18476    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
18477            ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
18478        sendResourcesChangedBroadcast(mediaStatus, replacing,
18479                pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver);
18480    }
18481
18482    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
18483            String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
18484        int size = pkgList.length;
18485        if (size > 0) {
18486            // Send broadcasts here
18487            Bundle extras = new Bundle();
18488            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
18489            if (uidArr != null) {
18490                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
18491            }
18492            if (replacing) {
18493                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
18494            }
18495            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
18496                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
18497            sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null);
18498        }
18499    }
18500
18501   /*
18502     * Look at potentially valid container ids from processCids If package
18503     * information doesn't match the one on record or package scanning fails,
18504     * the cid is added to list of removeCids. We currently don't delete stale
18505     * containers.
18506     */
18507    private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr,
18508            boolean externalStorage) {
18509        ArrayList<String> pkgList = new ArrayList<String>();
18510        Set<AsecInstallArgs> keys = processCids.keySet();
18511
18512        for (AsecInstallArgs args : keys) {
18513            String codePath = processCids.get(args);
18514            if (DEBUG_SD_INSTALL)
18515                Log.i(TAG, "Loading container : " + args.cid);
18516            int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
18517            try {
18518                // Make sure there are no container errors first.
18519                if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
18520                    Slog.e(TAG, "Failed to mount cid : " + args.cid
18521                            + " when installing from sdcard");
18522                    continue;
18523                }
18524                // Check code path here.
18525                if (codePath == null || !codePath.startsWith(args.getCodePath())) {
18526                    Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
18527                            + " does not match one in settings " + codePath);
18528                    continue;
18529                }
18530                // Parse package
18531                int parseFlags = mDefParseFlags;
18532                if (args.isExternalAsec()) {
18533                    parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE;
18534                }
18535                if (args.isFwdLocked()) {
18536                    parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
18537                }
18538
18539                synchronized (mInstallLock) {
18540                    PackageParser.Package pkg = null;
18541                    try {
18542                        // Sadly we don't know the package name yet to freeze it
18543                        pkg = scanPackageTracedLI(new File(codePath), parseFlags,
18544                                SCAN_IGNORE_FROZEN, 0, null);
18545                    } catch (PackageManagerException e) {
18546                        Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage());
18547                    }
18548                    // Scan the package
18549                    if (pkg != null) {
18550                        /*
18551                         * TODO why is the lock being held? doPostInstall is
18552                         * called in other places without the lock. This needs
18553                         * to be straightened out.
18554                         */
18555                        // writer
18556                        synchronized (mPackages) {
18557                            retCode = PackageManager.INSTALL_SUCCEEDED;
18558                            pkgList.add(pkg.packageName);
18559                            // Post process args
18560                            args.doPostInstall(PackageManager.INSTALL_SUCCEEDED,
18561                                    pkg.applicationInfo.uid);
18562                        }
18563                    } else {
18564                        Slog.i(TAG, "Failed to install pkg from  " + codePath + " from sdcard");
18565                    }
18566                }
18567
18568            } finally {
18569                if (retCode != PackageManager.INSTALL_SUCCEEDED) {
18570                    Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode);
18571                }
18572            }
18573        }
18574        // writer
18575        synchronized (mPackages) {
18576            // If the platform SDK has changed since the last time we booted,
18577            // we need to re-grant app permission to catch any new ones that
18578            // appear. This is really a hack, and means that apps can in some
18579            // cases get permissions that the user didn't initially explicitly
18580            // allow... it would be nice to have some better way to handle
18581            // this situation.
18582            final VersionInfo ver = externalStorage ? mSettings.getExternalVersion()
18583                    : mSettings.getInternalVersion();
18584            final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL
18585                    : StorageManager.UUID_PRIVATE_INTERNAL;
18586
18587            int updateFlags = UPDATE_PERMISSIONS_ALL;
18588            if (ver.sdkVersion != mSdkVersion) {
18589                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
18590                        + mSdkVersion + "; regranting permissions for external");
18591                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
18592            }
18593            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
18594
18595            // Yay, everything is now upgraded
18596            ver.forceCurrent();
18597
18598            // can downgrade to reader
18599            // Persist settings
18600            mSettings.writeLPr();
18601        }
18602        // Send a broadcast to let everyone know we are done processing
18603        if (pkgList.size() > 0) {
18604            sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
18605        }
18606    }
18607
18608   /*
18609     * Utility method to unload a list of specified containers
18610     */
18611    private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) {
18612        // Just unmount all valid containers.
18613        for (AsecInstallArgs arg : cidArgs) {
18614            synchronized (mInstallLock) {
18615                arg.doPostDeleteLI(false);
18616           }
18617       }
18618   }
18619
18620    /*
18621     * Unload packages mounted on external media. This involves deleting package
18622     * data from internal structures, sending broadcasts about disabled packages,
18623     * gc'ing to free up references, unmounting all secure containers
18624     * corresponding to packages on external media, and posting a
18625     * UPDATED_MEDIA_STATUS message if status has been requested. Please note
18626     * that we always have to post this message if status has been requested no
18627     * matter what.
18628     */
18629    private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[],
18630            final boolean reportStatus) {
18631        if (DEBUG_SD_INSTALL)
18632            Log.i(TAG, "unloading media packages");
18633        ArrayList<String> pkgList = new ArrayList<String>();
18634        ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>();
18635        final Set<AsecInstallArgs> keys = processCids.keySet();
18636        for (AsecInstallArgs args : keys) {
18637            String pkgName = args.getPackageName();
18638            if (DEBUG_SD_INSTALL)
18639                Log.i(TAG, "Trying to unload pkg : " + pkgName);
18640            // Delete package internally
18641            PackageRemovedInfo outInfo = new PackageRemovedInfo();
18642            synchronized (mInstallLock) {
18643                final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
18644                final boolean res;
18645                try (PackageFreezer freezer = freezePackageForDelete(pkgName, deleteFlags,
18646                        "unloadMediaPackages")) {
18647                    res = deletePackageLIF(pkgName, null, false, null, deleteFlags, outInfo, false,
18648                            null);
18649                }
18650                if (res) {
18651                    pkgList.add(pkgName);
18652                } else {
18653                    Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
18654                    failedList.add(args);
18655                }
18656            }
18657        }
18658
18659        // reader
18660        synchronized (mPackages) {
18661            // We didn't update the settings after removing each package;
18662            // write them now for all packages.
18663            mSettings.writeLPr();
18664        }
18665
18666        // We have to absolutely send UPDATED_MEDIA_STATUS only
18667        // after confirming that all the receivers processed the ordered
18668        // broadcast when packages get disabled, force a gc to clean things up.
18669        // and unload all the containers.
18670        if (pkgList.size() > 0) {
18671            sendResourcesChangedBroadcast(false, false, pkgList, uidArr,
18672                    new IIntentReceiver.Stub() {
18673                public void performReceive(Intent intent, int resultCode, String data,
18674                        Bundle extras, boolean ordered, boolean sticky,
18675                        int sendingUser) throws RemoteException {
18676                    Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
18677                            reportStatus ? 1 : 0, 1, keys);
18678                    mHandler.sendMessage(msg);
18679                }
18680            });
18681        } else {
18682            Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
18683                    keys);
18684            mHandler.sendMessage(msg);
18685        }
18686    }
18687
18688    private void loadPrivatePackages(final VolumeInfo vol) {
18689        mHandler.post(new Runnable() {
18690            @Override
18691            public void run() {
18692                loadPrivatePackagesInner(vol);
18693            }
18694        });
18695    }
18696
18697    private void loadPrivatePackagesInner(VolumeInfo vol) {
18698        final String volumeUuid = vol.fsUuid;
18699        if (TextUtils.isEmpty(volumeUuid)) {
18700            Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring");
18701            return;
18702        }
18703
18704        final ArrayList<PackageFreezer> freezers = new ArrayList<>();
18705        final ArrayList<ApplicationInfo> loaded = new ArrayList<>();
18706        final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE;
18707
18708        final VersionInfo ver;
18709        final List<PackageSetting> packages;
18710        synchronized (mPackages) {
18711            ver = mSettings.findOrCreateVersion(volumeUuid);
18712            packages = mSettings.getVolumePackagesLPr(volumeUuid);
18713        }
18714
18715        for (PackageSetting ps : packages) {
18716            freezers.add(freezePackage(ps.name, "loadPrivatePackagesInner"));
18717            synchronized (mInstallLock) {
18718                final PackageParser.Package pkg;
18719                try {
18720                    pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null);
18721                    loaded.add(pkg.applicationInfo);
18722
18723                } catch (PackageManagerException e) {
18724                    Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage());
18725                }
18726
18727                if (!Build.FINGERPRINT.equals(ver.fingerprint)) {
18728                    clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
18729                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
18730                                    | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
18731                }
18732            }
18733        }
18734
18735        // Reconcile app data for all started/unlocked users
18736        final StorageManager sm = mContext.getSystemService(StorageManager.class);
18737        final UserManager um = mContext.getSystemService(UserManager.class);
18738        for (UserInfo user : um.getUsers()) {
18739            final int flags;
18740            if (um.isUserUnlocked(user.id)) {
18741                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
18742            } else if (um.isUserRunning(user.id)) {
18743                flags = StorageManager.FLAG_STORAGE_DE;
18744            } else {
18745                continue;
18746            }
18747
18748            sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags);
18749            synchronized (mInstallLock) {
18750                reconcileAppsDataLI(volumeUuid, user.id, flags);
18751            }
18752        }
18753
18754        synchronized (mPackages) {
18755            int updateFlags = UPDATE_PERMISSIONS_ALL;
18756            if (ver.sdkVersion != mSdkVersion) {
18757                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
18758                        + mSdkVersion + "; regranting permissions for " + volumeUuid);
18759                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
18760            }
18761            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
18762
18763            // Yay, everything is now upgraded
18764            ver.forceCurrent();
18765
18766            mSettings.writeLPr();
18767        }
18768
18769        for (PackageFreezer freezer : freezers) {
18770            freezer.close();
18771        }
18772
18773        if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded);
18774        sendResourcesChangedBroadcast(true, false, loaded, null);
18775    }
18776
18777    private void unloadPrivatePackages(final VolumeInfo vol) {
18778        mHandler.post(new Runnable() {
18779            @Override
18780            public void run() {
18781                unloadPrivatePackagesInner(vol);
18782            }
18783        });
18784    }
18785
18786    private void unloadPrivatePackagesInner(VolumeInfo vol) {
18787        final String volumeUuid = vol.fsUuid;
18788        if (TextUtils.isEmpty(volumeUuid)) {
18789            Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring");
18790            return;
18791        }
18792
18793        final ArrayList<ApplicationInfo> unloaded = new ArrayList<>();
18794        synchronized (mInstallLock) {
18795        synchronized (mPackages) {
18796            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid);
18797            for (PackageSetting ps : packages) {
18798                if (ps.pkg == null) continue;
18799
18800                final ApplicationInfo info = ps.pkg.applicationInfo;
18801                final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
18802                final PackageRemovedInfo outInfo = new PackageRemovedInfo();
18803
18804                try (PackageFreezer freezer = freezePackageForDelete(ps.name, deleteFlags,
18805                        "unloadPrivatePackagesInner")) {
18806                    if (deletePackageLIF(ps.name, null, false, null, deleteFlags, outInfo,
18807                            false, null)) {
18808                        unloaded.add(info);
18809                    } else {
18810                        Slog.w(TAG, "Failed to unload " + ps.codePath);
18811                    }
18812                }
18813            }
18814
18815            mSettings.writeLPr();
18816        }
18817        }
18818
18819        if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded);
18820        sendResourcesChangedBroadcast(false, false, unloaded, null);
18821    }
18822
18823    /**
18824     * Prepare storage areas for given user on all mounted devices.
18825     */
18826    void prepareUserData(int userId, int userSerial, int flags) {
18827        synchronized (mInstallLock) {
18828            final StorageManager storage = mContext.getSystemService(StorageManager.class);
18829            for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
18830                final String volumeUuid = vol.getFsUuid();
18831                prepareUserDataLI(volumeUuid, userId, userSerial, flags, true);
18832            }
18833        }
18834    }
18835
18836    private void prepareUserDataLI(String volumeUuid, int userId, int userSerial, int flags,
18837            boolean allowRecover) {
18838        // Prepare storage and verify that serial numbers are consistent; if
18839        // there's a mismatch we need to destroy to avoid leaking data
18840        final StorageManager storage = mContext.getSystemService(StorageManager.class);
18841        try {
18842            storage.prepareUserStorage(volumeUuid, userId, userSerial, flags);
18843
18844            if ((flags & StorageManager.FLAG_STORAGE_DE) != 0 && !mOnlyCore) {
18845                UserManagerService.enforceSerialNumber(
18846                        Environment.getDataUserDeDirectory(volumeUuid, userId), userSerial);
18847            }
18848            if ((flags & StorageManager.FLAG_STORAGE_CE) != 0 && !mOnlyCore) {
18849                UserManagerService.enforceSerialNumber(
18850                        Environment.getDataUserCeDirectory(volumeUuid, userId), userSerial);
18851            }
18852
18853            synchronized (mInstallLock) {
18854                mInstaller.createUserData(volumeUuid, userId, userSerial, flags);
18855            }
18856        } catch (Exception e) {
18857            logCriticalInfo(Log.WARN, "Destroying user " + userId + " on volume " + volumeUuid
18858                    + " because we failed to prepare: " + e);
18859            destroyUserDataLI(volumeUuid, userId,
18860                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
18861
18862            if (allowRecover) {
18863                // Try one last time; if we fail again we're really in trouble
18864                prepareUserDataLI(volumeUuid, userId, userSerial, flags, false);
18865            }
18866        }
18867    }
18868
18869    /**
18870     * Destroy storage areas for given user on all mounted devices.
18871     */
18872    void destroyUserData(int userId, int flags) {
18873        synchronized (mInstallLock) {
18874            final StorageManager storage = mContext.getSystemService(StorageManager.class);
18875            for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
18876                final String volumeUuid = vol.getFsUuid();
18877                destroyUserDataLI(volumeUuid, userId, flags);
18878            }
18879        }
18880    }
18881
18882    private void destroyUserDataLI(String volumeUuid, int userId, int flags) {
18883        final StorageManager storage = mContext.getSystemService(StorageManager.class);
18884        try {
18885            // Clean up app data, profile data, and media data
18886            mInstaller.destroyUserData(volumeUuid, userId, flags);
18887
18888            // Clean up system data
18889            if (Objects.equals(volumeUuid, StorageManager.UUID_PRIVATE_INTERNAL)) {
18890                if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) {
18891                    FileUtils.deleteContentsAndDir(Environment.getUserSystemDirectory(userId));
18892                    FileUtils.deleteContentsAndDir(Environment.getDataSystemDeDirectory(userId));
18893                }
18894                if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
18895                    FileUtils.deleteContentsAndDir(Environment.getDataSystemCeDirectory(userId));
18896                }
18897            }
18898
18899            // Data with special labels is now gone, so finish the job
18900            storage.destroyUserStorage(volumeUuid, userId, flags);
18901
18902        } catch (Exception e) {
18903            logCriticalInfo(Log.WARN,
18904                    "Failed to destroy user " + userId + " on volume " + volumeUuid + ": " + e);
18905        }
18906    }
18907
18908    /**
18909     * Examine all users present on given mounted volume, and destroy data
18910     * belonging to users that are no longer valid, or whose user ID has been
18911     * recycled.
18912     */
18913    private void reconcileUsers(String volumeUuid) {
18914        final List<File> files = new ArrayList<>();
18915        Collections.addAll(files, FileUtils
18916                .listFilesOrEmpty(Environment.getDataUserDeDirectory(volumeUuid)));
18917        Collections.addAll(files, FileUtils
18918                .listFilesOrEmpty(Environment.getDataUserCeDirectory(volumeUuid)));
18919        for (File file : files) {
18920            if (!file.isDirectory()) continue;
18921
18922            final int userId;
18923            final UserInfo info;
18924            try {
18925                userId = Integer.parseInt(file.getName());
18926                info = sUserManager.getUserInfo(userId);
18927            } catch (NumberFormatException e) {
18928                Slog.w(TAG, "Invalid user directory " + file);
18929                continue;
18930            }
18931
18932            boolean destroyUser = false;
18933            if (info == null) {
18934                logCriticalInfo(Log.WARN, "Destroying user directory " + file
18935                        + " because no matching user was found");
18936                destroyUser = true;
18937            } else if (!mOnlyCore) {
18938                try {
18939                    UserManagerService.enforceSerialNumber(file, info.serialNumber);
18940                } catch (IOException e) {
18941                    logCriticalInfo(Log.WARN, "Destroying user directory " + file
18942                            + " because we failed to enforce serial number: " + e);
18943                    destroyUser = true;
18944                }
18945            }
18946
18947            if (destroyUser) {
18948                synchronized (mInstallLock) {
18949                    destroyUserDataLI(volumeUuid, userId,
18950                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
18951                }
18952            }
18953        }
18954    }
18955
18956    private void assertPackageKnown(String volumeUuid, String packageName)
18957            throws PackageManagerException {
18958        synchronized (mPackages) {
18959            final PackageSetting ps = mSettings.mPackages.get(packageName);
18960            if (ps == null) {
18961                throw new PackageManagerException("Package " + packageName + " is unknown");
18962            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
18963                throw new PackageManagerException(
18964                        "Package " + packageName + " found on unknown volume " + volumeUuid
18965                                + "; expected volume " + ps.volumeUuid);
18966            }
18967        }
18968    }
18969
18970    private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId)
18971            throws PackageManagerException {
18972        synchronized (mPackages) {
18973            final PackageSetting ps = mSettings.mPackages.get(packageName);
18974            if (ps == null) {
18975                throw new PackageManagerException("Package " + packageName + " is unknown");
18976            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
18977                throw new PackageManagerException(
18978                        "Package " + packageName + " found on unknown volume " + volumeUuid
18979                                + "; expected volume " + ps.volumeUuid);
18980            } else if (!ps.getInstalled(userId)) {
18981                throw new PackageManagerException(
18982                        "Package " + packageName + " not installed for user " + userId);
18983            }
18984        }
18985    }
18986
18987    /**
18988     * Examine all apps present on given mounted volume, and destroy apps that
18989     * aren't expected, either due to uninstallation or reinstallation on
18990     * another volume.
18991     */
18992    private void reconcileApps(String volumeUuid) {
18993        final File[] files = FileUtils
18994                .listFilesOrEmpty(Environment.getDataAppDirectory(volumeUuid));
18995        for (File file : files) {
18996            final boolean isPackage = (isApkFile(file) || file.isDirectory())
18997                    && !PackageInstallerService.isStageName(file.getName());
18998            if (!isPackage) {
18999                // Ignore entries which are not packages
19000                continue;
19001            }
19002
19003            try {
19004                final PackageLite pkg = PackageParser.parsePackageLite(file,
19005                        PackageParser.PARSE_MUST_BE_APK);
19006                assertPackageKnown(volumeUuid, pkg.packageName);
19007
19008            } catch (PackageParserException | PackageManagerException e) {
19009                logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
19010                synchronized (mInstallLock) {
19011                    removeCodePathLI(file);
19012                }
19013            }
19014        }
19015    }
19016
19017    /**
19018     * Reconcile all app data for the given user.
19019     * <p>
19020     * Verifies that directories exist and that ownership and labeling is
19021     * correct for all installed apps on all mounted volumes.
19022     */
19023    void reconcileAppsData(int userId, int flags) {
19024        final StorageManager storage = mContext.getSystemService(StorageManager.class);
19025        for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
19026            final String volumeUuid = vol.getFsUuid();
19027            synchronized (mInstallLock) {
19028                reconcileAppsDataLI(volumeUuid, userId, flags);
19029            }
19030        }
19031    }
19032
19033    /**
19034     * Reconcile all app data on given mounted volume.
19035     * <p>
19036     * Destroys app data that isn't expected, either due to uninstallation or
19037     * reinstallation on another volume.
19038     * <p>
19039     * Verifies that directories exist and that ownership and labeling is
19040     * correct for all installed apps.
19041     */
19042    private void reconcileAppsDataLI(String volumeUuid, int userId, int flags) {
19043        Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x"
19044                + Integer.toHexString(flags));
19045
19046        final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId);
19047        final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId);
19048
19049        boolean restoreconNeeded = false;
19050
19051        // First look for stale data that doesn't belong, and check if things
19052        // have changed since we did our last restorecon
19053        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
19054            if (!isUserKeyUnlocked(userId)) {
19055                throw new RuntimeException(
19056                        "Yikes, someone asked us to reconcile CE storage while " + userId
19057                                + " was still locked; this would have caused massive data loss!");
19058            }
19059
19060            restoreconNeeded |= SELinuxMMAC.isRestoreconNeeded(ceDir);
19061
19062            final File[] files = FileUtils.listFilesOrEmpty(ceDir);
19063            for (File file : files) {
19064                final String packageName = file.getName();
19065                try {
19066                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
19067                } catch (PackageManagerException e) {
19068                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
19069                    try {
19070                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
19071                                StorageManager.FLAG_STORAGE_CE, 0);
19072                    } catch (InstallerException e2) {
19073                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
19074                    }
19075                }
19076            }
19077        }
19078        if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) {
19079            restoreconNeeded |= SELinuxMMAC.isRestoreconNeeded(deDir);
19080
19081            final File[] files = FileUtils.listFilesOrEmpty(deDir);
19082            for (File file : files) {
19083                final String packageName = file.getName();
19084                try {
19085                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
19086                } catch (PackageManagerException e) {
19087                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
19088                    try {
19089                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
19090                                StorageManager.FLAG_STORAGE_DE, 0);
19091                    } catch (InstallerException e2) {
19092                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
19093                    }
19094                }
19095            }
19096        }
19097
19098        // Ensure that data directories are ready to roll for all packages
19099        // installed for this volume and user
19100        final List<PackageSetting> packages;
19101        synchronized (mPackages) {
19102            packages = mSettings.getVolumePackagesLPr(volumeUuid);
19103        }
19104        int preparedCount = 0;
19105        for (PackageSetting ps : packages) {
19106            final String packageName = ps.name;
19107            if (ps.pkg == null) {
19108                Slog.w(TAG, "Odd, missing scanned package " + packageName);
19109                // TODO: might be due to legacy ASEC apps; we should circle back
19110                // and reconcile again once they're scanned
19111                continue;
19112            }
19113
19114            if (ps.getInstalled(userId)) {
19115                prepareAppDataLIF(ps.pkg, userId, flags, restoreconNeeded);
19116
19117                if (maybeMigrateAppDataLIF(ps.pkg, userId)) {
19118                    // We may have just shuffled around app data directories, so
19119                    // prepare them one more time
19120                    prepareAppDataLIF(ps.pkg, userId, flags, restoreconNeeded);
19121                }
19122
19123                preparedCount++;
19124            }
19125        }
19126
19127        if (restoreconNeeded) {
19128            if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
19129                SELinuxMMAC.setRestoreconDone(ceDir);
19130            }
19131            if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) {
19132                SELinuxMMAC.setRestoreconDone(deDir);
19133            }
19134        }
19135
19136        Slog.v(TAG, "reconcileAppsData finished " + preparedCount
19137                + " packages; restoreconNeeded was " + restoreconNeeded);
19138    }
19139
19140    /**
19141     * Prepare app data for the given app just after it was installed or
19142     * upgraded. This method carefully only touches users that it's installed
19143     * for, and it forces a restorecon to handle any seinfo changes.
19144     * <p>
19145     * Verifies that directories exist and that ownership and labeling is
19146     * correct for all installed apps. If there is an ownership mismatch, it
19147     * will try recovering system apps by wiping data; third-party app data is
19148     * left intact.
19149     * <p>
19150     * <em>Note: To avoid a deadlock, do not call this method with {@code mPackages} lock held</em>
19151     */
19152    private void prepareAppDataAfterInstallLIF(PackageParser.Package pkg) {
19153        final PackageSetting ps;
19154        synchronized (mPackages) {
19155            ps = mSettings.mPackages.get(pkg.packageName);
19156            mSettings.writeKernelMappingLPr(ps);
19157        }
19158
19159        final UserManager um = mContext.getSystemService(UserManager.class);
19160        for (UserInfo user : um.getUsers()) {
19161            final int flags;
19162            if (um.isUserUnlocked(user.id)) {
19163                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
19164            } else if (um.isUserRunning(user.id)) {
19165                flags = StorageManager.FLAG_STORAGE_DE;
19166            } else {
19167                continue;
19168            }
19169
19170            if (ps.getInstalled(user.id)) {
19171                // Whenever an app changes, force a restorecon of its data
19172                // TODO: when user data is locked, mark that we're still dirty
19173                prepareAppDataLIF(pkg, user.id, flags, true);
19174            }
19175        }
19176    }
19177
19178    /**
19179     * Prepare app data for the given app.
19180     * <p>
19181     * Verifies that directories exist and that ownership and labeling is
19182     * correct for all installed apps. If there is an ownership mismatch, this
19183     * will try recovering system apps by wiping data; third-party app data is
19184     * left intact.
19185     */
19186    private void prepareAppDataLIF(PackageParser.Package pkg, int userId, int flags,
19187            boolean restoreconNeeded) {
19188        if (pkg == null) {
19189            Slog.wtf(TAG, "Package was null!", new Throwable());
19190            return;
19191        }
19192        prepareAppDataLeafLIF(pkg, userId, flags, restoreconNeeded);
19193        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
19194        for (int i = 0; i < childCount; i++) {
19195            prepareAppDataLeafLIF(pkg.childPackages.get(i), userId, flags, restoreconNeeded);
19196        }
19197    }
19198
19199    private void prepareAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags,
19200            boolean restoreconNeeded) {
19201        if (DEBUG_APP_DATA) {
19202            Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x"
19203                    + Integer.toHexString(flags) + (restoreconNeeded ? " restoreconNeeded" : ""));
19204        }
19205
19206        final String volumeUuid = pkg.volumeUuid;
19207        final String packageName = pkg.packageName;
19208        final ApplicationInfo app = pkg.applicationInfo;
19209        final int appId = UserHandle.getAppId(app.uid);
19210
19211        Preconditions.checkNotNull(app.seinfo);
19212
19213        try {
19214            mInstaller.createAppData(volumeUuid, packageName, userId, flags,
19215                    appId, app.seinfo, app.targetSdkVersion);
19216        } catch (InstallerException e) {
19217            if (app.isSystemApp()) {
19218                logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName
19219                        + ", but trying to recover: " + e);
19220                destroyAppDataLeafLIF(pkg, userId, flags);
19221                try {
19222                    mInstaller.createAppData(volumeUuid, packageName, userId, flags,
19223                            appId, app.seinfo, app.targetSdkVersion);
19224                    logCriticalInfo(Log.DEBUG, "Recovery succeeded!");
19225                } catch (InstallerException e2) {
19226                    logCriticalInfo(Log.DEBUG, "Recovery failed!");
19227                }
19228            } else {
19229                Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e);
19230            }
19231        }
19232
19233        if (restoreconNeeded) {
19234            try {
19235                mInstaller.restoreconAppData(volumeUuid, packageName, userId, flags, appId,
19236                        app.seinfo);
19237            } catch (InstallerException e) {
19238                Slog.e(TAG, "Failed to restorecon for " + packageName + ": " + e);
19239            }
19240        }
19241
19242        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
19243            try {
19244                // CE storage is unlocked right now, so read out the inode and
19245                // remember for use later when it's locked
19246                // TODO: mark this structure as dirty so we persist it!
19247                final long ceDataInode = mInstaller.getAppDataInode(volumeUuid, packageName, userId,
19248                        StorageManager.FLAG_STORAGE_CE);
19249                synchronized (mPackages) {
19250                    final PackageSetting ps = mSettings.mPackages.get(packageName);
19251                    if (ps != null) {
19252                        ps.setCeDataInode(ceDataInode, userId);
19253                    }
19254                }
19255            } catch (InstallerException e) {
19256                Slog.e(TAG, "Failed to find inode for " + packageName + ": " + e);
19257            }
19258        }
19259
19260        prepareAppDataContentsLeafLIF(pkg, userId, flags);
19261    }
19262
19263    private void prepareAppDataContentsLIF(PackageParser.Package pkg, int userId, int flags) {
19264        if (pkg == null) {
19265            Slog.wtf(TAG, "Package was null!", new Throwable());
19266            return;
19267        }
19268        prepareAppDataContentsLeafLIF(pkg, userId, flags);
19269        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
19270        for (int i = 0; i < childCount; i++) {
19271            prepareAppDataContentsLeafLIF(pkg.childPackages.get(i), userId, flags);
19272        }
19273    }
19274
19275    private void prepareAppDataContentsLeafLIF(PackageParser.Package pkg, int userId, int flags) {
19276        final String volumeUuid = pkg.volumeUuid;
19277        final String packageName = pkg.packageName;
19278        final ApplicationInfo app = pkg.applicationInfo;
19279
19280        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
19281            // Create a native library symlink only if we have native libraries
19282            // and if the native libraries are 32 bit libraries. We do not provide
19283            // this symlink for 64 bit libraries.
19284            if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) {
19285                final String nativeLibPath = app.nativeLibraryDir;
19286                try {
19287                    mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName,
19288                            nativeLibPath, userId);
19289                } catch (InstallerException e) {
19290                    Slog.e(TAG, "Failed to link native for " + packageName + ": " + e);
19291                }
19292            }
19293        }
19294    }
19295
19296    /**
19297     * For system apps on non-FBE devices, this method migrates any existing
19298     * CE/DE data to match the {@code defaultToDeviceProtectedStorage} flag
19299     * requested by the app.
19300     */
19301    private boolean maybeMigrateAppDataLIF(PackageParser.Package pkg, int userId) {
19302        if (pkg.isSystemApp() && !StorageManager.isFileEncryptedNativeOrEmulated()
19303                && PackageManager.APPLY_DEFAULT_TO_DEVICE_PROTECTED_STORAGE) {
19304            final int storageTarget = pkg.applicationInfo.isDefaultToDeviceProtectedStorage()
19305                    ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE;
19306            try {
19307                mInstaller.migrateAppData(pkg.volumeUuid, pkg.packageName, userId,
19308                        storageTarget);
19309            } catch (InstallerException e) {
19310                logCriticalInfo(Log.WARN,
19311                        "Failed to migrate " + pkg.packageName + ": " + e.getMessage());
19312            }
19313            return true;
19314        } else {
19315            return false;
19316        }
19317    }
19318
19319    public PackageFreezer freezePackage(String packageName, String killReason) {
19320        return new PackageFreezer(packageName, killReason);
19321    }
19322
19323    public PackageFreezer freezePackageForInstall(String packageName, int installFlags,
19324            String killReason) {
19325        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
19326            return new PackageFreezer();
19327        } else {
19328            return freezePackage(packageName, killReason);
19329        }
19330    }
19331
19332    public PackageFreezer freezePackageForDelete(String packageName, int deleteFlags,
19333            String killReason) {
19334        if ((deleteFlags & PackageManager.DELETE_DONT_KILL_APP) != 0) {
19335            return new PackageFreezer();
19336        } else {
19337            return freezePackage(packageName, killReason);
19338        }
19339    }
19340
19341    /**
19342     * Class that freezes and kills the given package upon creation, and
19343     * unfreezes it upon closing. This is typically used when doing surgery on
19344     * app code/data to prevent the app from running while you're working.
19345     */
19346    private class PackageFreezer implements AutoCloseable {
19347        private final String mPackageName;
19348        private final PackageFreezer[] mChildren;
19349
19350        private final boolean mWeFroze;
19351
19352        private final AtomicBoolean mClosed = new AtomicBoolean();
19353        private final CloseGuard mCloseGuard = CloseGuard.get();
19354
19355        /**
19356         * Create and return a stub freezer that doesn't actually do anything,
19357         * typically used when someone requested
19358         * {@link PackageManager#INSTALL_DONT_KILL_APP} or
19359         * {@link PackageManager#DELETE_DONT_KILL_APP}.
19360         */
19361        public PackageFreezer() {
19362            mPackageName = null;
19363            mChildren = null;
19364            mWeFroze = false;
19365            mCloseGuard.open("close");
19366        }
19367
19368        public PackageFreezer(String packageName, String killReason) {
19369            synchronized (mPackages) {
19370                mPackageName = packageName;
19371                mWeFroze = mFrozenPackages.add(mPackageName);
19372
19373                final PackageSetting ps = mSettings.mPackages.get(mPackageName);
19374                if (ps != null) {
19375                    killApplication(ps.name, ps.appId, killReason);
19376                }
19377
19378                final PackageParser.Package p = mPackages.get(packageName);
19379                if (p != null && p.childPackages != null) {
19380                    final int N = p.childPackages.size();
19381                    mChildren = new PackageFreezer[N];
19382                    for (int i = 0; i < N; i++) {
19383                        mChildren[i] = new PackageFreezer(p.childPackages.get(i).packageName,
19384                                killReason);
19385                    }
19386                } else {
19387                    mChildren = null;
19388                }
19389            }
19390            mCloseGuard.open("close");
19391        }
19392
19393        @Override
19394        protected void finalize() throws Throwable {
19395            try {
19396                mCloseGuard.warnIfOpen();
19397                close();
19398            } finally {
19399                super.finalize();
19400            }
19401        }
19402
19403        @Override
19404        public void close() {
19405            mCloseGuard.close();
19406            if (mClosed.compareAndSet(false, true)) {
19407                synchronized (mPackages) {
19408                    if (mWeFroze) {
19409                        mFrozenPackages.remove(mPackageName);
19410                    }
19411
19412                    if (mChildren != null) {
19413                        for (PackageFreezer freezer : mChildren) {
19414                            freezer.close();
19415                        }
19416                    }
19417                }
19418            }
19419        }
19420    }
19421
19422    /**
19423     * Verify that given package is currently frozen.
19424     */
19425    private void checkPackageFrozen(String packageName) {
19426        synchronized (mPackages) {
19427            if (!mFrozenPackages.contains(packageName)) {
19428                Slog.wtf(TAG, "Expected " + packageName + " to be frozen!", new Throwable());
19429            }
19430        }
19431    }
19432
19433    @Override
19434    public int movePackage(final String packageName, final String volumeUuid) {
19435        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
19436
19437        final UserHandle user = new UserHandle(UserHandle.getCallingUserId());
19438        final int moveId = mNextMoveId.getAndIncrement();
19439        mHandler.post(new Runnable() {
19440            @Override
19441            public void run() {
19442                try {
19443                    movePackageInternal(packageName, volumeUuid, moveId, user);
19444                } catch (PackageManagerException e) {
19445                    Slog.w(TAG, "Failed to move " + packageName, e);
19446                    mMoveCallbacks.notifyStatusChanged(moveId,
19447                            PackageManager.MOVE_FAILED_INTERNAL_ERROR);
19448                }
19449            }
19450        });
19451        return moveId;
19452    }
19453
19454    private void movePackageInternal(final String packageName, final String volumeUuid,
19455            final int moveId, UserHandle user) throws PackageManagerException {
19456        final StorageManager storage = mContext.getSystemService(StorageManager.class);
19457        final PackageManager pm = mContext.getPackageManager();
19458
19459        final boolean currentAsec;
19460        final String currentVolumeUuid;
19461        final File codeFile;
19462        final String installerPackageName;
19463        final String packageAbiOverride;
19464        final int appId;
19465        final String seinfo;
19466        final String label;
19467        final int targetSdkVersion;
19468        final PackageFreezer freezer;
19469
19470        // reader
19471        synchronized (mPackages) {
19472            final PackageParser.Package pkg = mPackages.get(packageName);
19473            final PackageSetting ps = mSettings.mPackages.get(packageName);
19474            if (pkg == null || ps == null) {
19475                throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package");
19476            }
19477
19478            if (pkg.applicationInfo.isSystemApp()) {
19479                throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE,
19480                        "Cannot move system application");
19481            }
19482
19483            if (pkg.applicationInfo.isExternalAsec()) {
19484                currentAsec = true;
19485                currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL;
19486            } else if (pkg.applicationInfo.isForwardLocked()) {
19487                currentAsec = true;
19488                currentVolumeUuid = "forward_locked";
19489            } else {
19490                currentAsec = false;
19491                currentVolumeUuid = ps.volumeUuid;
19492
19493                final File probe = new File(pkg.codePath);
19494                final File probeOat = new File(probe, "oat");
19495                if (!probe.isDirectory() || !probeOat.isDirectory()) {
19496                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
19497                            "Move only supported for modern cluster style installs");
19498                }
19499            }
19500
19501            if (Objects.equals(currentVolumeUuid, volumeUuid)) {
19502                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
19503                        "Package already moved to " + volumeUuid);
19504            }
19505            if (pkg.applicationInfo.isInternal() && isPackageDeviceAdminOnAnyUser(packageName)) {
19506                throw new PackageManagerException(MOVE_FAILED_DEVICE_ADMIN,
19507                        "Device admin cannot be moved");
19508            }
19509
19510            if (mFrozenPackages.contains(packageName)) {
19511                throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING,
19512                        "Failed to move already frozen package");
19513            }
19514
19515            codeFile = new File(pkg.codePath);
19516            installerPackageName = ps.installerPackageName;
19517            packageAbiOverride = ps.cpuAbiOverrideString;
19518            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
19519            seinfo = pkg.applicationInfo.seinfo;
19520            label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo));
19521            targetSdkVersion = pkg.applicationInfo.targetSdkVersion;
19522            freezer = new PackageFreezer(packageName, "movePackageInternal");
19523        }
19524
19525        final Bundle extras = new Bundle();
19526        extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName);
19527        extras.putString(Intent.EXTRA_TITLE, label);
19528        mMoveCallbacks.notifyCreated(moveId, extras);
19529
19530        int installFlags;
19531        final boolean moveCompleteApp;
19532        final File measurePath;
19533
19534        if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) {
19535            installFlags = INSTALL_INTERNAL;
19536            moveCompleteApp = !currentAsec;
19537            measurePath = Environment.getDataAppDirectory(volumeUuid);
19538        } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) {
19539            installFlags = INSTALL_EXTERNAL;
19540            moveCompleteApp = false;
19541            measurePath = storage.getPrimaryPhysicalVolume().getPath();
19542        } else {
19543            final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid);
19544            if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE
19545                    || !volume.isMountedWritable()) {
19546                freezer.close();
19547                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
19548                        "Move location not mounted private volume");
19549            }
19550
19551            Preconditions.checkState(!currentAsec);
19552
19553            installFlags = INSTALL_INTERNAL;
19554            moveCompleteApp = true;
19555            measurePath = Environment.getDataAppDirectory(volumeUuid);
19556        }
19557
19558        final PackageStats stats = new PackageStats(null, -1);
19559        synchronized (mInstaller) {
19560            if (!getPackageSizeInfoLI(packageName, -1, stats)) {
19561                freezer.close();
19562                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
19563                        "Failed to measure package size");
19564            }
19565        }
19566
19567        if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size "
19568                + stats.dataSize);
19569
19570        final long startFreeBytes = measurePath.getFreeSpace();
19571        final long sizeBytes;
19572        if (moveCompleteApp) {
19573            sizeBytes = stats.codeSize + stats.dataSize;
19574        } else {
19575            sizeBytes = stats.codeSize;
19576        }
19577
19578        if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) {
19579            freezer.close();
19580            throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
19581                    "Not enough free space to move");
19582        }
19583
19584        mMoveCallbacks.notifyStatusChanged(moveId, 10);
19585
19586        final CountDownLatch installedLatch = new CountDownLatch(1);
19587        final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
19588            @Override
19589            public void onUserActionRequired(Intent intent) throws RemoteException {
19590                throw new IllegalStateException();
19591            }
19592
19593            @Override
19594            public void onPackageInstalled(String basePackageName, int returnCode, String msg,
19595                    Bundle extras) throws RemoteException {
19596                if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: "
19597                        + PackageManager.installStatusToString(returnCode, msg));
19598
19599                installedLatch.countDown();
19600                freezer.close();
19601
19602                final int status = PackageManager.installStatusToPublicStatus(returnCode);
19603                switch (status) {
19604                    case PackageInstaller.STATUS_SUCCESS:
19605                        mMoveCallbacks.notifyStatusChanged(moveId,
19606                                PackageManager.MOVE_SUCCEEDED);
19607                        break;
19608                    case PackageInstaller.STATUS_FAILURE_STORAGE:
19609                        mMoveCallbacks.notifyStatusChanged(moveId,
19610                                PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
19611                        break;
19612                    default:
19613                        mMoveCallbacks.notifyStatusChanged(moveId,
19614                                PackageManager.MOVE_FAILED_INTERNAL_ERROR);
19615                        break;
19616                }
19617            }
19618        };
19619
19620        final MoveInfo move;
19621        if (moveCompleteApp) {
19622            // Kick off a thread to report progress estimates
19623            new Thread() {
19624                @Override
19625                public void run() {
19626                    while (true) {
19627                        try {
19628                            if (installedLatch.await(1, TimeUnit.SECONDS)) {
19629                                break;
19630                            }
19631                        } catch (InterruptedException ignored) {
19632                        }
19633
19634                        final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace();
19635                        final int progress = 10 + (int) MathUtils.constrain(
19636                                ((deltaFreeBytes * 80) / sizeBytes), 0, 80);
19637                        mMoveCallbacks.notifyStatusChanged(moveId, progress);
19638                    }
19639                }
19640            }.start();
19641
19642            final String dataAppName = codeFile.getName();
19643            move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName,
19644                    dataAppName, appId, seinfo, targetSdkVersion);
19645        } else {
19646            move = null;
19647        }
19648
19649        installFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
19650
19651        final Message msg = mHandler.obtainMessage(INIT_COPY);
19652        final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
19653        final InstallParams params = new InstallParams(origin, move, installObserver, installFlags,
19654                installerPackageName, volumeUuid, null /*verificationInfo*/, user,
19655                packageAbiOverride, null /*grantedPermissions*/, null /*certificates*/);
19656        params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params));
19657        msg.obj = params;
19658
19659        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage",
19660                System.identityHashCode(msg.obj));
19661        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
19662                System.identityHashCode(msg.obj));
19663
19664        mHandler.sendMessage(msg);
19665    }
19666
19667    @Override
19668    public int movePrimaryStorage(String volumeUuid) throws RemoteException {
19669        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
19670
19671        final int realMoveId = mNextMoveId.getAndIncrement();
19672        final Bundle extras = new Bundle();
19673        extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid);
19674        mMoveCallbacks.notifyCreated(realMoveId, extras);
19675
19676        final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() {
19677            @Override
19678            public void onCreated(int moveId, Bundle extras) {
19679                // Ignored
19680            }
19681
19682            @Override
19683            public void onStatusChanged(int moveId, int status, long estMillis) {
19684                mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis);
19685            }
19686        };
19687
19688        final StorageManager storage = mContext.getSystemService(StorageManager.class);
19689        storage.setPrimaryStorageUuid(volumeUuid, callback);
19690        return realMoveId;
19691    }
19692
19693    @Override
19694    public int getMoveStatus(int moveId) {
19695        mContext.enforceCallingOrSelfPermission(
19696                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
19697        return mMoveCallbacks.mLastStatus.get(moveId);
19698    }
19699
19700    @Override
19701    public void registerMoveCallback(IPackageMoveObserver callback) {
19702        mContext.enforceCallingOrSelfPermission(
19703                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
19704        mMoveCallbacks.register(callback);
19705    }
19706
19707    @Override
19708    public void unregisterMoveCallback(IPackageMoveObserver callback) {
19709        mContext.enforceCallingOrSelfPermission(
19710                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
19711        mMoveCallbacks.unregister(callback);
19712    }
19713
19714    @Override
19715    public boolean setInstallLocation(int loc) {
19716        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
19717                null);
19718        if (getInstallLocation() == loc) {
19719            return true;
19720        }
19721        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
19722                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
19723            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
19724                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
19725            return true;
19726        }
19727        return false;
19728   }
19729
19730    @Override
19731    public int getInstallLocation() {
19732        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
19733                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
19734                PackageHelper.APP_INSTALL_AUTO);
19735    }
19736
19737    /** Called by UserManagerService */
19738    void cleanUpUser(UserManagerService userManager, int userHandle) {
19739        synchronized (mPackages) {
19740            mDirtyUsers.remove(userHandle);
19741            mUserNeedsBadging.delete(userHandle);
19742            mSettings.removeUserLPw(userHandle);
19743            mPendingBroadcasts.remove(userHandle);
19744            mEphemeralApplicationRegistry.onUserRemovedLPw(userHandle);
19745            removeUnusedPackagesLPw(userManager, userHandle);
19746        }
19747    }
19748
19749    /**
19750     * We're removing userHandle and would like to remove any downloaded packages
19751     * that are no longer in use by any other user.
19752     * @param userHandle the user being removed
19753     */
19754    private void removeUnusedPackagesLPw(UserManagerService userManager, final int userHandle) {
19755        final boolean DEBUG_CLEAN_APKS = false;
19756        int [] users = userManager.getUserIds();
19757        Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
19758        while (psit.hasNext()) {
19759            PackageSetting ps = psit.next();
19760            if (ps.pkg == null) {
19761                continue;
19762            }
19763            final String packageName = ps.pkg.packageName;
19764            // Skip over if system app
19765            if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
19766                continue;
19767            }
19768            if (DEBUG_CLEAN_APKS) {
19769                Slog.i(TAG, "Checking package " + packageName);
19770            }
19771            boolean keep = shouldKeepUninstalledPackageLPr(packageName);
19772            if (keep) {
19773                if (DEBUG_CLEAN_APKS) {
19774                    Slog.i(TAG, "  Keeping package " + packageName + " - requested by DO");
19775                }
19776            } else {
19777                for (int i = 0; i < users.length; i++) {
19778                    if (users[i] != userHandle && ps.getInstalled(users[i])) {
19779                        keep = true;
19780                        if (DEBUG_CLEAN_APKS) {
19781                            Slog.i(TAG, "  Keeping package " + packageName + " for user "
19782                                    + users[i]);
19783                        }
19784                        break;
19785                    }
19786                }
19787            }
19788            if (!keep) {
19789                if (DEBUG_CLEAN_APKS) {
19790                    Slog.i(TAG, "  Removing package " + packageName);
19791                }
19792                mHandler.post(new Runnable() {
19793                    public void run() {
19794                        deletePackageX(packageName, userHandle, 0);
19795                    } //end run
19796                });
19797            }
19798        }
19799    }
19800
19801    /** Called by UserManagerService */
19802    void createNewUser(int userHandle) {
19803        synchronized (mInstallLock) {
19804            mSettings.createNewUserLI(this, mInstaller, userHandle);
19805        }
19806        synchronized (mPackages) {
19807            applyFactoryDefaultBrowserLPw(userHandle);
19808            primeDomainVerificationsLPw(userHandle);
19809        }
19810    }
19811
19812    void newUserCreated(final int userHandle) {
19813        mDefaultPermissionPolicy.grantDefaultPermissions(userHandle);
19814        // If permission review for legacy apps is required, we represent
19815        // dagerous permissions for such apps as always granted runtime
19816        // permissions to keep per user flag state whether review is needed.
19817        // Hence, if a new user is added we have to propagate dangerous
19818        // permission grants for these legacy apps.
19819        if (Build.PERMISSIONS_REVIEW_REQUIRED) {
19820            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
19821                    | UPDATE_PERMISSIONS_REPLACE_ALL);
19822        }
19823    }
19824
19825    @Override
19826    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
19827        mContext.enforceCallingOrSelfPermission(
19828                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
19829                "Only package verification agents can read the verifier device identity");
19830
19831        synchronized (mPackages) {
19832            return mSettings.getVerifierDeviceIdentityLPw();
19833        }
19834    }
19835
19836    @Override
19837    public void setPermissionEnforced(String permission, boolean enforced) {
19838        // TODO: Now that we no longer change GID for storage, this should to away.
19839        mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
19840                "setPermissionEnforced");
19841        if (READ_EXTERNAL_STORAGE.equals(permission)) {
19842            synchronized (mPackages) {
19843                if (mSettings.mReadExternalStorageEnforced == null
19844                        || mSettings.mReadExternalStorageEnforced != enforced) {
19845                    mSettings.mReadExternalStorageEnforced = enforced;
19846                    mSettings.writeLPr();
19847                }
19848            }
19849            // kill any non-foreground processes so we restart them and
19850            // grant/revoke the GID.
19851            final IActivityManager am = ActivityManagerNative.getDefault();
19852            if (am != null) {
19853                final long token = Binder.clearCallingIdentity();
19854                try {
19855                    am.killProcessesBelowForeground("setPermissionEnforcement");
19856                } catch (RemoteException e) {
19857                } finally {
19858                    Binder.restoreCallingIdentity(token);
19859                }
19860            }
19861        } else {
19862            throw new IllegalArgumentException("No selective enforcement for " + permission);
19863        }
19864    }
19865
19866    @Override
19867    @Deprecated
19868    public boolean isPermissionEnforced(String permission) {
19869        return true;
19870    }
19871
19872    @Override
19873    public boolean isStorageLow() {
19874        final long token = Binder.clearCallingIdentity();
19875        try {
19876            final DeviceStorageMonitorInternal
19877                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
19878            if (dsm != null) {
19879                return dsm.isMemoryLow();
19880            } else {
19881                return false;
19882            }
19883        } finally {
19884            Binder.restoreCallingIdentity(token);
19885        }
19886    }
19887
19888    @Override
19889    public IPackageInstaller getPackageInstaller() {
19890        return mInstallerService;
19891    }
19892
19893    private boolean userNeedsBadging(int userId) {
19894        int index = mUserNeedsBadging.indexOfKey(userId);
19895        if (index < 0) {
19896            final UserInfo userInfo;
19897            final long token = Binder.clearCallingIdentity();
19898            try {
19899                userInfo = sUserManager.getUserInfo(userId);
19900            } finally {
19901                Binder.restoreCallingIdentity(token);
19902            }
19903            final boolean b;
19904            if (userInfo != null && userInfo.isManagedProfile()) {
19905                b = true;
19906            } else {
19907                b = false;
19908            }
19909            mUserNeedsBadging.put(userId, b);
19910            return b;
19911        }
19912        return mUserNeedsBadging.valueAt(index);
19913    }
19914
19915    @Override
19916    public KeySet getKeySetByAlias(String packageName, String alias) {
19917        if (packageName == null || alias == null) {
19918            return null;
19919        }
19920        synchronized(mPackages) {
19921            final PackageParser.Package pkg = mPackages.get(packageName);
19922            if (pkg == null) {
19923                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
19924                throw new IllegalArgumentException("Unknown package: " + packageName);
19925            }
19926            KeySetManagerService ksms = mSettings.mKeySetManagerService;
19927            return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
19928        }
19929    }
19930
19931    @Override
19932    public KeySet getSigningKeySet(String packageName) {
19933        if (packageName == null) {
19934            return null;
19935        }
19936        synchronized(mPackages) {
19937            final PackageParser.Package pkg = mPackages.get(packageName);
19938            if (pkg == null) {
19939                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
19940                throw new IllegalArgumentException("Unknown package: " + packageName);
19941            }
19942            if (pkg.applicationInfo.uid != Binder.getCallingUid()
19943                    && Process.SYSTEM_UID != Binder.getCallingUid()) {
19944                throw new SecurityException("May not access signing KeySet of other apps.");
19945            }
19946            KeySetManagerService ksms = mSettings.mKeySetManagerService;
19947            return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
19948        }
19949    }
19950
19951    @Override
19952    public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
19953        if (packageName == null || ks == null) {
19954            return false;
19955        }
19956        synchronized(mPackages) {
19957            final PackageParser.Package pkg = mPackages.get(packageName);
19958            if (pkg == null) {
19959                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
19960                throw new IllegalArgumentException("Unknown package: " + packageName);
19961            }
19962            IBinder ksh = ks.getToken();
19963            if (ksh instanceof KeySetHandle) {
19964                KeySetManagerService ksms = mSettings.mKeySetManagerService;
19965                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
19966            }
19967            return false;
19968        }
19969    }
19970
19971    @Override
19972    public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
19973        if (packageName == null || ks == null) {
19974            return false;
19975        }
19976        synchronized(mPackages) {
19977            final PackageParser.Package pkg = mPackages.get(packageName);
19978            if (pkg == null) {
19979                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
19980                throw new IllegalArgumentException("Unknown package: " + packageName);
19981            }
19982            IBinder ksh = ks.getToken();
19983            if (ksh instanceof KeySetHandle) {
19984                KeySetManagerService ksms = mSettings.mKeySetManagerService;
19985                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
19986            }
19987            return false;
19988        }
19989    }
19990
19991    private void deletePackageIfUnusedLPr(final String packageName) {
19992        PackageSetting ps = mSettings.mPackages.get(packageName);
19993        if (ps == null) {
19994            return;
19995        }
19996        if (!ps.isAnyInstalled(sUserManager.getUserIds())) {
19997            // TODO Implement atomic delete if package is unused
19998            // It is currently possible that the package will be deleted even if it is installed
19999            // after this method returns.
20000            mHandler.post(new Runnable() {
20001                public void run() {
20002                    deletePackageX(packageName, 0, PackageManager.DELETE_ALL_USERS);
20003                }
20004            });
20005        }
20006    }
20007
20008    /**
20009     * Check and throw if the given before/after packages would be considered a
20010     * downgrade.
20011     */
20012    private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after)
20013            throws PackageManagerException {
20014        if (after.versionCode < before.mVersionCode) {
20015            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
20016                    "Update version code " + after.versionCode + " is older than current "
20017                    + before.mVersionCode);
20018        } else if (after.versionCode == before.mVersionCode) {
20019            if (after.baseRevisionCode < before.baseRevisionCode) {
20020                throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
20021                        "Update base revision code " + after.baseRevisionCode
20022                        + " is older than current " + before.baseRevisionCode);
20023            }
20024
20025            if (!ArrayUtils.isEmpty(after.splitNames)) {
20026                for (int i = 0; i < after.splitNames.length; i++) {
20027                    final String splitName = after.splitNames[i];
20028                    final int j = ArrayUtils.indexOf(before.splitNames, splitName);
20029                    if (j != -1) {
20030                        if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) {
20031                            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
20032                                    "Update split " + splitName + " revision code "
20033                                    + after.splitRevisionCodes[i] + " is older than current "
20034                                    + before.splitRevisionCodes[j]);
20035                        }
20036                    }
20037                }
20038            }
20039        }
20040    }
20041
20042    private static class MoveCallbacks extends Handler {
20043        private static final int MSG_CREATED = 1;
20044        private static final int MSG_STATUS_CHANGED = 2;
20045
20046        private final RemoteCallbackList<IPackageMoveObserver>
20047                mCallbacks = new RemoteCallbackList<>();
20048
20049        private final SparseIntArray mLastStatus = new SparseIntArray();
20050
20051        public MoveCallbacks(Looper looper) {
20052            super(looper);
20053        }
20054
20055        public void register(IPackageMoveObserver callback) {
20056            mCallbacks.register(callback);
20057        }
20058
20059        public void unregister(IPackageMoveObserver callback) {
20060            mCallbacks.unregister(callback);
20061        }
20062
20063        @Override
20064        public void handleMessage(Message msg) {
20065            final SomeArgs args = (SomeArgs) msg.obj;
20066            final int n = mCallbacks.beginBroadcast();
20067            for (int i = 0; i < n; i++) {
20068                final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i);
20069                try {
20070                    invokeCallback(callback, msg.what, args);
20071                } catch (RemoteException ignored) {
20072                }
20073            }
20074            mCallbacks.finishBroadcast();
20075            args.recycle();
20076        }
20077
20078        private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args)
20079                throws RemoteException {
20080            switch (what) {
20081                case MSG_CREATED: {
20082                    callback.onCreated(args.argi1, (Bundle) args.arg2);
20083                    break;
20084                }
20085                case MSG_STATUS_CHANGED: {
20086                    callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3);
20087                    break;
20088                }
20089            }
20090        }
20091
20092        private void notifyCreated(int moveId, Bundle extras) {
20093            Slog.v(TAG, "Move " + moveId + " created " + extras.toString());
20094
20095            final SomeArgs args = SomeArgs.obtain();
20096            args.argi1 = moveId;
20097            args.arg2 = extras;
20098            obtainMessage(MSG_CREATED, args).sendToTarget();
20099        }
20100
20101        private void notifyStatusChanged(int moveId, int status) {
20102            notifyStatusChanged(moveId, status, -1);
20103        }
20104
20105        private void notifyStatusChanged(int moveId, int status, long estMillis) {
20106            Slog.v(TAG, "Move " + moveId + " status " + status);
20107
20108            final SomeArgs args = SomeArgs.obtain();
20109            args.argi1 = moveId;
20110            args.argi2 = status;
20111            args.arg3 = estMillis;
20112            obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget();
20113
20114            synchronized (mLastStatus) {
20115                mLastStatus.put(moveId, status);
20116            }
20117        }
20118    }
20119
20120    private final static class OnPermissionChangeListeners extends Handler {
20121        private static final int MSG_ON_PERMISSIONS_CHANGED = 1;
20122
20123        private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners =
20124                new RemoteCallbackList<>();
20125
20126        public OnPermissionChangeListeners(Looper looper) {
20127            super(looper);
20128        }
20129
20130        @Override
20131        public void handleMessage(Message msg) {
20132            switch (msg.what) {
20133                case MSG_ON_PERMISSIONS_CHANGED: {
20134                    final int uid = msg.arg1;
20135                    handleOnPermissionsChanged(uid);
20136                } break;
20137            }
20138        }
20139
20140        public void addListenerLocked(IOnPermissionsChangeListener listener) {
20141            mPermissionListeners.register(listener);
20142
20143        }
20144
20145        public void removeListenerLocked(IOnPermissionsChangeListener listener) {
20146            mPermissionListeners.unregister(listener);
20147        }
20148
20149        public void onPermissionsChanged(int uid) {
20150            if (mPermissionListeners.getRegisteredCallbackCount() > 0) {
20151                obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget();
20152            }
20153        }
20154
20155        private void handleOnPermissionsChanged(int uid) {
20156            final int count = mPermissionListeners.beginBroadcast();
20157            try {
20158                for (int i = 0; i < count; i++) {
20159                    IOnPermissionsChangeListener callback = mPermissionListeners
20160                            .getBroadcastItem(i);
20161                    try {
20162                        callback.onPermissionsChanged(uid);
20163                    } catch (RemoteException e) {
20164                        Log.e(TAG, "Permission listener is dead", e);
20165                    }
20166                }
20167            } finally {
20168                mPermissionListeners.finishBroadcast();
20169            }
20170        }
20171    }
20172
20173    private class PackageManagerInternalImpl extends PackageManagerInternal {
20174        @Override
20175        public void setLocationPackagesProvider(PackagesProvider provider) {
20176            synchronized (mPackages) {
20177                mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider);
20178            }
20179        }
20180
20181        @Override
20182        public void setVoiceInteractionPackagesProvider(PackagesProvider provider) {
20183            synchronized (mPackages) {
20184                mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider);
20185            }
20186        }
20187
20188        @Override
20189        public void setSmsAppPackagesProvider(PackagesProvider provider) {
20190            synchronized (mPackages) {
20191                mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider);
20192            }
20193        }
20194
20195        @Override
20196        public void setDialerAppPackagesProvider(PackagesProvider provider) {
20197            synchronized (mPackages) {
20198                mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider);
20199            }
20200        }
20201
20202        @Override
20203        public void setSimCallManagerPackagesProvider(PackagesProvider provider) {
20204            synchronized (mPackages) {
20205                mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider);
20206            }
20207        }
20208
20209        @Override
20210        public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) {
20211            synchronized (mPackages) {
20212                mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider);
20213            }
20214        }
20215
20216        @Override
20217        public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) {
20218            synchronized (mPackages) {
20219                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr(
20220                        packageName, userId);
20221            }
20222        }
20223
20224        @Override
20225        public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) {
20226            synchronized (mPackages) {
20227                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr(
20228                        packageName, userId);
20229            }
20230        }
20231
20232        @Override
20233        public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) {
20234            synchronized (mPackages) {
20235                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr(
20236                        packageName, userId);
20237            }
20238        }
20239
20240        @Override
20241        public void setKeepUninstalledPackages(final List<String> packageList) {
20242            Preconditions.checkNotNull(packageList);
20243            List<String> removedFromList = null;
20244            synchronized (mPackages) {
20245                if (mKeepUninstalledPackages != null) {
20246                    final int packagesCount = mKeepUninstalledPackages.size();
20247                    for (int i = 0; i < packagesCount; i++) {
20248                        String oldPackage = mKeepUninstalledPackages.get(i);
20249                        if (packageList != null && packageList.contains(oldPackage)) {
20250                            continue;
20251                        }
20252                        if (removedFromList == null) {
20253                            removedFromList = new ArrayList<>();
20254                        }
20255                        removedFromList.add(oldPackage);
20256                    }
20257                }
20258                mKeepUninstalledPackages = new ArrayList<>(packageList);
20259                if (removedFromList != null) {
20260                    final int removedCount = removedFromList.size();
20261                    for (int i = 0; i < removedCount; i++) {
20262                        deletePackageIfUnusedLPr(removedFromList.get(i));
20263                    }
20264                }
20265            }
20266        }
20267
20268        @Override
20269        public boolean isPermissionsReviewRequired(String packageName, int userId) {
20270            synchronized (mPackages) {
20271                // If we do not support permission review, done.
20272                if (!Build.PERMISSIONS_REVIEW_REQUIRED) {
20273                    return false;
20274                }
20275
20276                PackageSetting packageSetting = mSettings.mPackages.get(packageName);
20277                if (packageSetting == null) {
20278                    return false;
20279                }
20280
20281                // Permission review applies only to apps not supporting the new permission model.
20282                if (packageSetting.pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.M) {
20283                    return false;
20284                }
20285
20286                // Legacy apps have the permission and get user consent on launch.
20287                PermissionsState permissionsState = packageSetting.getPermissionsState();
20288                return permissionsState.isPermissionReviewRequired(userId);
20289            }
20290        }
20291
20292        @Override
20293        public ApplicationInfo getApplicationInfo(String packageName, int userId) {
20294            return PackageManagerService.this.getApplicationInfo(packageName, 0 /*flags*/, userId);
20295        }
20296
20297        @Override
20298        public ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
20299                int userId) {
20300            return PackageManagerService.this.getHomeActivitiesAsUser(allHomeCandidates, userId);
20301        }
20302    }
20303
20304    @Override
20305    public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) {
20306        enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps");
20307        synchronized (mPackages) {
20308            final long identity = Binder.clearCallingIdentity();
20309            try {
20310                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr(
20311                        packageNames, userId);
20312            } finally {
20313                Binder.restoreCallingIdentity(identity);
20314            }
20315        }
20316    }
20317
20318    private static void enforceSystemOrPhoneCaller(String tag) {
20319        int callingUid = Binder.getCallingUid();
20320        if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) {
20321            throw new SecurityException(
20322                    "Cannot call " + tag + " from UID " + callingUid);
20323        }
20324    }
20325
20326    boolean isHistoricalPackageUsageAvailable() {
20327        return mPackageUsage.isHistoricalPackageUsageAvailable();
20328    }
20329
20330    /**
20331     * Return a <b>copy</b> of the collection of packages known to the package manager.
20332     * @return A copy of the values of mPackages.
20333     */
20334    Collection<PackageParser.Package> getPackages() {
20335        synchronized (mPackages) {
20336            return new ArrayList<>(mPackages.values());
20337        }
20338    }
20339
20340    /**
20341     * Logs process start information (including base APK hash) to the security log.
20342     * @hide
20343     */
20344    public void logAppProcessStartIfNeeded(String processName, int uid, String seinfo,
20345            String apkFile, int pid) {
20346        if (!SecurityLog.isLoggingEnabled()) {
20347            return;
20348        }
20349        Bundle data = new Bundle();
20350        data.putLong("startTimestamp", System.currentTimeMillis());
20351        data.putString("processName", processName);
20352        data.putInt("uid", uid);
20353        data.putString("seinfo", seinfo);
20354        data.putString("apkFile", apkFile);
20355        data.putInt("pid", pid);
20356        Message msg = mProcessLoggingHandler.obtainMessage(
20357                ProcessLoggingHandler.LOG_APP_PROCESS_START_MSG);
20358        msg.setData(data);
20359        mProcessLoggingHandler.sendMessage(msg);
20360    }
20361}
20362