PackageManagerService.java revision 14e7acd58c8b4f9f2fd517cded5c4e3099fd5989
1/*
2 * Copyright (C) 2006 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server.pm;
18
19import static android.Manifest.permission.READ_EXTERNAL_STORAGE;
20import static android.Manifest.permission.WRITE_EXTERNAL_STORAGE;
21import static android.Manifest.permission.WRITE_MEDIA_STORAGE;
22import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DEFAULT;
23import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED;
24import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED;
25import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER;
26import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_ENABLED;
27import static android.content.pm.PackageManager.DELETE_KEEP_DATA;
28import static android.content.pm.PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
29import static android.content.pm.PackageManager.FLAG_PERMISSION_POLICY_FIXED;
30import static android.content.pm.PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
31import static android.content.pm.PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE;
32import static android.content.pm.PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
33import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_FIXED;
34import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_SET;
35import static android.content.pm.PackageManager.INSTALL_EXTERNAL;
36import static android.content.pm.PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
37import static android.content.pm.PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER;
38import static android.content.pm.PackageManager.INSTALL_FAILED_DEXOPT;
39import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
40import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION;
41import static android.content.pm.PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID;
42import static android.content.pm.PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
43import static android.content.pm.PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
44import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_APK;
45import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
46import static android.content.pm.PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY;
47import static android.content.pm.PackageManager.INSTALL_FAILED_PACKAGE_CHANGED;
48import static android.content.pm.PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
49import static android.content.pm.PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE;
50import static android.content.pm.PackageManager.INSTALL_FAILED_TEST_ONLY;
51import static android.content.pm.PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE;
52import static android.content.pm.PackageManager.INSTALL_FAILED_USER_RESTRICTED;
53import static android.content.pm.PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
54import static android.content.pm.PackageManager.INSTALL_FORWARD_LOCK;
55import static android.content.pm.PackageManager.INSTALL_INTERNAL;
56import static android.content.pm.PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
57import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
58import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK;
59import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
60import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER;
61import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
62import static android.content.pm.PackageManager.MATCH_ALL;
63import static android.content.pm.PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
64import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_AWARE;
65import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_UNAWARE;
66import static android.content.pm.PackageManager.MATCH_DISABLED_COMPONENTS;
67import static android.content.pm.PackageManager.MATCH_FACTORY_ONLY;
68import static android.content.pm.PackageManager.MATCH_SYSTEM_ONLY;
69import static android.content.pm.PackageManager.MATCH_UNINSTALLED_PACKAGES;
70import static android.content.pm.PackageManager.MOVE_FAILED_DEVICE_ADMIN;
71import static android.content.pm.PackageManager.MOVE_FAILED_DOESNT_EXIST;
72import static android.content.pm.PackageManager.MOVE_FAILED_INTERNAL_ERROR;
73import static android.content.pm.PackageManager.MOVE_FAILED_OPERATION_PENDING;
74import static android.content.pm.PackageManager.MOVE_FAILED_SYSTEM_PACKAGE;
75import static android.content.pm.PackageManager.PERMISSION_DENIED;
76import static android.content.pm.PackageManager.PERMISSION_GRANTED;
77import static android.content.pm.PackageParser.PARSE_IS_PRIVILEGED;
78import static android.content.pm.PackageParser.isApkFile;
79import static android.os.Process.PACKAGE_INFO_GID;
80import static android.os.Process.SYSTEM_UID;
81import static android.os.Trace.TRACE_TAG_PACKAGE_MANAGER;
82import static android.system.OsConstants.O_CREAT;
83import static android.system.OsConstants.O_RDWR;
84
85import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE;
86import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_PARENT;
87import static com.android.internal.content.NativeLibraryHelper.LIB64_DIR_NAME;
88import static com.android.internal.content.NativeLibraryHelper.LIB_DIR_NAME;
89import static com.android.internal.util.ArrayUtils.appendInt;
90import static com.android.server.pm.Installer.DEXOPT_PUBLIC;
91import static com.android.server.pm.InstructionSets.getAppDexInstructionSets;
92import static com.android.server.pm.InstructionSets.getDexCodeInstructionSet;
93import static com.android.server.pm.InstructionSets.getDexCodeInstructionSets;
94import static com.android.server.pm.InstructionSets.getPreferredInstructionSet;
95import static com.android.server.pm.InstructionSets.getPrimaryInstructionSet;
96import static com.android.server.pm.PackageManagerServiceCompilerMapping.getCompilerFilterForReason;
97import static com.android.server.pm.PackageManagerServiceCompilerMapping.getFullCompilerFilter;
98import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_FAILURE;
99import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS;
100import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED;
101
102import android.Manifest;
103import android.annotation.NonNull;
104import android.annotation.Nullable;
105import android.app.ActivityManager;
106import android.app.ActivityManagerNative;
107import android.app.IActivityManager;
108import android.app.admin.DevicePolicyManagerInternal;
109import android.app.admin.IDevicePolicyManager;
110import android.app.admin.SecurityLog;
111import android.app.backup.IBackupManager;
112import android.content.BroadcastReceiver;
113import android.content.ComponentName;
114import android.content.Context;
115import android.content.IIntentReceiver;
116import android.content.Intent;
117import android.content.IntentFilter;
118import android.content.IntentSender;
119import android.content.IntentSender.SendIntentException;
120import android.content.ServiceConnection;
121import android.content.pm.ActivityInfo;
122import android.content.pm.ApplicationInfo;
123import android.content.pm.AppsQueryHelper;
124import android.content.pm.ComponentInfo;
125import android.content.pm.EphemeralApplicationInfo;
126import android.content.pm.EphemeralResolveInfo;
127import android.content.pm.EphemeralResolveInfo.EphemeralResolveIntentInfo;
128import android.content.pm.FeatureInfo;
129import android.content.pm.IOnPermissionsChangeListener;
130import android.content.pm.IPackageDataObserver;
131import android.content.pm.IPackageDeleteObserver;
132import android.content.pm.IPackageDeleteObserver2;
133import android.content.pm.IPackageInstallObserver2;
134import android.content.pm.IPackageInstaller;
135import android.content.pm.IPackageManager;
136import android.content.pm.IPackageMoveObserver;
137import android.content.pm.IPackageStatsObserver;
138import android.content.pm.InstrumentationInfo;
139import android.content.pm.IntentFilterVerificationInfo;
140import android.content.pm.KeySet;
141import android.content.pm.PackageCleanItem;
142import android.content.pm.PackageInfo;
143import android.content.pm.PackageInfoLite;
144import android.content.pm.PackageInstaller;
145import android.content.pm.PackageManager;
146import android.content.pm.PackageManager.LegacyPackageDeleteObserver;
147import android.content.pm.PackageManagerInternal;
148import android.content.pm.PackageParser;
149import android.content.pm.PackageParser.ActivityIntentInfo;
150import android.content.pm.PackageParser.PackageLite;
151import android.content.pm.PackageParser.PackageParserException;
152import android.content.pm.PackageStats;
153import android.content.pm.PackageUserState;
154import android.content.pm.ParceledListSlice;
155import android.content.pm.PermissionGroupInfo;
156import android.content.pm.PermissionInfo;
157import android.content.pm.ProviderInfo;
158import android.content.pm.ResolveInfo;
159import android.content.pm.ServiceInfo;
160import android.content.pm.Signature;
161import android.content.pm.UserInfo;
162import android.content.pm.VerifierDeviceIdentity;
163import android.content.pm.VerifierInfo;
164import android.content.res.Resources;
165import android.graphics.Bitmap;
166import android.hardware.display.DisplayManager;
167import android.net.Uri;
168import android.os.Binder;
169import android.os.Build;
170import android.os.Bundle;
171import android.os.Debug;
172import android.os.Environment;
173import android.os.Environment.UserEnvironment;
174import android.os.FileUtils;
175import android.os.Handler;
176import android.os.IBinder;
177import android.os.Looper;
178import android.os.Message;
179import android.os.Parcel;
180import android.os.ParcelFileDescriptor;
181import android.os.Process;
182import android.os.RemoteCallbackList;
183import android.os.RemoteException;
184import android.os.ResultReceiver;
185import android.os.SELinux;
186import android.os.ServiceManager;
187import android.os.SystemClock;
188import android.os.SystemProperties;
189import android.os.Trace;
190import android.os.UserHandle;
191import android.os.UserManager;
192import android.os.storage.IMountService;
193import android.os.storage.MountServiceInternal;
194import android.os.storage.StorageEventListener;
195import android.os.storage.StorageManager;
196import android.os.storage.VolumeInfo;
197import android.os.storage.VolumeRecord;
198import android.security.KeyStore;
199import android.security.SystemKeyStore;
200import android.system.ErrnoException;
201import android.system.Os;
202import android.text.TextUtils;
203import android.text.format.DateUtils;
204import android.util.ArrayMap;
205import android.util.ArraySet;
206import android.util.AtomicFile;
207import android.util.DisplayMetrics;
208import android.util.EventLog;
209import android.util.ExceptionUtils;
210import android.util.Log;
211import android.util.LogPrinter;
212import android.util.MathUtils;
213import android.util.PrintStreamPrinter;
214import android.util.Slog;
215import android.util.SparseArray;
216import android.util.SparseBooleanArray;
217import android.util.SparseIntArray;
218import android.util.Xml;
219import android.util.jar.StrictJarFile;
220import android.view.Display;
221
222import com.android.internal.R;
223import com.android.internal.annotations.GuardedBy;
224import com.android.internal.app.IMediaContainerService;
225import com.android.internal.app.ResolverActivity;
226import com.android.internal.content.NativeLibraryHelper;
227import com.android.internal.content.PackageHelper;
228import com.android.internal.os.IParcelFileDescriptorFactory;
229import com.android.internal.os.InstallerConnection.InstallerException;
230import com.android.internal.os.SomeArgs;
231import com.android.internal.os.Zygote;
232import com.android.internal.telephony.CarrierAppUtils;
233import com.android.internal.util.ArrayUtils;
234import com.android.internal.util.FastPrintWriter;
235import com.android.internal.util.FastXmlSerializer;
236import com.android.internal.util.IndentingPrintWriter;
237import com.android.internal.util.Preconditions;
238import com.android.internal.util.XmlUtils;
239import com.android.server.EventLogTags;
240import com.android.server.FgThread;
241import com.android.server.IntentResolver;
242import com.android.server.LocalServices;
243import com.android.server.ServiceThread;
244import com.android.server.SystemConfig;
245import com.android.server.Watchdog;
246import com.android.server.pm.PermissionsState.PermissionState;
247import com.android.server.pm.Settings.DatabaseVersion;
248import com.android.server.pm.Settings.VersionInfo;
249import com.android.server.storage.DeviceStorageMonitorInternal;
250
251import dalvik.system.CloseGuard;
252import dalvik.system.DexFile;
253import dalvik.system.VMRuntime;
254
255import libcore.io.IoUtils;
256import libcore.util.EmptyArray;
257
258import org.xmlpull.v1.XmlPullParser;
259import org.xmlpull.v1.XmlPullParserException;
260import org.xmlpull.v1.XmlSerializer;
261
262import java.io.BufferedInputStream;
263import java.io.BufferedOutputStream;
264import java.io.BufferedReader;
265import java.io.ByteArrayInputStream;
266import java.io.ByteArrayOutputStream;
267import java.io.File;
268import java.io.FileDescriptor;
269import java.io.FileNotFoundException;
270import java.io.FileOutputStream;
271import java.io.FileReader;
272import java.io.FilenameFilter;
273import java.io.IOException;
274import java.io.InputStream;
275import java.io.PrintWriter;
276import java.nio.charset.StandardCharsets;
277import java.security.MessageDigest;
278import java.security.NoSuchAlgorithmException;
279import java.security.PublicKey;
280import java.security.cert.Certificate;
281import java.security.cert.CertificateEncodingException;
282import java.security.cert.CertificateException;
283import java.text.SimpleDateFormat;
284import java.util.ArrayList;
285import java.util.Arrays;
286import java.util.Collection;
287import java.util.Collections;
288import java.util.Comparator;
289import java.util.Date;
290import java.util.HashSet;
291import java.util.Iterator;
292import java.util.List;
293import java.util.Map;
294import java.util.Objects;
295import java.util.Set;
296import java.util.concurrent.CountDownLatch;
297import java.util.concurrent.TimeUnit;
298import java.util.concurrent.atomic.AtomicBoolean;
299import java.util.concurrent.atomic.AtomicInteger;
300import java.util.concurrent.atomic.AtomicLong;
301
302/**
303 * Keep track of all those APKs everywhere.
304 * <p>
305 * Internally there are two important locks:
306 * <ul>
307 * <li>{@link #mPackages} is used to guard all in-memory parsed package details
308 * and other related state. It is a fine-grained lock that should only be held
309 * momentarily, as it's one of the most contended locks in the system.
310 * <li>{@link #mInstallLock} is used to guard all {@code installd} access, whose
311 * operations typically involve heavy lifting of application data on disk. Since
312 * {@code installd} is single-threaded, and it's operations can often be slow,
313 * this lock should never be acquired while already holding {@link #mPackages}.
314 * Conversely, it's safe to acquire {@link #mPackages} momentarily while already
315 * holding {@link #mInstallLock}.
316 * </ul>
317 * Many internal methods rely on the caller to hold the appropriate locks, and
318 * this contract is expressed through method name suffixes:
319 * <ul>
320 * <li>fooLI(): the caller must hold {@link #mInstallLock}
321 * <li>fooLIF(): the caller must hold {@link #mInstallLock} and the package
322 * being modified must be frozen
323 * <li>fooLPr(): the caller must hold {@link #mPackages} for reading
324 * <li>fooLPw(): the caller must hold {@link #mPackages} for writing
325 * </ul>
326 * <p>
327 * Because this class is very central to the platform's security; please run all
328 * CTS and unit tests whenever making modifications:
329 *
330 * <pre>
331 * $ runtest -c android.content.pm.PackageManagerTests frameworks-core
332 * $ cts-tradefed run commandAndExit cts -m AppSecurityTests
333 * </pre>
334 */
335public class PackageManagerService extends IPackageManager.Stub {
336    static final String TAG = "PackageManager";
337    static final boolean DEBUG_SETTINGS = false;
338    static final boolean DEBUG_PREFERRED = false;
339    static final boolean DEBUG_UPGRADE = false;
340    static final boolean DEBUG_DOMAIN_VERIFICATION = false;
341    private static final boolean DEBUG_BACKUP = false;
342    private static final boolean DEBUG_INSTALL = false;
343    private static final boolean DEBUG_REMOVE = false;
344    private static final boolean DEBUG_BROADCASTS = false;
345    private static final boolean DEBUG_SHOW_INFO = false;
346    private static final boolean DEBUG_PACKAGE_INFO = false;
347    private static final boolean DEBUG_INTENT_MATCHING = false;
348    private static final boolean DEBUG_PACKAGE_SCANNING = false;
349    private static final boolean DEBUG_VERIFY = false;
350    private static final boolean DEBUG_FILTERS = false;
351
352    // Debug output for dexopting. This is shared between PackageManagerService, OtaDexoptService
353    // and PackageDexOptimizer. All these classes have their own flag to allow switching a single
354    // user, but by default initialize to this.
355    static final boolean DEBUG_DEXOPT = false;
356
357    private static final boolean DEBUG_ABI_SELECTION = false;
358    private static final boolean DEBUG_EPHEMERAL = false;
359    private static final boolean DEBUG_TRIAGED_MISSING = false;
360    private static final boolean DEBUG_APP_DATA = false;
361
362    static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = false;
363
364    private static final boolean DISABLE_EPHEMERAL_APPS = true;
365
366    private static final int RADIO_UID = Process.PHONE_UID;
367    private static final int LOG_UID = Process.LOG_UID;
368    private static final int NFC_UID = Process.NFC_UID;
369    private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID;
370    private static final int SHELL_UID = Process.SHELL_UID;
371
372    // Cap the size of permission trees that 3rd party apps can define
373    private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768;     // characters of text
374
375    // Suffix used during package installation when copying/moving
376    // package apks to install directory.
377    private static final String INSTALL_PACKAGE_SUFFIX = "-";
378
379    static final int SCAN_NO_DEX = 1<<1;
380    static final int SCAN_FORCE_DEX = 1<<2;
381    static final int SCAN_UPDATE_SIGNATURE = 1<<3;
382    static final int SCAN_NEW_INSTALL = 1<<4;
383    static final int SCAN_NO_PATHS = 1<<5;
384    static final int SCAN_UPDATE_TIME = 1<<6;
385    static final int SCAN_DEFER_DEX = 1<<7;
386    static final int SCAN_BOOTING = 1<<8;
387    static final int SCAN_TRUSTED_OVERLAY = 1<<9;
388    static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<10;
389    static final int SCAN_REPLACING = 1<<11;
390    static final int SCAN_REQUIRE_KNOWN = 1<<12;
391    static final int SCAN_MOVE = 1<<13;
392    static final int SCAN_INITIAL = 1<<14;
393    static final int SCAN_CHECK_ONLY = 1<<15;
394    static final int SCAN_DONT_KILL_APP = 1<<17;
395    static final int SCAN_IGNORE_FROZEN = 1<<18;
396
397    static final int REMOVE_CHATTY = 1<<16;
398
399    private static final int[] EMPTY_INT_ARRAY = new int[0];
400
401    /**
402     * Timeout (in milliseconds) after which the watchdog should declare that
403     * our handler thread is wedged.  The usual default for such things is one
404     * minute but we sometimes do very lengthy I/O operations on this thread,
405     * such as installing multi-gigabyte applications, so ours needs to be longer.
406     */
407    private static final long WATCHDOG_TIMEOUT = 1000*60*10;     // ten minutes
408
409    /**
410     * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim
411     * be run on this device.  We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL
412     * settings entry if available, otherwise we use the hardcoded default.  If it's been
413     * more than this long since the last fstrim, we force one during the boot sequence.
414     *
415     * This backstops other fstrim scheduling:  if the device is alive at midnight+idle,
416     * one gets run at the next available charging+idle time.  This final mandatory
417     * no-fstrim check kicks in only of the other scheduling criteria is never met.
418     */
419    private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS;
420
421    /**
422     * Whether verification is enabled by default.
423     */
424    private static final boolean DEFAULT_VERIFY_ENABLE = true;
425
426    /**
427     * The default maximum time to wait for the verification agent to return in
428     * milliseconds.
429     */
430    private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000;
431
432    /**
433     * The default response for package verification timeout.
434     *
435     * This can be either PackageManager.VERIFICATION_ALLOW or
436     * PackageManager.VERIFICATION_REJECT.
437     */
438    private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW;
439
440    static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer";
441
442    static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
443            DEFAULT_CONTAINER_PACKAGE,
444            "com.android.defcontainer.DefaultContainerService");
445
446    private static final String KILL_APP_REASON_GIDS_CHANGED =
447            "permission grant or revoke changed gids";
448
449    private static final String KILL_APP_REASON_PERMISSIONS_REVOKED =
450            "permissions revoked";
451
452    private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive";
453
454    private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay";
455
456    /** Permission grant: not grant the permission. */
457    private static final int GRANT_DENIED = 1;
458
459    /** Permission grant: grant the permission as an install permission. */
460    private static final int GRANT_INSTALL = 2;
461
462    /** Permission grant: grant the permission as a runtime one. */
463    private static final int GRANT_RUNTIME = 3;
464
465    /** Permission grant: grant as runtime a permission that was granted as an install time one. */
466    private static final int GRANT_UPGRADE = 4;
467
468    /** Canonical intent used to identify what counts as a "web browser" app */
469    private static final Intent sBrowserIntent;
470    static {
471        sBrowserIntent = new Intent();
472        sBrowserIntent.setAction(Intent.ACTION_VIEW);
473        sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE);
474        sBrowserIntent.setData(Uri.parse("http:"));
475    }
476
477    /**
478     * The set of all protected actions [i.e. those actions for which a high priority
479     * intent filter is disallowed].
480     */
481    private static final Set<String> PROTECTED_ACTIONS = new ArraySet<>();
482    static {
483        PROTECTED_ACTIONS.add(Intent.ACTION_SEND);
484        PROTECTED_ACTIONS.add(Intent.ACTION_SENDTO);
485        PROTECTED_ACTIONS.add(Intent.ACTION_SEND_MULTIPLE);
486        PROTECTED_ACTIONS.add(Intent.ACTION_VIEW);
487    }
488
489    // Compilation reasons.
490    public static final int REASON_FIRST_BOOT = 0;
491    public static final int REASON_BOOT = 1;
492    public static final int REASON_INSTALL = 2;
493    public static final int REASON_BACKGROUND_DEXOPT = 3;
494    public static final int REASON_AB_OTA = 4;
495    public static final int REASON_NON_SYSTEM_LIBRARY = 5;
496    public static final int REASON_SHARED_APK = 6;
497    public static final int REASON_FORCED_DEXOPT = 7;
498
499    public static final int REASON_LAST = REASON_FORCED_DEXOPT;
500
501    final ServiceThread mHandlerThread;
502
503    final PackageHandler mHandler;
504
505    private final ProcessLoggingHandler mProcessLoggingHandler;
506
507    /**
508     * Messages for {@link #mHandler} that need to wait for system ready before
509     * being dispatched.
510     */
511    private ArrayList<Message> mPostSystemReadyMessages;
512
513    final int mSdkVersion = Build.VERSION.SDK_INT;
514
515    final Context mContext;
516    final boolean mFactoryTest;
517    final boolean mOnlyCore;
518    final DisplayMetrics mMetrics;
519    final int mDefParseFlags;
520    final String[] mSeparateProcesses;
521    final boolean mIsUpgrade;
522    final boolean mIsPreNUpgrade;
523
524    /** The location for ASEC container files on internal storage. */
525    final String mAsecInternalPath;
526
527    // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages
528    // LOCK HELD.  Can be called with mInstallLock held.
529    @GuardedBy("mInstallLock")
530    final Installer mInstaller;
531
532    /** Directory where installed third-party apps stored */
533    final File mAppInstallDir;
534    final File mEphemeralInstallDir;
535
536    /**
537     * Directory to which applications installed internally have their
538     * 32 bit native libraries copied.
539     */
540    private File mAppLib32InstallDir;
541
542    // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked
543    // apps.
544    final File mDrmAppPrivateInstallDir;
545
546    // ----------------------------------------------------------------
547
548    // Lock for state used when installing and doing other long running
549    // operations.  Methods that must be called with this lock held have
550    // the suffix "LI".
551    final Object mInstallLock = new Object();
552
553    // ----------------------------------------------------------------
554
555    // Keys are String (package name), values are Package.  This also serves
556    // as the lock for the global state.  Methods that must be called with
557    // this lock held have the prefix "LP".
558    @GuardedBy("mPackages")
559    final ArrayMap<String, PackageParser.Package> mPackages =
560            new ArrayMap<String, PackageParser.Package>();
561
562    final ArrayMap<String, Set<String>> mKnownCodebase =
563            new ArrayMap<String, Set<String>>();
564
565    // Tracks available target package names -> overlay package paths.
566    final ArrayMap<String, ArrayMap<String, PackageParser.Package>> mOverlays =
567        new ArrayMap<String, ArrayMap<String, PackageParser.Package>>();
568
569    /**
570     * Tracks new system packages [received in an OTA] that we expect to
571     * find updated user-installed versions. Keys are package name, values
572     * are package location.
573     */
574    final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>();
575    /**
576     * Tracks high priority intent filters for protected actions. During boot, certain
577     * filter actions are protected and should never be allowed to have a high priority
578     * intent filter for them. However, there is one, and only one exception -- the
579     * setup wizard. It must be able to define a high priority intent filter for these
580     * actions to ensure there are no escapes from the wizard. We need to delay processing
581     * of these during boot as we need to look at all of the system packages in order
582     * to know which component is the setup wizard.
583     */
584    private final List<PackageParser.ActivityIntentInfo> mProtectedFilters = new ArrayList<>();
585    /**
586     * Whether or not processing protected filters should be deferred.
587     */
588    private boolean mDeferProtectedFilters = true;
589
590    /**
591     * Tracks existing system packages prior to receiving an OTA. Keys are package name.
592     */
593    final private ArraySet<String> mExistingSystemPackages = new ArraySet<>();
594    /**
595     * Whether or not system app permissions should be promoted from install to runtime.
596     */
597    boolean mPromoteSystemApps;
598
599    @GuardedBy("mPackages")
600    final Settings mSettings;
601
602    /**
603     * Set of package names that are currently "frozen", which means active
604     * surgery is being done on the code/data for that package. The platform
605     * will refuse to launch frozen packages to avoid race conditions.
606     *
607     * @see PackageFreezer
608     */
609    @GuardedBy("mPackages")
610    final ArraySet<String> mFrozenPackages = new ArraySet<>();
611
612    boolean mRestoredSettings;
613
614    // System configuration read by SystemConfig.
615    final int[] mGlobalGids;
616    final SparseArray<ArraySet<String>> mSystemPermissions;
617    final ArrayMap<String, FeatureInfo> mAvailableFeatures;
618
619    // If mac_permissions.xml was found for seinfo labeling.
620    boolean mFoundPolicyFile;
621
622    private final EphemeralApplicationRegistry mEphemeralApplicationRegistry;
623
624    public static final class SharedLibraryEntry {
625        public final String path;
626        public final String apk;
627
628        SharedLibraryEntry(String _path, String _apk) {
629            path = _path;
630            apk = _apk;
631        }
632    }
633
634    // Currently known shared libraries.
635    final ArrayMap<String, SharedLibraryEntry> mSharedLibraries =
636            new ArrayMap<String, SharedLibraryEntry>();
637
638    // All available activities, for your resolving pleasure.
639    final ActivityIntentResolver mActivities =
640            new ActivityIntentResolver();
641
642    // All available receivers, for your resolving pleasure.
643    final ActivityIntentResolver mReceivers =
644            new ActivityIntentResolver();
645
646    // All available services, for your resolving pleasure.
647    final ServiceIntentResolver mServices = new ServiceIntentResolver();
648
649    // All available providers, for your resolving pleasure.
650    final ProviderIntentResolver mProviders = new ProviderIntentResolver();
651
652    // Mapping from provider base names (first directory in content URI codePath)
653    // to the provider information.
654    final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority =
655            new ArrayMap<String, PackageParser.Provider>();
656
657    // Mapping from instrumentation class names to info about them.
658    final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
659            new ArrayMap<ComponentName, PackageParser.Instrumentation>();
660
661    // Mapping from permission names to info about them.
662    final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups =
663            new ArrayMap<String, PackageParser.PermissionGroup>();
664
665    // Packages whose data we have transfered into another package, thus
666    // should no longer exist.
667    final ArraySet<String> mTransferedPackages = new ArraySet<String>();
668
669    // Broadcast actions that are only available to the system.
670    final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>();
671
672    /** List of packages waiting for verification. */
673    final SparseArray<PackageVerificationState> mPendingVerification
674            = new SparseArray<PackageVerificationState>();
675
676    /** Set of packages associated with each app op permission. */
677    final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>();
678
679    final PackageInstallerService mInstallerService;
680
681    private final PackageDexOptimizer mPackageDexOptimizer;
682
683    private AtomicInteger mNextMoveId = new AtomicInteger();
684    private final MoveCallbacks mMoveCallbacks;
685
686    private final OnPermissionChangeListeners mOnPermissionChangeListeners;
687
688    // Cache of users who need badging.
689    SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray();
690
691    /** Token for keys in mPendingVerification. */
692    private int mPendingVerificationToken = 0;
693
694    volatile boolean mSystemReady;
695    volatile boolean mSafeMode;
696    volatile boolean mHasSystemUidErrors;
697
698    ApplicationInfo mAndroidApplication;
699    final ActivityInfo mResolveActivity = new ActivityInfo();
700    final ResolveInfo mResolveInfo = new ResolveInfo();
701    ComponentName mResolveComponentName;
702    PackageParser.Package mPlatformPackage;
703    ComponentName mCustomResolverComponentName;
704
705    boolean mResolverReplaced = false;
706
707    private final @Nullable ComponentName mIntentFilterVerifierComponent;
708    private final @Nullable IntentFilterVerifier<ActivityIntentInfo> mIntentFilterVerifier;
709
710    private int mIntentFilterVerificationToken = 0;
711
712    /** Component that knows whether or not an ephemeral application exists */
713    final ComponentName mEphemeralResolverComponent;
714    /** The service connection to the ephemeral resolver */
715    final EphemeralResolverConnection mEphemeralResolverConnection;
716
717    /** Component used to install ephemeral applications */
718    final ComponentName mEphemeralInstallerComponent;
719    final ActivityInfo mEphemeralInstallerActivity = new ActivityInfo();
720    final ResolveInfo mEphemeralInstallerInfo = new ResolveInfo();
721
722    final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates
723            = new SparseArray<IntentFilterVerificationState>();
724
725    final DefaultPermissionGrantPolicy mDefaultPermissionPolicy =
726            new DefaultPermissionGrantPolicy(this);
727
728    // List of packages names to keep cached, even if they are uninstalled for all users
729    private List<String> mKeepUninstalledPackages;
730
731    private static class IFVerificationParams {
732        PackageParser.Package pkg;
733        boolean replacing;
734        int userId;
735        int verifierUid;
736
737        public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing,
738                int _userId, int _verifierUid) {
739            pkg = _pkg;
740            replacing = _replacing;
741            userId = _userId;
742            replacing = _replacing;
743            verifierUid = _verifierUid;
744        }
745    }
746
747    private interface IntentFilterVerifier<T extends IntentFilter> {
748        boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId,
749                                               T filter, String packageName);
750        void startVerifications(int userId);
751        void receiveVerificationResponse(int verificationId);
752    }
753
754    private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> {
755        private Context mContext;
756        private ComponentName mIntentFilterVerifierComponent;
757        private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>();
758
759        public IntentVerifierProxy(Context context, ComponentName verifierComponent) {
760            mContext = context;
761            mIntentFilterVerifierComponent = verifierComponent;
762        }
763
764        private String getDefaultScheme() {
765            return IntentFilter.SCHEME_HTTPS;
766        }
767
768        @Override
769        public void startVerifications(int userId) {
770            // Launch verifications requests
771            int count = mCurrentIntentFilterVerifications.size();
772            for (int n=0; n<count; n++) {
773                int verificationId = mCurrentIntentFilterVerifications.get(n);
774                final IntentFilterVerificationState ivs =
775                        mIntentFilterVerificationStates.get(verificationId);
776
777                String packageName = ivs.getPackageName();
778
779                ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
780                final int filterCount = filters.size();
781                ArraySet<String> domainsSet = new ArraySet<>();
782                for (int m=0; m<filterCount; m++) {
783                    PackageParser.ActivityIntentInfo filter = filters.get(m);
784                    domainsSet.addAll(filter.getHostsList());
785                }
786                ArrayList<String> domainsList = new ArrayList<>(domainsSet);
787                synchronized (mPackages) {
788                    if (mSettings.createIntentFilterVerificationIfNeededLPw(
789                            packageName, domainsList) != null) {
790                        scheduleWriteSettingsLocked();
791                    }
792                }
793                sendVerificationRequest(userId, verificationId, ivs);
794            }
795            mCurrentIntentFilterVerifications.clear();
796        }
797
798        private void sendVerificationRequest(int userId, int verificationId,
799                IntentFilterVerificationState ivs) {
800
801            Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
802            verificationIntent.putExtra(
803                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID,
804                    verificationId);
805            verificationIntent.putExtra(
806                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME,
807                    getDefaultScheme());
808            verificationIntent.putExtra(
809                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS,
810                    ivs.getHostsString());
811            verificationIntent.putExtra(
812                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME,
813                    ivs.getPackageName());
814            verificationIntent.setComponent(mIntentFilterVerifierComponent);
815            verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
816
817            UserHandle user = new UserHandle(userId);
818            mContext.sendBroadcastAsUser(verificationIntent, user);
819            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
820                    "Sending IntentFilter verification broadcast");
821        }
822
823        public void receiveVerificationResponse(int verificationId) {
824            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
825
826            final boolean verified = ivs.isVerified();
827
828            ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
829            final int count = filters.size();
830            if (DEBUG_DOMAIN_VERIFICATION) {
831                Slog.i(TAG, "Received verification response " + verificationId
832                        + " for " + count + " filters, verified=" + verified);
833            }
834            for (int n=0; n<count; n++) {
835                PackageParser.ActivityIntentInfo filter = filters.get(n);
836                filter.setVerified(verified);
837
838                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString()
839                        + " verified with result:" + verified + " and hosts:"
840                        + ivs.getHostsString());
841            }
842
843            mIntentFilterVerificationStates.remove(verificationId);
844
845            final String packageName = ivs.getPackageName();
846            IntentFilterVerificationInfo ivi = null;
847
848            synchronized (mPackages) {
849                ivi = mSettings.getIntentFilterVerificationLPr(packageName);
850            }
851            if (ivi == null) {
852                Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:"
853                        + verificationId + " packageName:" + packageName);
854                return;
855            }
856            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
857                    "Updating IntentFilterVerificationInfo for package " + packageName
858                            +" verificationId:" + verificationId);
859
860            synchronized (mPackages) {
861                if (verified) {
862                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS);
863                } else {
864                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK);
865                }
866                scheduleWriteSettingsLocked();
867
868                final int userId = ivs.getUserId();
869                if (userId != UserHandle.USER_ALL) {
870                    final int userStatus =
871                            mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
872
873                    int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
874                    boolean needUpdate = false;
875
876                    // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have
877                    // already been set by the User thru the Disambiguation dialog
878                    switch (userStatus) {
879                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
880                            if (verified) {
881                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
882                            } else {
883                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
884                            }
885                            needUpdate = true;
886                            break;
887
888                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
889                            if (verified) {
890                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
891                                needUpdate = true;
892                            }
893                            break;
894
895                        default:
896                            // Nothing to do
897                    }
898
899                    if (needUpdate) {
900                        mSettings.updateIntentFilterVerificationStatusLPw(
901                                packageName, updatedStatus, userId);
902                        scheduleWritePackageRestrictionsLocked(userId);
903                    }
904                }
905            }
906        }
907
908        @Override
909        public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId,
910                    ActivityIntentInfo filter, String packageName) {
911            if (!hasValidDomains(filter)) {
912                return false;
913            }
914            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
915            if (ivs == null) {
916                ivs = createDomainVerificationState(verifierUid, userId, verificationId,
917                        packageName);
918            }
919            if (DEBUG_DOMAIN_VERIFICATION) {
920                Slog.d(TAG, "Adding verification filter for " + packageName + ": " + filter);
921            }
922            ivs.addFilter(filter);
923            return true;
924        }
925
926        private IntentFilterVerificationState createDomainVerificationState(int verifierUid,
927                int userId, int verificationId, String packageName) {
928            IntentFilterVerificationState ivs = new IntentFilterVerificationState(
929                    verifierUid, userId, packageName);
930            ivs.setPendingState();
931            synchronized (mPackages) {
932                mIntentFilterVerificationStates.append(verificationId, ivs);
933                mCurrentIntentFilterVerifications.add(verificationId);
934            }
935            return ivs;
936        }
937    }
938
939    private static boolean hasValidDomains(ActivityIntentInfo filter) {
940        return filter.hasCategory(Intent.CATEGORY_BROWSABLE)
941                && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
942                        filter.hasDataScheme(IntentFilter.SCHEME_HTTPS));
943    }
944
945    // Set of pending broadcasts for aggregating enable/disable of components.
946    static class PendingPackageBroadcasts {
947        // for each user id, a map of <package name -> components within that package>
948        final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap;
949
950        public PendingPackageBroadcasts() {
951            mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2);
952        }
953
954        public ArrayList<String> get(int userId, String packageName) {
955            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
956            return packages.get(packageName);
957        }
958
959        public void put(int userId, String packageName, ArrayList<String> components) {
960            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
961            packages.put(packageName, components);
962        }
963
964        public void remove(int userId, String packageName) {
965            ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId);
966            if (packages != null) {
967                packages.remove(packageName);
968            }
969        }
970
971        public void remove(int userId) {
972            mUidMap.remove(userId);
973        }
974
975        public int userIdCount() {
976            return mUidMap.size();
977        }
978
979        public int userIdAt(int n) {
980            return mUidMap.keyAt(n);
981        }
982
983        public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) {
984            return mUidMap.get(userId);
985        }
986
987        public int size() {
988            // total number of pending broadcast entries across all userIds
989            int num = 0;
990            for (int i = 0; i< mUidMap.size(); i++) {
991                num += mUidMap.valueAt(i).size();
992            }
993            return num;
994        }
995
996        public void clear() {
997            mUidMap.clear();
998        }
999
1000        private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) {
1001            ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId);
1002            if (map == null) {
1003                map = new ArrayMap<String, ArrayList<String>>();
1004                mUidMap.put(userId, map);
1005            }
1006            return map;
1007        }
1008    }
1009    final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts();
1010
1011    // Service Connection to remote media container service to copy
1012    // package uri's from external media onto secure containers
1013    // or internal storage.
1014    private IMediaContainerService mContainerService = null;
1015
1016    static final int SEND_PENDING_BROADCAST = 1;
1017    static final int MCS_BOUND = 3;
1018    static final int END_COPY = 4;
1019    static final int INIT_COPY = 5;
1020    static final int MCS_UNBIND = 6;
1021    static final int START_CLEANING_PACKAGE = 7;
1022    static final int FIND_INSTALL_LOC = 8;
1023    static final int POST_INSTALL = 9;
1024    static final int MCS_RECONNECT = 10;
1025    static final int MCS_GIVE_UP = 11;
1026    static final int UPDATED_MEDIA_STATUS = 12;
1027    static final int WRITE_SETTINGS = 13;
1028    static final int WRITE_PACKAGE_RESTRICTIONS = 14;
1029    static final int PACKAGE_VERIFIED = 15;
1030    static final int CHECK_PENDING_VERIFICATION = 16;
1031    static final int START_INTENT_FILTER_VERIFICATIONS = 17;
1032    static final int INTENT_FILTER_VERIFIED = 18;
1033
1034    static final int WRITE_SETTINGS_DELAY = 10*1000;  // 10 seconds
1035
1036    // Delay time in millisecs
1037    static final int BROADCAST_DELAY = 10 * 1000;
1038
1039    static UserManagerService sUserManager;
1040
1041    // Stores a list of users whose package restrictions file needs to be updated
1042    private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>();
1043
1044    final private DefaultContainerConnection mDefContainerConn =
1045            new DefaultContainerConnection();
1046    class DefaultContainerConnection implements ServiceConnection {
1047        public void onServiceConnected(ComponentName name, IBinder service) {
1048            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
1049            IMediaContainerService imcs =
1050                IMediaContainerService.Stub.asInterface(service);
1051            mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
1052        }
1053
1054        public void onServiceDisconnected(ComponentName name) {
1055            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
1056        }
1057    }
1058
1059    // Recordkeeping of restore-after-install operations that are currently in flight
1060    // between the Package Manager and the Backup Manager
1061    static class PostInstallData {
1062        public InstallArgs args;
1063        public PackageInstalledInfo res;
1064
1065        PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
1066            args = _a;
1067            res = _r;
1068        }
1069    }
1070
1071    final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
1072    int mNextInstallToken = 1;  // nonzero; will be wrapped back to 1 when ++ overflows
1073
1074    // XML tags for backup/restore of various bits of state
1075    private static final String TAG_PREFERRED_BACKUP = "pa";
1076    private static final String TAG_DEFAULT_APPS = "da";
1077    private static final String TAG_INTENT_FILTER_VERIFICATION = "iv";
1078
1079    private static final String TAG_PERMISSION_BACKUP = "perm-grant-backup";
1080    private static final String TAG_ALL_GRANTS = "rt-grants";
1081    private static final String TAG_GRANT = "grant";
1082    private static final String ATTR_PACKAGE_NAME = "pkg";
1083
1084    private static final String TAG_PERMISSION = "perm";
1085    private static final String ATTR_PERMISSION_NAME = "name";
1086    private static final String ATTR_IS_GRANTED = "g";
1087    private static final String ATTR_USER_SET = "set";
1088    private static final String ATTR_USER_FIXED = "fixed";
1089    private static final String ATTR_REVOKE_ON_UPGRADE = "rou";
1090
1091    // System/policy permission grants are not backed up
1092    private static final int SYSTEM_RUNTIME_GRANT_MASK =
1093            FLAG_PERMISSION_POLICY_FIXED
1094            | FLAG_PERMISSION_SYSTEM_FIXED
1095            | FLAG_PERMISSION_GRANTED_BY_DEFAULT;
1096
1097    // And we back up these user-adjusted states
1098    private static final int USER_RUNTIME_GRANT_MASK =
1099            FLAG_PERMISSION_USER_SET
1100            | FLAG_PERMISSION_USER_FIXED
1101            | FLAG_PERMISSION_REVOKE_ON_UPGRADE;
1102
1103    final @Nullable String mRequiredVerifierPackage;
1104    final @NonNull String mRequiredInstallerPackage;
1105    final @Nullable String mSetupWizardPackage;
1106    final @NonNull String mServicesSystemSharedLibraryPackageName;
1107    final @NonNull String mSharedSystemSharedLibraryPackageName;
1108
1109    private final PackageUsage mPackageUsage = new PackageUsage();
1110
1111    private class PackageUsage {
1112        private static final int WRITE_INTERVAL
1113            = (DEBUG_DEXOPT) ? 0 : 30*60*1000; // 30m in ms
1114
1115        private final Object mFileLock = new Object();
1116        private final AtomicLong mLastWritten = new AtomicLong(0);
1117        private final AtomicBoolean mBackgroundWriteRunning = new AtomicBoolean(false);
1118
1119        private boolean mIsHistoricalPackageUsageAvailable = true;
1120
1121        boolean isHistoricalPackageUsageAvailable() {
1122            return mIsHistoricalPackageUsageAvailable;
1123        }
1124
1125        void write(boolean force) {
1126            if (force) {
1127                writeInternal();
1128                return;
1129            }
1130            if (SystemClock.elapsedRealtime() - mLastWritten.get() < WRITE_INTERVAL
1131                && !DEBUG_DEXOPT) {
1132                return;
1133            }
1134            if (mBackgroundWriteRunning.compareAndSet(false, true)) {
1135                new Thread("PackageUsage_DiskWriter") {
1136                    @Override
1137                    public void run() {
1138                        try {
1139                            writeInternal();
1140                        } finally {
1141                            mBackgroundWriteRunning.set(false);
1142                        }
1143                    }
1144                }.start();
1145            }
1146        }
1147
1148        private void writeInternal() {
1149            synchronized (mPackages) {
1150                synchronized (mFileLock) {
1151                    AtomicFile file = getFile();
1152                    FileOutputStream f = null;
1153                    try {
1154                        f = file.startWrite();
1155                        BufferedOutputStream out = new BufferedOutputStream(f);
1156                        FileUtils.setPermissions(file.getBaseFile().getPath(),
1157                                0640, SYSTEM_UID, PACKAGE_INFO_GID);
1158                        StringBuilder sb = new StringBuilder();
1159
1160                        sb.append(USAGE_FILE_MAGIC_VERSION_1);
1161                        sb.append('\n');
1162                        out.write(sb.toString().getBytes(StandardCharsets.US_ASCII));
1163
1164                        for (PackageParser.Package pkg : mPackages.values()) {
1165                            if (pkg.getLatestPackageUseTimeInMills() == 0L) {
1166                                continue;
1167                            }
1168                            sb.setLength(0);
1169                            sb.append(pkg.packageName);
1170                            for (long usageTimeInMillis : pkg.mLastPackageUsageTimeInMills) {
1171                                sb.append(' ');
1172                                sb.append(usageTimeInMillis);
1173                            }
1174                            sb.append('\n');
1175                            out.write(sb.toString().getBytes(StandardCharsets.US_ASCII));
1176                        }
1177                        out.flush();
1178                        file.finishWrite(f);
1179                    } catch (IOException e) {
1180                        if (f != null) {
1181                            file.failWrite(f);
1182                        }
1183                        Log.e(TAG, "Failed to write package usage times", e);
1184                    }
1185                }
1186            }
1187            mLastWritten.set(SystemClock.elapsedRealtime());
1188        }
1189
1190        void readLP() {
1191            synchronized (mFileLock) {
1192                AtomicFile file = getFile();
1193                BufferedInputStream in = null;
1194                try {
1195                    in = new BufferedInputStream(file.openRead());
1196                    StringBuffer sb = new StringBuffer();
1197
1198                    String firstLine = readLine(in, sb);
1199                    if (firstLine.equals(USAGE_FILE_MAGIC_VERSION_1)) {
1200                        readVersion1LP(in, sb);
1201                    } else {
1202                        readVersion0LP(in, sb, firstLine);
1203                    }
1204                } catch (FileNotFoundException expected) {
1205                    mIsHistoricalPackageUsageAvailable = false;
1206                } catch (IOException e) {
1207                    Log.w(TAG, "Failed to read package usage times", e);
1208                } finally {
1209                    IoUtils.closeQuietly(in);
1210                }
1211            }
1212            mLastWritten.set(SystemClock.elapsedRealtime());
1213        }
1214
1215        private void readVersion0LP(InputStream in, StringBuffer sb, String firstLine)
1216                throws IOException {
1217            // Initial version of the file had no version number and stored one
1218            // package-timestamp pair per line.
1219            // Note that the first line has already been read from the InputStream.
1220            for (String line = firstLine; line != null; line = readLine(in, sb)) {
1221                String[] tokens = line.split(" ");
1222                if (tokens.length != 2) {
1223                    throw new IOException("Failed to parse " + line +
1224                            " as package-timestamp pair.");
1225                }
1226
1227                String packageName = tokens[0];
1228                PackageParser.Package pkg = mPackages.get(packageName);
1229                if (pkg == null) {
1230                    continue;
1231                }
1232
1233                long timestamp = parseAsLong(tokens[1]);
1234                for (int reason = 0;
1235                        reason < PackageManager.NOTIFY_PACKAGE_USE_REASONS_COUNT;
1236                        reason++) {
1237                    pkg.mLastPackageUsageTimeInMills[reason] = timestamp;
1238                }
1239            }
1240        }
1241
1242        private void readVersion1LP(InputStream in, StringBuffer sb) throws IOException {
1243            // Version 1 of the file started with the corresponding version
1244            // number and then stored a package name and eight timestamps per line.
1245            String line;
1246            while ((line = readLine(in, sb)) != null) {
1247                String[] tokens = line.split(" ");
1248                if (tokens.length != PackageManager.NOTIFY_PACKAGE_USE_REASONS_COUNT + 1) {
1249                    throw new IOException("Failed to parse " + line + " as a timestamp array.");
1250                }
1251
1252                String packageName = tokens[0];
1253                PackageParser.Package pkg = mPackages.get(packageName);
1254                if (pkg == null) {
1255                    continue;
1256                }
1257
1258                for (int reason = 0;
1259                        reason < PackageManager.NOTIFY_PACKAGE_USE_REASONS_COUNT;
1260                        reason++) {
1261                    pkg.mLastPackageUsageTimeInMills[reason] = parseAsLong(tokens[reason + 1]);
1262                }
1263            }
1264        }
1265
1266        private long parseAsLong(String token) throws IOException {
1267            try {
1268                return Long.parseLong(token);
1269            } catch (NumberFormatException e) {
1270                throw new IOException("Failed to parse " + token + " as a long.", e);
1271            }
1272        }
1273
1274        private String readLine(InputStream in, StringBuffer sb) throws IOException {
1275            return readToken(in, sb, '\n');
1276        }
1277
1278        private String readToken(InputStream in, StringBuffer sb, char endOfToken)
1279                throws IOException {
1280            sb.setLength(0);
1281            while (true) {
1282                int ch = in.read();
1283                if (ch == -1) {
1284                    if (sb.length() == 0) {
1285                        return null;
1286                    }
1287                    throw new IOException("Unexpected EOF");
1288                }
1289                if (ch == endOfToken) {
1290                    return sb.toString();
1291                }
1292                sb.append((char)ch);
1293            }
1294        }
1295
1296        private AtomicFile getFile() {
1297            File dataDir = Environment.getDataDirectory();
1298            File systemDir = new File(dataDir, "system");
1299            File fname = new File(systemDir, "package-usage.list");
1300            return new AtomicFile(fname);
1301        }
1302
1303        private static final String USAGE_FILE_MAGIC = "PACKAGE_USAGE__VERSION_";
1304        private static final String USAGE_FILE_MAGIC_VERSION_1 = USAGE_FILE_MAGIC + "1";
1305    }
1306
1307    class PackageHandler extends Handler {
1308        private boolean mBound = false;
1309        final ArrayList<HandlerParams> mPendingInstalls =
1310            new ArrayList<HandlerParams>();
1311
1312        private boolean connectToService() {
1313            if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
1314                    " DefaultContainerService");
1315            Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
1316            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1317            if (mContext.bindServiceAsUser(service, mDefContainerConn,
1318                    Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
1319                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1320                mBound = true;
1321                return true;
1322            }
1323            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1324            return false;
1325        }
1326
1327        private void disconnectService() {
1328            mContainerService = null;
1329            mBound = false;
1330            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1331            mContext.unbindService(mDefContainerConn);
1332            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1333        }
1334
1335        PackageHandler(Looper looper) {
1336            super(looper);
1337        }
1338
1339        public void handleMessage(Message msg) {
1340            try {
1341                doHandleMessage(msg);
1342            } finally {
1343                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1344            }
1345        }
1346
1347        void doHandleMessage(Message msg) {
1348            switch (msg.what) {
1349                case INIT_COPY: {
1350                    HandlerParams params = (HandlerParams) msg.obj;
1351                    int idx = mPendingInstalls.size();
1352                    if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params);
1353                    // If a bind was already initiated we dont really
1354                    // need to do anything. The pending install
1355                    // will be processed later on.
1356                    if (!mBound) {
1357                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1358                                System.identityHashCode(mHandler));
1359                        // If this is the only one pending we might
1360                        // have to bind to the service again.
1361                        if (!connectToService()) {
1362                            Slog.e(TAG, "Failed to bind to media container service");
1363                            params.serviceError();
1364                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1365                                    System.identityHashCode(mHandler));
1366                            if (params.traceMethod != null) {
1367                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod,
1368                                        params.traceCookie);
1369                            }
1370                            return;
1371                        } else {
1372                            // Once we bind to the service, the first
1373                            // pending request will be processed.
1374                            mPendingInstalls.add(idx, params);
1375                        }
1376                    } else {
1377                        mPendingInstalls.add(idx, params);
1378                        // Already bound to the service. Just make
1379                        // sure we trigger off processing the first request.
1380                        if (idx == 0) {
1381                            mHandler.sendEmptyMessage(MCS_BOUND);
1382                        }
1383                    }
1384                    break;
1385                }
1386                case MCS_BOUND: {
1387                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound");
1388                    if (msg.obj != null) {
1389                        mContainerService = (IMediaContainerService) msg.obj;
1390                        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1391                                System.identityHashCode(mHandler));
1392                    }
1393                    if (mContainerService == null) {
1394                        if (!mBound) {
1395                            // Something seriously wrong since we are not bound and we are not
1396                            // waiting for connection. Bail out.
1397                            Slog.e(TAG, "Cannot bind to media container service");
1398                            for (HandlerParams params : mPendingInstalls) {
1399                                // Indicate service bind error
1400                                params.serviceError();
1401                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1402                                        System.identityHashCode(params));
1403                                if (params.traceMethod != null) {
1404                                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER,
1405                                            params.traceMethod, params.traceCookie);
1406                                }
1407                                return;
1408                            }
1409                            mPendingInstalls.clear();
1410                        } else {
1411                            Slog.w(TAG, "Waiting to connect to media container service");
1412                        }
1413                    } else if (mPendingInstalls.size() > 0) {
1414                        HandlerParams params = mPendingInstalls.get(0);
1415                        if (params != null) {
1416                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1417                                    System.identityHashCode(params));
1418                            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy");
1419                            if (params.startCopy()) {
1420                                // We are done...  look for more work or to
1421                                // go idle.
1422                                if (DEBUG_SD_INSTALL) Log.i(TAG,
1423                                        "Checking for more work or unbind...");
1424                                // Delete pending install
1425                                if (mPendingInstalls.size() > 0) {
1426                                    mPendingInstalls.remove(0);
1427                                }
1428                                if (mPendingInstalls.size() == 0) {
1429                                    if (mBound) {
1430                                        if (DEBUG_SD_INSTALL) Log.i(TAG,
1431                                                "Posting delayed MCS_UNBIND");
1432                                        removeMessages(MCS_UNBIND);
1433                                        Message ubmsg = obtainMessage(MCS_UNBIND);
1434                                        // Unbind after a little delay, to avoid
1435                                        // continual thrashing.
1436                                        sendMessageDelayed(ubmsg, 10000);
1437                                    }
1438                                } else {
1439                                    // There are more pending requests in queue.
1440                                    // Just post MCS_BOUND message to trigger processing
1441                                    // of next pending install.
1442                                    if (DEBUG_SD_INSTALL) Log.i(TAG,
1443                                            "Posting MCS_BOUND for next work");
1444                                    mHandler.sendEmptyMessage(MCS_BOUND);
1445                                }
1446                            }
1447                            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
1448                        }
1449                    } else {
1450                        // Should never happen ideally.
1451                        Slog.w(TAG, "Empty queue");
1452                    }
1453                    break;
1454                }
1455                case MCS_RECONNECT: {
1456                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect");
1457                    if (mPendingInstalls.size() > 0) {
1458                        if (mBound) {
1459                            disconnectService();
1460                        }
1461                        if (!connectToService()) {
1462                            Slog.e(TAG, "Failed to bind to media container service");
1463                            for (HandlerParams params : mPendingInstalls) {
1464                                // Indicate service bind error
1465                                params.serviceError();
1466                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1467                                        System.identityHashCode(params));
1468                            }
1469                            mPendingInstalls.clear();
1470                        }
1471                    }
1472                    break;
1473                }
1474                case MCS_UNBIND: {
1475                    // If there is no actual work left, then time to unbind.
1476                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind");
1477
1478                    if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) {
1479                        if (mBound) {
1480                            if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()");
1481
1482                            disconnectService();
1483                        }
1484                    } else if (mPendingInstalls.size() > 0) {
1485                        // There are more pending requests in queue.
1486                        // Just post MCS_BOUND message to trigger processing
1487                        // of next pending install.
1488                        mHandler.sendEmptyMessage(MCS_BOUND);
1489                    }
1490
1491                    break;
1492                }
1493                case MCS_GIVE_UP: {
1494                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries");
1495                    HandlerParams params = mPendingInstalls.remove(0);
1496                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1497                            System.identityHashCode(params));
1498                    break;
1499                }
1500                case SEND_PENDING_BROADCAST: {
1501                    String packages[];
1502                    ArrayList<String> components[];
1503                    int size = 0;
1504                    int uids[];
1505                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1506                    synchronized (mPackages) {
1507                        if (mPendingBroadcasts == null) {
1508                            return;
1509                        }
1510                        size = mPendingBroadcasts.size();
1511                        if (size <= 0) {
1512                            // Nothing to be done. Just return
1513                            return;
1514                        }
1515                        packages = new String[size];
1516                        components = new ArrayList[size];
1517                        uids = new int[size];
1518                        int i = 0;  // filling out the above arrays
1519
1520                        for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) {
1521                            int packageUserId = mPendingBroadcasts.userIdAt(n);
1522                            Iterator<Map.Entry<String, ArrayList<String>>> it
1523                                    = mPendingBroadcasts.packagesForUserId(packageUserId)
1524                                            .entrySet().iterator();
1525                            while (it.hasNext() && i < size) {
1526                                Map.Entry<String, ArrayList<String>> ent = it.next();
1527                                packages[i] = ent.getKey();
1528                                components[i] = ent.getValue();
1529                                PackageSetting ps = mSettings.mPackages.get(ent.getKey());
1530                                uids[i] = (ps != null)
1531                                        ? UserHandle.getUid(packageUserId, ps.appId)
1532                                        : -1;
1533                                i++;
1534                            }
1535                        }
1536                        size = i;
1537                        mPendingBroadcasts.clear();
1538                    }
1539                    // Send broadcasts
1540                    for (int i = 0; i < size; i++) {
1541                        sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]);
1542                    }
1543                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1544                    break;
1545                }
1546                case START_CLEANING_PACKAGE: {
1547                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1548                    final String packageName = (String)msg.obj;
1549                    final int userId = msg.arg1;
1550                    final boolean andCode = msg.arg2 != 0;
1551                    synchronized (mPackages) {
1552                        if (userId == UserHandle.USER_ALL) {
1553                            int[] users = sUserManager.getUserIds();
1554                            for (int user : users) {
1555                                mSettings.addPackageToCleanLPw(
1556                                        new PackageCleanItem(user, packageName, andCode));
1557                            }
1558                        } else {
1559                            mSettings.addPackageToCleanLPw(
1560                                    new PackageCleanItem(userId, packageName, andCode));
1561                        }
1562                    }
1563                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1564                    startCleaningPackages();
1565                } break;
1566                case POST_INSTALL: {
1567                    if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
1568
1569                    PostInstallData data = mRunningInstalls.get(msg.arg1);
1570                    mRunningInstalls.delete(msg.arg1);
1571
1572                    if (data != null) {
1573                        InstallArgs args = data.args;
1574                        PackageInstalledInfo parentRes = data.res;
1575
1576                        final boolean grantPermissions = (args.installFlags
1577                                & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0;
1578                        final boolean killApp = (args.installFlags
1579                                & PackageManager.INSTALL_DONT_KILL_APP) == 0;
1580                        final String[] grantedPermissions = args.installGrantPermissions;
1581
1582                        // Handle the parent package
1583                        handlePackagePostInstall(parentRes, grantPermissions, killApp,
1584                                grantedPermissions, args.observer);
1585
1586                        // Handle the child packages
1587                        final int childCount = (parentRes.addedChildPackages != null)
1588                                ? parentRes.addedChildPackages.size() : 0;
1589                        for (int i = 0; i < childCount; i++) {
1590                            PackageInstalledInfo childRes = parentRes.addedChildPackages.valueAt(i);
1591                            handlePackagePostInstall(childRes, grantPermissions, killApp,
1592                                    grantedPermissions, args.observer);
1593                        }
1594
1595                        // Log tracing if needed
1596                        if (args.traceMethod != null) {
1597                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod,
1598                                    args.traceCookie);
1599                        }
1600                    } else {
1601                        Slog.e(TAG, "Bogus post-install token " + msg.arg1);
1602                    }
1603
1604                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1);
1605                } break;
1606                case UPDATED_MEDIA_STATUS: {
1607                    if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS");
1608                    boolean reportStatus = msg.arg1 == 1;
1609                    boolean doGc = msg.arg2 == 1;
1610                    if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc);
1611                    if (doGc) {
1612                        // Force a gc to clear up stale containers.
1613                        Runtime.getRuntime().gc();
1614                    }
1615                    if (msg.obj != null) {
1616                        @SuppressWarnings("unchecked")
1617                        Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj;
1618                        if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers");
1619                        // Unload containers
1620                        unloadAllContainers(args);
1621                    }
1622                    if (reportStatus) {
1623                        try {
1624                            if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back");
1625                            PackageHelper.getMountService().finishMediaUpdate();
1626                        } catch (RemoteException e) {
1627                            Log.e(TAG, "MountService not running?");
1628                        }
1629                    }
1630                } break;
1631                case WRITE_SETTINGS: {
1632                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1633                    synchronized (mPackages) {
1634                        removeMessages(WRITE_SETTINGS);
1635                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1636                        mSettings.writeLPr();
1637                        mDirtyUsers.clear();
1638                    }
1639                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1640                } break;
1641                case WRITE_PACKAGE_RESTRICTIONS: {
1642                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1643                    synchronized (mPackages) {
1644                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1645                        for (int userId : mDirtyUsers) {
1646                            mSettings.writePackageRestrictionsLPr(userId);
1647                        }
1648                        mDirtyUsers.clear();
1649                    }
1650                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1651                } break;
1652                case CHECK_PENDING_VERIFICATION: {
1653                    final int verificationId = msg.arg1;
1654                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1655
1656                    if ((state != null) && !state.timeoutExtended()) {
1657                        final InstallArgs args = state.getInstallArgs();
1658                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1659
1660                        Slog.i(TAG, "Verification timed out for " + originUri);
1661                        mPendingVerification.remove(verificationId);
1662
1663                        int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1664
1665                        if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) {
1666                            Slog.i(TAG, "Continuing with installation of " + originUri);
1667                            state.setVerifierResponse(Binder.getCallingUid(),
1668                                    PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT);
1669                            broadcastPackageVerified(verificationId, originUri,
1670                                    PackageManager.VERIFICATION_ALLOW,
1671                                    state.getInstallArgs().getUser());
1672                            try {
1673                                ret = args.copyApk(mContainerService, true);
1674                            } catch (RemoteException e) {
1675                                Slog.e(TAG, "Could not contact the ContainerService");
1676                            }
1677                        } else {
1678                            broadcastPackageVerified(verificationId, originUri,
1679                                    PackageManager.VERIFICATION_REJECT,
1680                                    state.getInstallArgs().getUser());
1681                        }
1682
1683                        Trace.asyncTraceEnd(
1684                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1685
1686                        processPendingInstall(args, ret);
1687                        mHandler.sendEmptyMessage(MCS_UNBIND);
1688                    }
1689                    break;
1690                }
1691                case PACKAGE_VERIFIED: {
1692                    final int verificationId = msg.arg1;
1693
1694                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1695                    if (state == null) {
1696                        Slog.w(TAG, "Invalid verification token " + verificationId + " received");
1697                        break;
1698                    }
1699
1700                    final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj;
1701
1702                    state.setVerifierResponse(response.callerUid, response.code);
1703
1704                    if (state.isVerificationComplete()) {
1705                        mPendingVerification.remove(verificationId);
1706
1707                        final InstallArgs args = state.getInstallArgs();
1708                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1709
1710                        int ret;
1711                        if (state.isInstallAllowed()) {
1712                            ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
1713                            broadcastPackageVerified(verificationId, originUri,
1714                                    response.code, state.getInstallArgs().getUser());
1715                            try {
1716                                ret = args.copyApk(mContainerService, true);
1717                            } catch (RemoteException e) {
1718                                Slog.e(TAG, "Could not contact the ContainerService");
1719                            }
1720                        } else {
1721                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1722                        }
1723
1724                        Trace.asyncTraceEnd(
1725                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1726
1727                        processPendingInstall(args, ret);
1728                        mHandler.sendEmptyMessage(MCS_UNBIND);
1729                    }
1730
1731                    break;
1732                }
1733                case START_INTENT_FILTER_VERIFICATIONS: {
1734                    IFVerificationParams params = (IFVerificationParams) msg.obj;
1735                    verifyIntentFiltersIfNeeded(params.userId, params.verifierUid,
1736                            params.replacing, params.pkg);
1737                    break;
1738                }
1739                case INTENT_FILTER_VERIFIED: {
1740                    final int verificationId = msg.arg1;
1741
1742                    final IntentFilterVerificationState state = mIntentFilterVerificationStates.get(
1743                            verificationId);
1744                    if (state == null) {
1745                        Slog.w(TAG, "Invalid IntentFilter verification token "
1746                                + verificationId + " received");
1747                        break;
1748                    }
1749
1750                    final int userId = state.getUserId();
1751
1752                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1753                            "Processing IntentFilter verification with token:"
1754                            + verificationId + " and userId:" + userId);
1755
1756                    final IntentFilterVerificationResponse response =
1757                            (IntentFilterVerificationResponse) msg.obj;
1758
1759                    state.setVerifierResponse(response.callerUid, response.code);
1760
1761                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1762                            "IntentFilter verification with token:" + verificationId
1763                            + " and userId:" + userId
1764                            + " is settings verifier response with response code:"
1765                            + response.code);
1766
1767                    if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) {
1768                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: "
1769                                + response.getFailedDomainsString());
1770                    }
1771
1772                    if (state.isVerificationComplete()) {
1773                        mIntentFilterVerifier.receiveVerificationResponse(verificationId);
1774                    } else {
1775                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1776                                "IntentFilter verification with token:" + verificationId
1777                                + " was not said to be complete");
1778                    }
1779
1780                    break;
1781                }
1782            }
1783        }
1784    }
1785
1786    private void handlePackagePostInstall(PackageInstalledInfo res, boolean grantPermissions,
1787            boolean killApp, String[] grantedPermissions,
1788            IPackageInstallObserver2 installObserver) {
1789        if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
1790            // Send the removed broadcasts
1791            if (res.removedInfo != null) {
1792                res.removedInfo.sendPackageRemovedBroadcasts(killApp);
1793            }
1794
1795            // Now that we successfully installed the package, grant runtime
1796            // permissions if requested before broadcasting the install.
1797            if (grantPermissions && res.pkg.applicationInfo.targetSdkVersion
1798                    >= Build.VERSION_CODES.M) {
1799                grantRequestedRuntimePermissions(res.pkg, res.newUsers, grantedPermissions);
1800            }
1801
1802            final boolean update = res.removedInfo != null
1803                    && res.removedInfo.removedPackage != null;
1804
1805            // If this is the first time we have child packages for a disabled privileged
1806            // app that had no children, we grant requested runtime permissions to the new
1807            // children if the parent on the system image had them already granted.
1808            if (res.pkg.parentPackage != null) {
1809                synchronized (mPackages) {
1810                    grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(res.pkg);
1811                }
1812            }
1813
1814            synchronized (mPackages) {
1815                mEphemeralApplicationRegistry.onPackageInstalledLPw(res.pkg);
1816            }
1817
1818            final String packageName = res.pkg.applicationInfo.packageName;
1819            Bundle extras = new Bundle(1);
1820            extras.putInt(Intent.EXTRA_UID, res.uid);
1821
1822            // Determine the set of users who are adding this package for
1823            // the first time vs. those who are seeing an update.
1824            int[] firstUsers = EMPTY_INT_ARRAY;
1825            int[] updateUsers = EMPTY_INT_ARRAY;
1826            if (res.origUsers == null || res.origUsers.length == 0) {
1827                firstUsers = res.newUsers;
1828            } else {
1829                for (int newUser : res.newUsers) {
1830                    boolean isNew = true;
1831                    for (int origUser : res.origUsers) {
1832                        if (origUser == newUser) {
1833                            isNew = false;
1834                            break;
1835                        }
1836                    }
1837                    if (isNew) {
1838                        firstUsers = ArrayUtils.appendInt(firstUsers, newUser);
1839                    } else {
1840                        updateUsers = ArrayUtils.appendInt(updateUsers, newUser);
1841                    }
1842                }
1843            }
1844
1845            // Send installed broadcasts if the install/update is not ephemeral
1846            if (!isEphemeral(res.pkg)) {
1847                mProcessLoggingHandler.invalidateProcessLoggingBaseApkHash(res.pkg.baseCodePath);
1848
1849                // Send added for users that see the package for the first time
1850                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
1851                        extras, 0 /*flags*/, null /*targetPackage*/,
1852                        null /*finishedReceiver*/, firstUsers);
1853
1854                // Send added for users that don't see the package for the first time
1855                if (update) {
1856                    extras.putBoolean(Intent.EXTRA_REPLACING, true);
1857                }
1858                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
1859                        extras, 0 /*flags*/, null /*targetPackage*/,
1860                        null /*finishedReceiver*/, updateUsers);
1861
1862                // Send replaced for users that don't see the package for the first time
1863                if (update) {
1864                    sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
1865                            packageName, extras, 0 /*flags*/,
1866                            null /*targetPackage*/, null /*finishedReceiver*/,
1867                            updateUsers);
1868                    sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
1869                            null /*package*/, null /*extras*/, 0 /*flags*/,
1870                            packageName /*targetPackage*/,
1871                            null /*finishedReceiver*/, updateUsers);
1872                }
1873
1874                // Send broadcast package appeared if forward locked/external for all users
1875                // treat asec-hosted packages like removable media on upgrade
1876                if (res.pkg.isForwardLocked() || isExternal(res.pkg)) {
1877                    if (DEBUG_INSTALL) {
1878                        Slog.i(TAG, "upgrading pkg " + res.pkg
1879                                + " is ASEC-hosted -> AVAILABLE");
1880                    }
1881                    final int[] uidArray = new int[]{res.pkg.applicationInfo.uid};
1882                    ArrayList<String> pkgList = new ArrayList<>(1);
1883                    pkgList.add(packageName);
1884                    sendResourcesChangedBroadcast(true, true, pkgList, uidArray, null);
1885                }
1886            }
1887
1888            // Work that needs to happen on first install within each user
1889            if (firstUsers != null && firstUsers.length > 0) {
1890                synchronized (mPackages) {
1891                    for (int userId : firstUsers) {
1892                        // If this app is a browser and it's newly-installed for some
1893                        // users, clear any default-browser state in those users. The
1894                        // app's nature doesn't depend on the user, so we can just check
1895                        // its browser nature in any user and generalize.
1896                        if (packageIsBrowser(packageName, userId)) {
1897                            mSettings.setDefaultBrowserPackageNameLPw(null, userId);
1898                        }
1899
1900                        // We may also need to apply pending (restored) runtime
1901                        // permission grants within these users.
1902                        mSettings.applyPendingPermissionGrantsLPw(packageName, userId);
1903                    }
1904                }
1905            }
1906
1907            // Log current value of "unknown sources" setting
1908            EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED,
1909                    getUnknownSourcesSettings());
1910
1911            // Force a gc to clear up things
1912            Runtime.getRuntime().gc();
1913
1914            // Remove the replaced package's older resources safely now
1915            // We delete after a gc for applications  on sdcard.
1916            if (res.removedInfo != null && res.removedInfo.args != null) {
1917                synchronized (mInstallLock) {
1918                    res.removedInfo.args.doPostDeleteLI(true);
1919                }
1920            }
1921        }
1922
1923        // If someone is watching installs - notify them
1924        if (installObserver != null) {
1925            try {
1926                Bundle extras = extrasForInstallResult(res);
1927                installObserver.onPackageInstalled(res.name, res.returnCode,
1928                        res.returnMsg, extras);
1929            } catch (RemoteException e) {
1930                Slog.i(TAG, "Observer no longer exists.");
1931            }
1932        }
1933    }
1934
1935    private void grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(
1936            PackageParser.Package pkg) {
1937        if (pkg.parentPackage == null) {
1938            return;
1939        }
1940        if (pkg.requestedPermissions == null) {
1941            return;
1942        }
1943        final PackageSetting disabledSysParentPs = mSettings
1944                .getDisabledSystemPkgLPr(pkg.parentPackage.packageName);
1945        if (disabledSysParentPs == null || disabledSysParentPs.pkg == null
1946                || !disabledSysParentPs.isPrivileged()
1947                || (disabledSysParentPs.childPackageNames != null
1948                        && !disabledSysParentPs.childPackageNames.isEmpty())) {
1949            return;
1950        }
1951        final int[] allUserIds = sUserManager.getUserIds();
1952        final int permCount = pkg.requestedPermissions.size();
1953        for (int i = 0; i < permCount; i++) {
1954            String permission = pkg.requestedPermissions.get(i);
1955            BasePermission bp = mSettings.mPermissions.get(permission);
1956            if (bp == null || !(bp.isRuntime() || bp.isDevelopment())) {
1957                continue;
1958            }
1959            for (int userId : allUserIds) {
1960                if (disabledSysParentPs.getPermissionsState().hasRuntimePermission(
1961                        permission, userId)) {
1962                    grantRuntimePermission(pkg.packageName, permission, userId);
1963                }
1964            }
1965        }
1966    }
1967
1968    private StorageEventListener mStorageListener = new StorageEventListener() {
1969        @Override
1970        public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) {
1971            if (vol.type == VolumeInfo.TYPE_PRIVATE) {
1972                if (vol.state == VolumeInfo.STATE_MOUNTED) {
1973                    final String volumeUuid = vol.getFsUuid();
1974
1975                    // Clean up any users or apps that were removed or recreated
1976                    // while this volume was missing
1977                    reconcileUsers(volumeUuid);
1978                    reconcileApps(volumeUuid);
1979
1980                    // Clean up any install sessions that expired or were
1981                    // cancelled while this volume was missing
1982                    mInstallerService.onPrivateVolumeMounted(volumeUuid);
1983
1984                    loadPrivatePackages(vol);
1985
1986                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
1987                    unloadPrivatePackages(vol);
1988                }
1989            }
1990
1991            if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) {
1992                if (vol.state == VolumeInfo.STATE_MOUNTED) {
1993                    updateExternalMediaStatus(true, false);
1994                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
1995                    updateExternalMediaStatus(false, false);
1996                }
1997            }
1998        }
1999
2000        @Override
2001        public void onVolumeForgotten(String fsUuid) {
2002            if (TextUtils.isEmpty(fsUuid)) {
2003                Slog.e(TAG, "Forgetting internal storage is probably a mistake; ignoring");
2004                return;
2005            }
2006
2007            // Remove any apps installed on the forgotten volume
2008            synchronized (mPackages) {
2009                final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid);
2010                for (PackageSetting ps : packages) {
2011                    Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten");
2012                    deletePackage(ps.name, new LegacyPackageDeleteObserver(null).getBinder(),
2013                            UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS);
2014                }
2015
2016                mSettings.onVolumeForgotten(fsUuid);
2017                mSettings.writeLPr();
2018            }
2019        }
2020    };
2021
2022    private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int[] userIds,
2023            String[] grantedPermissions) {
2024        for (int userId : userIds) {
2025            grantRequestedRuntimePermissionsForUser(pkg, userId, grantedPermissions);
2026        }
2027
2028        // We could have touched GID membership, so flush out packages.list
2029        synchronized (mPackages) {
2030            mSettings.writePackageListLPr();
2031        }
2032    }
2033
2034    private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId,
2035            String[] grantedPermissions) {
2036        SettingBase sb = (SettingBase) pkg.mExtras;
2037        if (sb == null) {
2038            return;
2039        }
2040
2041        PermissionsState permissionsState = sb.getPermissionsState();
2042
2043        final int immutableFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
2044                | PackageManager.FLAG_PERMISSION_POLICY_FIXED;
2045
2046        for (String permission : pkg.requestedPermissions) {
2047            final BasePermission bp;
2048            synchronized (mPackages) {
2049                bp = mSettings.mPermissions.get(permission);
2050            }
2051            if (bp != null && (bp.isRuntime() || bp.isDevelopment())
2052                    && (grantedPermissions == null
2053                           || ArrayUtils.contains(grantedPermissions, permission))) {
2054                final int flags = permissionsState.getPermissionFlags(permission, userId);
2055                // Installer cannot change immutable permissions.
2056                if ((flags & immutableFlags) == 0) {
2057                    grantRuntimePermission(pkg.packageName, permission, userId);
2058                }
2059            }
2060        }
2061    }
2062
2063    Bundle extrasForInstallResult(PackageInstalledInfo res) {
2064        Bundle extras = null;
2065        switch (res.returnCode) {
2066            case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: {
2067                extras = new Bundle();
2068                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION,
2069                        res.origPermission);
2070                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE,
2071                        res.origPackage);
2072                break;
2073            }
2074            case PackageManager.INSTALL_SUCCEEDED: {
2075                extras = new Bundle();
2076                extras.putBoolean(Intent.EXTRA_REPLACING,
2077                        res.removedInfo != null && res.removedInfo.removedPackage != null);
2078                break;
2079            }
2080        }
2081        return extras;
2082    }
2083
2084    void scheduleWriteSettingsLocked() {
2085        if (!mHandler.hasMessages(WRITE_SETTINGS)) {
2086            mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
2087        }
2088    }
2089
2090    void scheduleWritePackageRestrictionsLocked(UserHandle user) {
2091        final int userId = user == null ? UserHandle.USER_ALL : user.getIdentifier();
2092        scheduleWritePackageRestrictionsLocked(userId);
2093    }
2094
2095    void scheduleWritePackageRestrictionsLocked(int userId) {
2096        final int[] userIds = (userId == UserHandle.USER_ALL)
2097                ? sUserManager.getUserIds() : new int[]{userId};
2098        for (int nextUserId : userIds) {
2099            if (!sUserManager.exists(nextUserId)) return;
2100            mDirtyUsers.add(nextUserId);
2101            if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) {
2102                mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY);
2103            }
2104        }
2105    }
2106
2107    public static PackageManagerService main(Context context, Installer installer,
2108            boolean factoryTest, boolean onlyCore) {
2109        // Self-check for initial settings.
2110        PackageManagerServiceCompilerMapping.checkProperties();
2111
2112        PackageManagerService m = new PackageManagerService(context, installer,
2113                factoryTest, onlyCore);
2114        m.enableSystemUserPackages();
2115        // Disable any carrier apps. We do this very early in boot to prevent the apps from being
2116        // disabled after already being started.
2117        CarrierAppUtils.disableCarrierAppsUntilPrivileged(context.getOpPackageName(), m,
2118                UserHandle.USER_SYSTEM);
2119        ServiceManager.addService("package", m);
2120        return m;
2121    }
2122
2123    private void enableSystemUserPackages() {
2124        if (!UserManager.isSplitSystemUser()) {
2125            return;
2126        }
2127        // For system user, enable apps based on the following conditions:
2128        // - app is whitelisted or belong to one of these groups:
2129        //   -- system app which has no launcher icons
2130        //   -- system app which has INTERACT_ACROSS_USERS permission
2131        //   -- system IME app
2132        // - app is not in the blacklist
2133        AppsQueryHelper queryHelper = new AppsQueryHelper(this);
2134        Set<String> enableApps = new ArraySet<>();
2135        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS
2136                | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM
2137                | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM));
2138        ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps();
2139        enableApps.addAll(wlApps);
2140        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_REQUIRED_FOR_SYSTEM_USER,
2141                /* systemAppsOnly */ false, UserHandle.SYSTEM));
2142        ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps();
2143        enableApps.removeAll(blApps);
2144        Log.i(TAG, "Applications installed for system user: " + enableApps);
2145        List<String> allAps = queryHelper.queryApps(0, /* systemAppsOnly */ false,
2146                UserHandle.SYSTEM);
2147        final int allAppsSize = allAps.size();
2148        synchronized (mPackages) {
2149            for (int i = 0; i < allAppsSize; i++) {
2150                String pName = allAps.get(i);
2151                PackageSetting pkgSetting = mSettings.mPackages.get(pName);
2152                // Should not happen, but we shouldn't be failing if it does
2153                if (pkgSetting == null) {
2154                    continue;
2155                }
2156                boolean install = enableApps.contains(pName);
2157                if (pkgSetting.getInstalled(UserHandle.USER_SYSTEM) != install) {
2158                    Log.i(TAG, (install ? "Installing " : "Uninstalling ") + pName
2159                            + " for system user");
2160                    pkgSetting.setInstalled(install, UserHandle.USER_SYSTEM);
2161                }
2162            }
2163        }
2164    }
2165
2166    private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) {
2167        DisplayManager displayManager = (DisplayManager) context.getSystemService(
2168                Context.DISPLAY_SERVICE);
2169        displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics);
2170    }
2171
2172    public PackageManagerService(Context context, Installer installer,
2173            boolean factoryTest, boolean onlyCore) {
2174        EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
2175                SystemClock.uptimeMillis());
2176
2177        if (mSdkVersion <= 0) {
2178            Slog.w(TAG, "**** ro.build.version.sdk not set!");
2179        }
2180
2181        mContext = context;
2182        mFactoryTest = factoryTest;
2183        mOnlyCore = onlyCore;
2184        mMetrics = new DisplayMetrics();
2185        mSettings = new Settings(mPackages);
2186        mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID,
2187                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2188        mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID,
2189                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2190        mSettings.addSharedUserLPw("android.uid.log", LOG_UID,
2191                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2192        mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID,
2193                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2194        mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID,
2195                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2196        mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID,
2197                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2198
2199        String separateProcesses = SystemProperties.get("debug.separate_processes");
2200        if (separateProcesses != null && separateProcesses.length() > 0) {
2201            if ("*".equals(separateProcesses)) {
2202                mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
2203                mSeparateProcesses = null;
2204                Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
2205            } else {
2206                mDefParseFlags = 0;
2207                mSeparateProcesses = separateProcesses.split(",");
2208                Slog.w(TAG, "Running with debug.separate_processes: "
2209                        + separateProcesses);
2210            }
2211        } else {
2212            mDefParseFlags = 0;
2213            mSeparateProcesses = null;
2214        }
2215
2216        mInstaller = installer;
2217        mPackageDexOptimizer = new PackageDexOptimizer(installer, mInstallLock, context,
2218                "*dexopt*");
2219        mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper());
2220
2221        mOnPermissionChangeListeners = new OnPermissionChangeListeners(
2222                FgThread.get().getLooper());
2223
2224        getDefaultDisplayMetrics(context, mMetrics);
2225
2226        SystemConfig systemConfig = SystemConfig.getInstance();
2227        mGlobalGids = systemConfig.getGlobalGids();
2228        mSystemPermissions = systemConfig.getSystemPermissions();
2229        mAvailableFeatures = systemConfig.getAvailableFeatures();
2230
2231        synchronized (mInstallLock) {
2232        // writer
2233        synchronized (mPackages) {
2234            mHandlerThread = new ServiceThread(TAG,
2235                    Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/);
2236            mHandlerThread.start();
2237            mHandler = new PackageHandler(mHandlerThread.getLooper());
2238            mProcessLoggingHandler = new ProcessLoggingHandler();
2239            Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT);
2240
2241            File dataDir = Environment.getDataDirectory();
2242            mAppInstallDir = new File(dataDir, "app");
2243            mAppLib32InstallDir = new File(dataDir, "app-lib");
2244            mEphemeralInstallDir = new File(dataDir, "app-ephemeral");
2245            mAsecInternalPath = new File(dataDir, "app-asec").getPath();
2246            mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
2247
2248            sUserManager = new UserManagerService(context, this, mPackages);
2249
2250            // Propagate permission configuration in to package manager.
2251            ArrayMap<String, SystemConfig.PermissionEntry> permConfig
2252                    = systemConfig.getPermissions();
2253            for (int i=0; i<permConfig.size(); i++) {
2254                SystemConfig.PermissionEntry perm = permConfig.valueAt(i);
2255                BasePermission bp = mSettings.mPermissions.get(perm.name);
2256                if (bp == null) {
2257                    bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN);
2258                    mSettings.mPermissions.put(perm.name, bp);
2259                }
2260                if (perm.gids != null) {
2261                    bp.setGids(perm.gids, perm.perUser);
2262                }
2263            }
2264
2265            ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries();
2266            for (int i=0; i<libConfig.size(); i++) {
2267                mSharedLibraries.put(libConfig.keyAt(i),
2268                        new SharedLibraryEntry(libConfig.valueAt(i), null));
2269            }
2270
2271            mFoundPolicyFile = SELinuxMMAC.readInstallPolicy();
2272
2273            mRestoredSettings = mSettings.readLPw(sUserManager.getUsers(false));
2274
2275            String customResolverActivity = Resources.getSystem().getString(
2276                    R.string.config_customResolverActivity);
2277            if (TextUtils.isEmpty(customResolverActivity)) {
2278                customResolverActivity = null;
2279            } else {
2280                mCustomResolverComponentName = ComponentName.unflattenFromString(
2281                        customResolverActivity);
2282            }
2283
2284            long startTime = SystemClock.uptimeMillis();
2285
2286            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
2287                    startTime);
2288
2289            // Set flag to monitor and not change apk file paths when
2290            // scanning install directories.
2291            final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING | SCAN_INITIAL;
2292
2293            final String bootClassPath = System.getenv("BOOTCLASSPATH");
2294            final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH");
2295
2296            if (bootClassPath == null) {
2297                Slog.w(TAG, "No BOOTCLASSPATH found!");
2298            }
2299
2300            if (systemServerClassPath == null) {
2301                Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!");
2302            }
2303
2304            final List<String> allInstructionSets = InstructionSets.getAllInstructionSets();
2305            final String[] dexCodeInstructionSets =
2306                    getDexCodeInstructionSets(
2307                            allInstructionSets.toArray(new String[allInstructionSets.size()]));
2308
2309            /**
2310             * Ensure all external libraries have had dexopt run on them.
2311             */
2312            if (mSharedLibraries.size() > 0) {
2313                // NOTE: For now, we're compiling these system "shared libraries"
2314                // (and framework jars) into all available architectures. It's possible
2315                // to compile them only when we come across an app that uses them (there's
2316                // already logic for that in scanPackageLI) but that adds some complexity.
2317                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
2318                    for (SharedLibraryEntry libEntry : mSharedLibraries.values()) {
2319                        final String lib = libEntry.path;
2320                        if (lib == null) {
2321                            continue;
2322                        }
2323
2324                        try {
2325                            // Shared libraries do not have profiles so we perform a full
2326                            // AOT compilation (if needed).
2327                            int dexoptNeeded = DexFile.getDexOptNeeded(
2328                                    lib, dexCodeInstructionSet,
2329                                    getCompilerFilterForReason(REASON_SHARED_APK),
2330                                    false /* newProfile */);
2331                            if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) {
2332                                mInstaller.dexopt(lib, Process.SYSTEM_UID, dexCodeInstructionSet,
2333                                        dexoptNeeded, DEXOPT_PUBLIC /*dexFlags*/,
2334                                        getCompilerFilterForReason(REASON_SHARED_APK),
2335                                        StorageManager.UUID_PRIVATE_INTERNAL);
2336                            }
2337                        } catch (FileNotFoundException e) {
2338                            Slog.w(TAG, "Library not found: " + lib);
2339                        } catch (IOException | InstallerException e) {
2340                            Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? "
2341                                    + e.getMessage());
2342                        }
2343                    }
2344                }
2345            }
2346
2347            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
2348
2349            final VersionInfo ver = mSettings.getInternalVersion();
2350            mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint);
2351
2352            // when upgrading from pre-M, promote system app permissions from install to runtime
2353            mPromoteSystemApps =
2354                    mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1;
2355
2356            // save off the names of pre-existing system packages prior to scanning; we don't
2357            // want to automatically grant runtime permissions for new system apps
2358            if (mPromoteSystemApps) {
2359                Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator();
2360                while (pkgSettingIter.hasNext()) {
2361                    PackageSetting ps = pkgSettingIter.next();
2362                    if (isSystemApp(ps)) {
2363                        mExistingSystemPackages.add(ps.name);
2364                    }
2365                }
2366            }
2367
2368            // When upgrading from pre-N, we need to handle package extraction like first boot,
2369            // as there is no profiling data available.
2370            mIsPreNUpgrade = !mSettings.isNWorkDone();
2371            mSettings.setNWorkDone();
2372
2373            // Collect vendor overlay packages.
2374            // (Do this before scanning any apps.)
2375            // For security and version matching reason, only consider
2376            // overlay packages if they reside in VENDOR_OVERLAY_DIR.
2377            File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR);
2378            scanDirTracedLI(vendorOverlayDir, mDefParseFlags
2379                    | PackageParser.PARSE_IS_SYSTEM
2380                    | PackageParser.PARSE_IS_SYSTEM_DIR
2381                    | PackageParser.PARSE_TRUSTED_OVERLAY, scanFlags | SCAN_TRUSTED_OVERLAY, 0);
2382
2383            // Find base frameworks (resource packages without code).
2384            scanDirTracedLI(frameworkDir, mDefParseFlags
2385                    | PackageParser.PARSE_IS_SYSTEM
2386                    | PackageParser.PARSE_IS_SYSTEM_DIR
2387                    | PackageParser.PARSE_IS_PRIVILEGED,
2388                    scanFlags | SCAN_NO_DEX, 0);
2389
2390            // Collected privileged system packages.
2391            final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
2392            scanDirTracedLI(privilegedAppDir, mDefParseFlags
2393                    | PackageParser.PARSE_IS_SYSTEM
2394                    | PackageParser.PARSE_IS_SYSTEM_DIR
2395                    | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0);
2396
2397            // Collect ordinary system packages.
2398            final File systemAppDir = new File(Environment.getRootDirectory(), "app");
2399            scanDirTracedLI(systemAppDir, mDefParseFlags
2400                    | PackageParser.PARSE_IS_SYSTEM
2401                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2402
2403            // Collect all vendor packages.
2404            File vendorAppDir = new File("/vendor/app");
2405            try {
2406                vendorAppDir = vendorAppDir.getCanonicalFile();
2407            } catch (IOException e) {
2408                // failed to look up canonical path, continue with original one
2409            }
2410            scanDirTracedLI(vendorAppDir, mDefParseFlags
2411                    | PackageParser.PARSE_IS_SYSTEM
2412                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2413
2414            // Collect all OEM packages.
2415            final File oemAppDir = new File(Environment.getOemDirectory(), "app");
2416            scanDirTracedLI(oemAppDir, mDefParseFlags
2417                    | PackageParser.PARSE_IS_SYSTEM
2418                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2419
2420            // Prune any system packages that no longer exist.
2421            final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>();
2422            if (!mOnlyCore) {
2423                Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
2424                while (psit.hasNext()) {
2425                    PackageSetting ps = psit.next();
2426
2427                    /*
2428                     * If this is not a system app, it can't be a
2429                     * disable system app.
2430                     */
2431                    if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
2432                        continue;
2433                    }
2434
2435                    /*
2436                     * If the package is scanned, it's not erased.
2437                     */
2438                    final PackageParser.Package scannedPkg = mPackages.get(ps.name);
2439                    if (scannedPkg != null) {
2440                        /*
2441                         * If the system app is both scanned and in the
2442                         * disabled packages list, then it must have been
2443                         * added via OTA. Remove it from the currently
2444                         * scanned package so the previously user-installed
2445                         * application can be scanned.
2446                         */
2447                        if (mSettings.isDisabledSystemPackageLPr(ps.name)) {
2448                            logCriticalInfo(Log.WARN, "Expecting better updated system app for "
2449                                    + ps.name + "; removing system app.  Last known codePath="
2450                                    + ps.codePathString + ", installStatus=" + ps.installStatus
2451                                    + ", versionCode=" + ps.versionCode + "; scanned versionCode="
2452                                    + scannedPkg.mVersionCode);
2453                            removePackageLI(scannedPkg, true);
2454                            mExpectingBetter.put(ps.name, ps.codePath);
2455                        }
2456
2457                        continue;
2458                    }
2459
2460                    if (!mSettings.isDisabledSystemPackageLPr(ps.name)) {
2461                        psit.remove();
2462                        logCriticalInfo(Log.WARN, "System package " + ps.name
2463                                + " no longer exists; it's data will be wiped");
2464                        // Actual deletion of code and data will be handled by later
2465                        // reconciliation step
2466                    } else {
2467                        final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name);
2468                        if (disabledPs.codePath == null || !disabledPs.codePath.exists()) {
2469                            possiblyDeletedUpdatedSystemApps.add(ps.name);
2470                        }
2471                    }
2472                }
2473            }
2474
2475            //look for any incomplete package installations
2476            ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr();
2477            for (int i = 0; i < deletePkgsList.size(); i++) {
2478                // Actual deletion of code and data will be handled by later
2479                // reconciliation step
2480                final String packageName = deletePkgsList.get(i).name;
2481                logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + packageName);
2482                synchronized (mPackages) {
2483                    mSettings.removePackageLPw(packageName);
2484                }
2485            }
2486
2487            //delete tmp files
2488            deleteTempPackageFiles();
2489
2490            // Remove any shared userIDs that have no associated packages
2491            mSettings.pruneSharedUsersLPw();
2492
2493            if (!mOnlyCore) {
2494                EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
2495                        SystemClock.uptimeMillis());
2496                scanDirTracedLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0);
2497
2498                scanDirTracedLI(mDrmAppPrivateInstallDir, mDefParseFlags
2499                        | PackageParser.PARSE_FORWARD_LOCK,
2500                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2501
2502                scanDirLI(mEphemeralInstallDir, mDefParseFlags
2503                        | PackageParser.PARSE_IS_EPHEMERAL,
2504                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2505
2506                /**
2507                 * Remove disable package settings for any updated system
2508                 * apps that were removed via an OTA. If they're not a
2509                 * previously-updated app, remove them completely.
2510                 * Otherwise, just revoke their system-level permissions.
2511                 */
2512                for (String deletedAppName : possiblyDeletedUpdatedSystemApps) {
2513                    PackageParser.Package deletedPkg = mPackages.get(deletedAppName);
2514                    mSettings.removeDisabledSystemPackageLPw(deletedAppName);
2515
2516                    String msg;
2517                    if (deletedPkg == null) {
2518                        msg = "Updated system package " + deletedAppName
2519                                + " no longer exists; it's data will be wiped";
2520                        // Actual deletion of code and data will be handled by later
2521                        // reconciliation step
2522                    } else {
2523                        msg = "Updated system app + " + deletedAppName
2524                                + " no longer present; removing system privileges for "
2525                                + deletedAppName;
2526
2527                        deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM;
2528
2529                        PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName);
2530                        deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM;
2531                    }
2532                    logCriticalInfo(Log.WARN, msg);
2533                }
2534
2535                /**
2536                 * Make sure all system apps that we expected to appear on
2537                 * the userdata partition actually showed up. If they never
2538                 * appeared, crawl back and revive the system version.
2539                 */
2540                for (int i = 0; i < mExpectingBetter.size(); i++) {
2541                    final String packageName = mExpectingBetter.keyAt(i);
2542                    if (!mPackages.containsKey(packageName)) {
2543                        final File scanFile = mExpectingBetter.valueAt(i);
2544
2545                        logCriticalInfo(Log.WARN, "Expected better " + packageName
2546                                + " but never showed up; reverting to system");
2547
2548                        int reparseFlags = mDefParseFlags;
2549                        if (FileUtils.contains(privilegedAppDir, scanFile)) {
2550                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2551                                    | PackageParser.PARSE_IS_SYSTEM_DIR
2552                                    | PackageParser.PARSE_IS_PRIVILEGED;
2553                        } else if (FileUtils.contains(systemAppDir, scanFile)) {
2554                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2555                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2556                        } else if (FileUtils.contains(vendorAppDir, scanFile)) {
2557                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2558                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2559                        } else if (FileUtils.contains(oemAppDir, scanFile)) {
2560                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2561                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2562                        } else {
2563                            Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile);
2564                            continue;
2565                        }
2566
2567                        mSettings.enableSystemPackageLPw(packageName);
2568
2569                        try {
2570                            scanPackageTracedLI(scanFile, reparseFlags, scanFlags, 0, null);
2571                        } catch (PackageManagerException e) {
2572                            Slog.e(TAG, "Failed to parse original system package: "
2573                                    + e.getMessage());
2574                        }
2575                    }
2576                }
2577            }
2578            mExpectingBetter.clear();
2579
2580            // Resolve protected action filters. Only the setup wizard is allowed to
2581            // have a high priority filter for these actions.
2582            mSetupWizardPackage = getSetupWizardPackageName();
2583            if (mProtectedFilters.size() > 0) {
2584                if (DEBUG_FILTERS && mSetupWizardPackage == null) {
2585                    Slog.i(TAG, "No setup wizard;"
2586                        + " All protected intents capped to priority 0");
2587                }
2588                for (ActivityIntentInfo filter : mProtectedFilters) {
2589                    if (filter.activity.info.packageName.equals(mSetupWizardPackage)) {
2590                        if (DEBUG_FILTERS) {
2591                            Slog.i(TAG, "Found setup wizard;"
2592                                + " allow priority " + filter.getPriority() + ";"
2593                                + " package: " + filter.activity.info.packageName
2594                                + " activity: " + filter.activity.className
2595                                + " priority: " + filter.getPriority());
2596                        }
2597                        // skip setup wizard; allow it to keep the high priority filter
2598                        continue;
2599                    }
2600                    Slog.w(TAG, "Protected action; cap priority to 0;"
2601                            + " package: " + filter.activity.info.packageName
2602                            + " activity: " + filter.activity.className
2603                            + " origPrio: " + filter.getPriority());
2604                    filter.setPriority(0);
2605                }
2606            }
2607            mDeferProtectedFilters = false;
2608            mProtectedFilters.clear();
2609
2610            // Now that we know all of the shared libraries, update all clients to have
2611            // the correct library paths.
2612            updateAllSharedLibrariesLPw();
2613
2614            for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) {
2615                // NOTE: We ignore potential failures here during a system scan (like
2616                // the rest of the commands above) because there's precious little we
2617                // can do about it. A settings error is reported, though.
2618                adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */,
2619                        false /* boot complete */);
2620            }
2621
2622            // Now that we know all the packages we are keeping,
2623            // read and update their last usage times.
2624            mPackageUsage.readLP();
2625
2626            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
2627                    SystemClock.uptimeMillis());
2628            Slog.i(TAG, "Time to scan packages: "
2629                    + ((SystemClock.uptimeMillis()-startTime)/1000f)
2630                    + " seconds");
2631
2632            // If the platform SDK has changed since the last time we booted,
2633            // we need to re-grant app permission to catch any new ones that
2634            // appear.  This is really a hack, and means that apps can in some
2635            // cases get permissions that the user didn't initially explicitly
2636            // allow...  it would be nice to have some better way to handle
2637            // this situation.
2638            int updateFlags = UPDATE_PERMISSIONS_ALL;
2639            if (ver.sdkVersion != mSdkVersion) {
2640                Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to "
2641                        + mSdkVersion + "; regranting permissions for internal storage");
2642                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
2643            }
2644            updatePermissionsLPw(null, null, StorageManager.UUID_PRIVATE_INTERNAL, updateFlags);
2645            ver.sdkVersion = mSdkVersion;
2646
2647            // If this is the first boot or an update from pre-M, and it is a normal
2648            // boot, then we need to initialize the default preferred apps across
2649            // all defined users.
2650            if (!onlyCore && (mPromoteSystemApps || !mRestoredSettings)) {
2651                for (UserInfo user : sUserManager.getUsers(true)) {
2652                    mSettings.applyDefaultPreferredAppsLPw(this, user.id);
2653                    applyFactoryDefaultBrowserLPw(user.id);
2654                    primeDomainVerificationsLPw(user.id);
2655                }
2656            }
2657
2658            // Prepare storage for system user really early during boot,
2659            // since core system apps like SettingsProvider and SystemUI
2660            // can't wait for user to start
2661            final int storageFlags;
2662            if (StorageManager.isFileEncryptedNativeOrEmulated()) {
2663                storageFlags = StorageManager.FLAG_STORAGE_DE;
2664            } else {
2665                storageFlags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
2666            }
2667            reconcileAppsDataLI(StorageManager.UUID_PRIVATE_INTERNAL, UserHandle.USER_SYSTEM,
2668                    storageFlags);
2669
2670            // If this is first boot after an OTA, and a normal boot, then
2671            // we need to clear code cache directories.
2672            if (mIsUpgrade && !onlyCore) {
2673                Slog.i(TAG, "Build fingerprint changed; clearing code caches");
2674                for (int i = 0; i < mSettings.mPackages.size(); i++) {
2675                    final PackageSetting ps = mSettings.mPackages.valueAt(i);
2676                    if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) {
2677                        // No apps are running this early, so no need to freeze
2678                        clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
2679                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
2680                                        | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
2681                    }
2682                    clearAppProfilesLIF(ps.pkg);
2683                }
2684                ver.fingerprint = Build.FINGERPRINT;
2685            }
2686
2687            checkDefaultBrowser();
2688
2689            // clear only after permissions and other defaults have been updated
2690            mExistingSystemPackages.clear();
2691            mPromoteSystemApps = false;
2692
2693            // All the changes are done during package scanning.
2694            ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION;
2695
2696            // can downgrade to reader
2697            mSettings.writeLPr();
2698
2699            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
2700                    SystemClock.uptimeMillis());
2701
2702            if (!mOnlyCore) {
2703                mRequiredVerifierPackage = getRequiredButNotReallyRequiredVerifierLPr();
2704                mRequiredInstallerPackage = getRequiredInstallerLPr();
2705                mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr();
2706                mIntentFilterVerifier = new IntentVerifierProxy(mContext,
2707                        mIntentFilterVerifierComponent);
2708                mServicesSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
2709                        PackageManager.SYSTEM_SHARED_LIBRARY_SERVICES);
2710                mSharedSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
2711                        PackageManager.SYSTEM_SHARED_LIBRARY_SHARED);
2712            } else {
2713                mRequiredVerifierPackage = null;
2714                mRequiredInstallerPackage = null;
2715                mIntentFilterVerifierComponent = null;
2716                mIntentFilterVerifier = null;
2717                mServicesSystemSharedLibraryPackageName = null;
2718                mSharedSystemSharedLibraryPackageName = null;
2719            }
2720
2721            mInstallerService = new PackageInstallerService(context, this);
2722
2723            final ComponentName ephemeralResolverComponent = getEphemeralResolverLPr();
2724            final ComponentName ephemeralInstallerComponent = getEphemeralInstallerLPr();
2725            // both the installer and resolver must be present to enable ephemeral
2726            if (ephemeralInstallerComponent != null && ephemeralResolverComponent != null) {
2727                if (DEBUG_EPHEMERAL) {
2728                    Slog.i(TAG, "Ephemeral activated; resolver: " + ephemeralResolverComponent
2729                            + " installer:" + ephemeralInstallerComponent);
2730                }
2731                mEphemeralResolverComponent = ephemeralResolverComponent;
2732                mEphemeralInstallerComponent = ephemeralInstallerComponent;
2733                setUpEphemeralInstallerActivityLP(mEphemeralInstallerComponent);
2734                mEphemeralResolverConnection =
2735                        new EphemeralResolverConnection(mContext, mEphemeralResolverComponent);
2736            } else {
2737                if (DEBUG_EPHEMERAL) {
2738                    final String missingComponent =
2739                            (ephemeralResolverComponent == null)
2740                            ? (ephemeralInstallerComponent == null)
2741                                    ? "resolver and installer"
2742                                    : "resolver"
2743                            : "installer";
2744                    Slog.i(TAG, "Ephemeral deactivated; missing " + missingComponent);
2745                }
2746                mEphemeralResolverComponent = null;
2747                mEphemeralInstallerComponent = null;
2748                mEphemeralResolverConnection = null;
2749            }
2750
2751            mEphemeralApplicationRegistry = new EphemeralApplicationRegistry(this);
2752        } // synchronized (mPackages)
2753        } // synchronized (mInstallLock)
2754
2755        // Now after opening every single application zip, make sure they
2756        // are all flushed.  Not really needed, but keeps things nice and
2757        // tidy.
2758        Runtime.getRuntime().gc();
2759
2760        // The initial scanning above does many calls into installd while
2761        // holding the mPackages lock, but we're mostly interested in yelling
2762        // once we have a booted system.
2763        mInstaller.setWarnIfHeld(mPackages);
2764
2765        // Expose private service for system components to use.
2766        LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl());
2767    }
2768
2769    @Override
2770    public boolean isFirstBoot() {
2771        return !mRestoredSettings;
2772    }
2773
2774    @Override
2775    public boolean isOnlyCoreApps() {
2776        return mOnlyCore;
2777    }
2778
2779    @Override
2780    public boolean isUpgrade() {
2781        return mIsUpgrade;
2782    }
2783
2784    private @Nullable String getRequiredButNotReallyRequiredVerifierLPr() {
2785        final Intent intent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
2786
2787        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
2788                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
2789                UserHandle.USER_SYSTEM);
2790        if (matches.size() == 1) {
2791            return matches.get(0).getComponentInfo().packageName;
2792        } else {
2793            Log.e(TAG, "There should probably be exactly one verifier; found " + matches);
2794            return null;
2795        }
2796    }
2797
2798    private @NonNull String getRequiredSharedLibraryLPr(String libraryName) {
2799        synchronized (mPackages) {
2800            SharedLibraryEntry libraryEntry = mSharedLibraries.get(libraryName);
2801            if (libraryEntry == null) {
2802                throw new IllegalStateException("Missing required shared library:" + libraryName);
2803            }
2804            return libraryEntry.apk;
2805        }
2806    }
2807
2808    private @NonNull String getRequiredInstallerLPr() {
2809        final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
2810        intent.addCategory(Intent.CATEGORY_DEFAULT);
2811        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
2812
2813        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
2814                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
2815                UserHandle.USER_SYSTEM);
2816        if (matches.size() == 1) {
2817            ResolveInfo resolveInfo = matches.get(0);
2818            if (!resolveInfo.activityInfo.applicationInfo.isPrivilegedApp()) {
2819                throw new RuntimeException("The installer must be a privileged app");
2820            }
2821            return matches.get(0).getComponentInfo().packageName;
2822        } else {
2823            throw new RuntimeException("There must be exactly one installer; found " + matches);
2824        }
2825    }
2826
2827    private @NonNull ComponentName getIntentFilterVerifierComponentNameLPr() {
2828        final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
2829
2830        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
2831                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
2832                UserHandle.USER_SYSTEM);
2833        ResolveInfo best = null;
2834        final int N = matches.size();
2835        for (int i = 0; i < N; i++) {
2836            final ResolveInfo cur = matches.get(i);
2837            final String packageName = cur.getComponentInfo().packageName;
2838            if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
2839                    packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) {
2840                continue;
2841            }
2842
2843            if (best == null || cur.priority > best.priority) {
2844                best = cur;
2845            }
2846        }
2847
2848        if (best != null) {
2849            return best.getComponentInfo().getComponentName();
2850        } else {
2851            throw new RuntimeException("There must be at least one intent filter verifier");
2852        }
2853    }
2854
2855    private @Nullable ComponentName getEphemeralResolverLPr() {
2856        final String[] packageArray =
2857                mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage);
2858        if (packageArray.length == 0) {
2859            if (DEBUG_EPHEMERAL) {
2860                Slog.d(TAG, "Ephemeral resolver NOT found; empty package list");
2861            }
2862            return null;
2863        }
2864
2865        final Intent resolverIntent = new Intent(Intent.ACTION_RESOLVE_EPHEMERAL_PACKAGE);
2866        final List<ResolveInfo> resolvers = queryIntentServicesInternal(resolverIntent, null,
2867                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
2868                UserHandle.USER_SYSTEM);
2869
2870        final int N = resolvers.size();
2871        if (N == 0) {
2872            if (DEBUG_EPHEMERAL) {
2873                Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters");
2874            }
2875            return null;
2876        }
2877
2878        final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray));
2879        for (int i = 0; i < N; i++) {
2880            final ResolveInfo info = resolvers.get(i);
2881
2882            if (info.serviceInfo == null) {
2883                continue;
2884            }
2885
2886            final String packageName = info.serviceInfo.packageName;
2887            if (!possiblePackages.contains(packageName)) {
2888                if (DEBUG_EPHEMERAL) {
2889                    Slog.d(TAG, "Ephemeral resolver not in allowed package list;"
2890                            + " pkg: " + packageName + ", info:" + info);
2891                }
2892                continue;
2893            }
2894
2895            if (DEBUG_EPHEMERAL) {
2896                Slog.v(TAG, "Ephemeral resolver found;"
2897                        + " pkg: " + packageName + ", info:" + info);
2898            }
2899            return new ComponentName(packageName, info.serviceInfo.name);
2900        }
2901        if (DEBUG_EPHEMERAL) {
2902            Slog.v(TAG, "Ephemeral resolver NOT found");
2903        }
2904        return null;
2905    }
2906
2907    private @Nullable ComponentName getEphemeralInstallerLPr() {
2908        final Intent intent = new Intent(Intent.ACTION_INSTALL_EPHEMERAL_PACKAGE);
2909        intent.addCategory(Intent.CATEGORY_DEFAULT);
2910        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
2911
2912        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
2913                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
2914                UserHandle.USER_SYSTEM);
2915        if (matches.size() == 0) {
2916            return null;
2917        } else if (matches.size() == 1) {
2918            return matches.get(0).getComponentInfo().getComponentName();
2919        } else {
2920            throw new RuntimeException(
2921                    "There must be at most one ephemeral installer; found " + matches);
2922        }
2923    }
2924
2925    private void primeDomainVerificationsLPw(int userId) {
2926        if (DEBUG_DOMAIN_VERIFICATION) {
2927            Slog.d(TAG, "Priming domain verifications in user " + userId);
2928        }
2929
2930        SystemConfig systemConfig = SystemConfig.getInstance();
2931        ArraySet<String> packages = systemConfig.getLinkedApps();
2932        ArraySet<String> domains = new ArraySet<String>();
2933
2934        for (String packageName : packages) {
2935            PackageParser.Package pkg = mPackages.get(packageName);
2936            if (pkg != null) {
2937                if (!pkg.isSystemApp()) {
2938                    Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>");
2939                    continue;
2940                }
2941
2942                domains.clear();
2943                for (PackageParser.Activity a : pkg.activities) {
2944                    for (ActivityIntentInfo filter : a.intents) {
2945                        if (hasValidDomains(filter)) {
2946                            domains.addAll(filter.getHostsList());
2947                        }
2948                    }
2949                }
2950
2951                if (domains.size() > 0) {
2952                    if (DEBUG_DOMAIN_VERIFICATION) {
2953                        Slog.v(TAG, "      + " + packageName);
2954                    }
2955                    // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual
2956                    // state w.r.t. the formal app-linkage "no verification attempted" state;
2957                    // and then 'always' in the per-user state actually used for intent resolution.
2958                    final IntentFilterVerificationInfo ivi;
2959                    ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName,
2960                            new ArrayList<String>(domains));
2961                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED);
2962                    mSettings.updateIntentFilterVerificationStatusLPw(packageName,
2963                            INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId);
2964                } else {
2965                    Slog.w(TAG, "Sysconfig <app-link> package '" + packageName
2966                            + "' does not handle web links");
2967                }
2968            } else {
2969                Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>");
2970            }
2971        }
2972
2973        scheduleWritePackageRestrictionsLocked(userId);
2974        scheduleWriteSettingsLocked();
2975    }
2976
2977    private void applyFactoryDefaultBrowserLPw(int userId) {
2978        // The default browser app's package name is stored in a string resource,
2979        // with a product-specific overlay used for vendor customization.
2980        String browserPkg = mContext.getResources().getString(
2981                com.android.internal.R.string.default_browser);
2982        if (!TextUtils.isEmpty(browserPkg)) {
2983            // non-empty string => required to be a known package
2984            PackageSetting ps = mSettings.mPackages.get(browserPkg);
2985            if (ps == null) {
2986                Slog.e(TAG, "Product default browser app does not exist: " + browserPkg);
2987                browserPkg = null;
2988            } else {
2989                mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
2990            }
2991        }
2992
2993        // Nothing valid explicitly set? Make the factory-installed browser the explicit
2994        // default.  If there's more than one, just leave everything alone.
2995        if (browserPkg == null) {
2996            calculateDefaultBrowserLPw(userId);
2997        }
2998    }
2999
3000    private void calculateDefaultBrowserLPw(int userId) {
3001        List<String> allBrowsers = resolveAllBrowserApps(userId);
3002        final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null;
3003        mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
3004    }
3005
3006    private List<String> resolveAllBrowserApps(int userId) {
3007        // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set
3008        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
3009                PackageManager.MATCH_ALL, userId);
3010
3011        final int count = list.size();
3012        List<String> result = new ArrayList<String>(count);
3013        for (int i=0; i<count; i++) {
3014            ResolveInfo info = list.get(i);
3015            if (info.activityInfo == null
3016                    || !info.handleAllWebDataURI
3017                    || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0
3018                    || result.contains(info.activityInfo.packageName)) {
3019                continue;
3020            }
3021            result.add(info.activityInfo.packageName);
3022        }
3023
3024        return result;
3025    }
3026
3027    private boolean packageIsBrowser(String packageName, int userId) {
3028        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
3029                PackageManager.MATCH_ALL, userId);
3030        final int N = list.size();
3031        for (int i = 0; i < N; i++) {
3032            ResolveInfo info = list.get(i);
3033            if (packageName.equals(info.activityInfo.packageName)) {
3034                return true;
3035            }
3036        }
3037        return false;
3038    }
3039
3040    private void checkDefaultBrowser() {
3041        final int myUserId = UserHandle.myUserId();
3042        final String packageName = getDefaultBrowserPackageName(myUserId);
3043        if (packageName != null) {
3044            PackageInfo info = getPackageInfo(packageName, 0, myUserId);
3045            if (info == null) {
3046                Slog.w(TAG, "Default browser no longer installed: " + packageName);
3047                synchronized (mPackages) {
3048                    applyFactoryDefaultBrowserLPw(myUserId);    // leaves ambiguous when > 1
3049                }
3050            }
3051        }
3052    }
3053
3054    @Override
3055    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
3056            throws RemoteException {
3057        try {
3058            return super.onTransact(code, data, reply, flags);
3059        } catch (RuntimeException e) {
3060            if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
3061                Slog.wtf(TAG, "Package Manager Crash", e);
3062            }
3063            throw e;
3064        }
3065    }
3066
3067    static int[] appendInts(int[] cur, int[] add) {
3068        if (add == null) return cur;
3069        if (cur == null) return add;
3070        final int N = add.length;
3071        for (int i=0; i<N; i++) {
3072            cur = appendInt(cur, add[i]);
3073        }
3074        return cur;
3075    }
3076
3077    private PackageInfo generatePackageInfo(PackageSetting ps, int flags, int userId) {
3078        if (!sUserManager.exists(userId)) return null;
3079        if (ps == null) {
3080            return null;
3081        }
3082        final PackageParser.Package p = ps.pkg;
3083        if (p == null) {
3084            return null;
3085        }
3086
3087        final PermissionsState permissionsState = ps.getPermissionsState();
3088
3089        final int[] gids = permissionsState.computeGids(userId);
3090        final Set<String> permissions = permissionsState.getPermissions(userId);
3091        final PackageUserState state = ps.readUserState(userId);
3092
3093        return PackageParser.generatePackageInfo(p, gids, flags,
3094                ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId);
3095    }
3096
3097    @Override
3098    public void checkPackageStartable(String packageName, int userId) {
3099        final boolean userKeyUnlocked = isUserKeyUnlocked(userId);
3100
3101        synchronized (mPackages) {
3102            final PackageSetting ps = mSettings.mPackages.get(packageName);
3103            if (ps == null) {
3104                throw new SecurityException("Package " + packageName + " was not found!");
3105            }
3106
3107            if (!ps.getInstalled(userId)) {
3108                throw new SecurityException(
3109                        "Package " + packageName + " was not installed for user " + userId + "!");
3110            }
3111
3112            if (mSafeMode && !ps.isSystem()) {
3113                throw new SecurityException("Package " + packageName + " not a system app!");
3114            }
3115
3116            if (mFrozenPackages.contains(packageName)) {
3117                throw new SecurityException("Package " + packageName + " is currently frozen!");
3118            }
3119
3120            if (!userKeyUnlocked && !(ps.pkg.applicationInfo.isDirectBootAware()
3121                    || ps.pkg.applicationInfo.isPartiallyDirectBootAware())) {
3122                throw new SecurityException("Package " + packageName + " is not encryption aware!");
3123            }
3124        }
3125    }
3126
3127    @Override
3128    public boolean isPackageAvailable(String packageName, int userId) {
3129        if (!sUserManager.exists(userId)) return false;
3130        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3131                false /* requireFullPermission */, false /* checkShell */, "is package available");
3132        synchronized (mPackages) {
3133            PackageParser.Package p = mPackages.get(packageName);
3134            if (p != null) {
3135                final PackageSetting ps = (PackageSetting) p.mExtras;
3136                if (ps != null) {
3137                    final PackageUserState state = ps.readUserState(userId);
3138                    if (state != null) {
3139                        return PackageParser.isAvailable(state);
3140                    }
3141                }
3142            }
3143        }
3144        return false;
3145    }
3146
3147    @Override
3148    public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
3149        if (!sUserManager.exists(userId)) return null;
3150        flags = updateFlagsForPackage(flags, userId, packageName);
3151        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3152                false /* requireFullPermission */, false /* checkShell */, "get package info");
3153        // reader
3154        synchronized (mPackages) {
3155            final boolean matchFactoryOnly = (flags & MATCH_FACTORY_ONLY) != 0;
3156            PackageParser.Package p = null;
3157            if (matchFactoryOnly) {
3158                final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName);
3159                if (ps != null) {
3160                    return generatePackageInfo(ps, flags, userId);
3161                }
3162            }
3163            if (p == null) {
3164                p = mPackages.get(packageName);
3165                if (matchFactoryOnly && p != null && !isSystemApp(p)) {
3166                    return null;
3167                }
3168            }
3169            if (DEBUG_PACKAGE_INFO)
3170                Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
3171            if (p != null) {
3172                return generatePackageInfo((PackageSetting)p.mExtras, flags, userId);
3173            }
3174            if (!matchFactoryOnly && (flags & MATCH_UNINSTALLED_PACKAGES) != 0) {
3175                final PackageSetting ps = mSettings.mPackages.get(packageName);
3176                return generatePackageInfo(ps, flags, userId);
3177            }
3178        }
3179        return null;
3180    }
3181
3182    @Override
3183    public String[] currentToCanonicalPackageNames(String[] names) {
3184        String[] out = new String[names.length];
3185        // reader
3186        synchronized (mPackages) {
3187            for (int i=names.length-1; i>=0; i--) {
3188                PackageSetting ps = mSettings.mPackages.get(names[i]);
3189                out[i] = ps != null && ps.realName != null ? ps.realName : names[i];
3190            }
3191        }
3192        return out;
3193    }
3194
3195    @Override
3196    public String[] canonicalToCurrentPackageNames(String[] names) {
3197        String[] out = new String[names.length];
3198        // reader
3199        synchronized (mPackages) {
3200            for (int i=names.length-1; i>=0; i--) {
3201                String cur = mSettings.mRenamedPackages.get(names[i]);
3202                out[i] = cur != null ? cur : names[i];
3203            }
3204        }
3205        return out;
3206    }
3207
3208    @Override
3209    public int getPackageUid(String packageName, int flags, int userId) {
3210        if (!sUserManager.exists(userId)) return -1;
3211        flags = updateFlagsForPackage(flags, userId, packageName);
3212        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3213                false /* requireFullPermission */, false /* checkShell */, "get package uid");
3214
3215        // reader
3216        synchronized (mPackages) {
3217            final PackageParser.Package p = mPackages.get(packageName);
3218            if (p != null && p.isMatch(flags)) {
3219                return UserHandle.getUid(userId, p.applicationInfo.uid);
3220            }
3221            if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) {
3222                final PackageSetting ps = mSettings.mPackages.get(packageName);
3223                if (ps != null && ps.isMatch(flags)) {
3224                    return UserHandle.getUid(userId, ps.appId);
3225                }
3226            }
3227        }
3228
3229        return -1;
3230    }
3231
3232    @Override
3233    public int[] getPackageGids(String packageName, int flags, int userId) {
3234        if (!sUserManager.exists(userId)) return null;
3235        flags = updateFlagsForPackage(flags, userId, packageName);
3236        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3237                false /* requireFullPermission */, false /* checkShell */,
3238                "getPackageGids");
3239
3240        // reader
3241        synchronized (mPackages) {
3242            final PackageParser.Package p = mPackages.get(packageName);
3243            if (p != null && p.isMatch(flags)) {
3244                PackageSetting ps = (PackageSetting) p.mExtras;
3245                return ps.getPermissionsState().computeGids(userId);
3246            }
3247            if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) {
3248                final PackageSetting ps = mSettings.mPackages.get(packageName);
3249                if (ps != null && ps.isMatch(flags)) {
3250                    return ps.getPermissionsState().computeGids(userId);
3251                }
3252            }
3253        }
3254
3255        return null;
3256    }
3257
3258    static PermissionInfo generatePermissionInfo(BasePermission bp, int flags) {
3259        if (bp.perm != null) {
3260            return PackageParser.generatePermissionInfo(bp.perm, flags);
3261        }
3262        PermissionInfo pi = new PermissionInfo();
3263        pi.name = bp.name;
3264        pi.packageName = bp.sourcePackage;
3265        pi.nonLocalizedLabel = bp.name;
3266        pi.protectionLevel = bp.protectionLevel;
3267        return pi;
3268    }
3269
3270    @Override
3271    public PermissionInfo getPermissionInfo(String name, int flags) {
3272        // reader
3273        synchronized (mPackages) {
3274            final BasePermission p = mSettings.mPermissions.get(name);
3275            if (p != null) {
3276                return generatePermissionInfo(p, flags);
3277            }
3278            return null;
3279        }
3280    }
3281
3282    @Override
3283    public @Nullable ParceledListSlice<PermissionInfo> queryPermissionsByGroup(String group,
3284            int flags) {
3285        // reader
3286        synchronized (mPackages) {
3287            if (group != null && !mPermissionGroups.containsKey(group)) {
3288                // This is thrown as NameNotFoundException
3289                return null;
3290            }
3291
3292            ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
3293            for (BasePermission p : mSettings.mPermissions.values()) {
3294                if (group == null) {
3295                    if (p.perm == null || p.perm.info.group == null) {
3296                        out.add(generatePermissionInfo(p, flags));
3297                    }
3298                } else {
3299                    if (p.perm != null && group.equals(p.perm.info.group)) {
3300                        out.add(PackageParser.generatePermissionInfo(p.perm, flags));
3301                    }
3302                }
3303            }
3304            return new ParceledListSlice<>(out);
3305        }
3306    }
3307
3308    @Override
3309    public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
3310        // reader
3311        synchronized (mPackages) {
3312            return PackageParser.generatePermissionGroupInfo(
3313                    mPermissionGroups.get(name), flags);
3314        }
3315    }
3316
3317    @Override
3318    public @NonNull ParceledListSlice<PermissionGroupInfo> getAllPermissionGroups(int flags) {
3319        // reader
3320        synchronized (mPackages) {
3321            final int N = mPermissionGroups.size();
3322            ArrayList<PermissionGroupInfo> out
3323                    = new ArrayList<PermissionGroupInfo>(N);
3324            for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
3325                out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
3326            }
3327            return new ParceledListSlice<>(out);
3328        }
3329    }
3330
3331    private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
3332            int userId) {
3333        if (!sUserManager.exists(userId)) return null;
3334        PackageSetting ps = mSettings.mPackages.get(packageName);
3335        if (ps != null) {
3336            if (ps.pkg == null) {
3337                final PackageInfo pInfo = generatePackageInfo(ps, flags, userId);
3338                if (pInfo != null) {
3339                    return pInfo.applicationInfo;
3340                }
3341                return null;
3342            }
3343            return PackageParser.generateApplicationInfo(ps.pkg, flags,
3344                    ps.readUserState(userId), userId);
3345        }
3346        return null;
3347    }
3348
3349    @Override
3350    public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
3351        if (!sUserManager.exists(userId)) return null;
3352        flags = updateFlagsForApplication(flags, userId, packageName);
3353        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3354                false /* requireFullPermission */, false /* checkShell */, "get application info");
3355        // writer
3356        synchronized (mPackages) {
3357            PackageParser.Package p = mPackages.get(packageName);
3358            if (DEBUG_PACKAGE_INFO) Log.v(
3359                    TAG, "getApplicationInfo " + packageName
3360                    + ": " + p);
3361            if (p != null) {
3362                PackageSetting ps = mSettings.mPackages.get(packageName);
3363                if (ps == null) return null;
3364                // Note: isEnabledLP() does not apply here - always return info
3365                return PackageParser.generateApplicationInfo(
3366                        p, flags, ps.readUserState(userId), userId);
3367            }
3368            if ("android".equals(packageName)||"system".equals(packageName)) {
3369                return mAndroidApplication;
3370            }
3371            if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) {
3372                return generateApplicationInfoFromSettingsLPw(packageName, flags, userId);
3373            }
3374        }
3375        return null;
3376    }
3377
3378    @Override
3379    public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize,
3380            final IPackageDataObserver observer) {
3381        mContext.enforceCallingOrSelfPermission(
3382                android.Manifest.permission.CLEAR_APP_CACHE, null);
3383        // Queue up an async operation since clearing cache may take a little while.
3384        mHandler.post(new Runnable() {
3385            public void run() {
3386                mHandler.removeCallbacks(this);
3387                boolean success = true;
3388                synchronized (mInstallLock) {
3389                    try {
3390                        mInstaller.freeCache(volumeUuid, freeStorageSize);
3391                    } catch (InstallerException e) {
3392                        Slog.w(TAG, "Couldn't clear application caches: " + e);
3393                        success = false;
3394                    }
3395                }
3396                if (observer != null) {
3397                    try {
3398                        observer.onRemoveCompleted(null, success);
3399                    } catch (RemoteException e) {
3400                        Slog.w(TAG, "RemoveException when invoking call back");
3401                    }
3402                }
3403            }
3404        });
3405    }
3406
3407    @Override
3408    public void freeStorage(final String volumeUuid, final long freeStorageSize,
3409            final IntentSender pi) {
3410        mContext.enforceCallingOrSelfPermission(
3411                android.Manifest.permission.CLEAR_APP_CACHE, null);
3412        // Queue up an async operation since clearing cache may take a little while.
3413        mHandler.post(new Runnable() {
3414            public void run() {
3415                mHandler.removeCallbacks(this);
3416                boolean success = true;
3417                synchronized (mInstallLock) {
3418                    try {
3419                        mInstaller.freeCache(volumeUuid, freeStorageSize);
3420                    } catch (InstallerException e) {
3421                        Slog.w(TAG, "Couldn't clear application caches: " + e);
3422                        success = false;
3423                    }
3424                }
3425                if(pi != null) {
3426                    try {
3427                        // Callback via pending intent
3428                        int code = success ? 1 : 0;
3429                        pi.sendIntent(null, code, null,
3430                                null, null);
3431                    } catch (SendIntentException e1) {
3432                        Slog.i(TAG, "Failed to send pending intent");
3433                    }
3434                }
3435            }
3436        });
3437    }
3438
3439    void freeStorage(String volumeUuid, long freeStorageSize) throws IOException {
3440        synchronized (mInstallLock) {
3441            try {
3442                mInstaller.freeCache(volumeUuid, freeStorageSize);
3443            } catch (InstallerException e) {
3444                throw new IOException("Failed to free enough space", e);
3445            }
3446        }
3447    }
3448
3449    /**
3450     * Return if the user key is currently unlocked.
3451     */
3452    private boolean isUserKeyUnlocked(int userId) {
3453        if (StorageManager.isFileEncryptedNativeOrEmulated()) {
3454            final IMountService mount = IMountService.Stub
3455                    .asInterface(ServiceManager.getService("mount"));
3456            if (mount == null) {
3457                Slog.w(TAG, "Early during boot, assuming locked");
3458                return false;
3459            }
3460            final long token = Binder.clearCallingIdentity();
3461            try {
3462                return mount.isUserKeyUnlocked(userId);
3463            } catch (RemoteException e) {
3464                throw e.rethrowAsRuntimeException();
3465            } finally {
3466                Binder.restoreCallingIdentity(token);
3467            }
3468        } else {
3469            return true;
3470        }
3471    }
3472
3473    /**
3474     * Update given flags based on encryption status of current user.
3475     */
3476    private int updateFlags(int flags, int userId) {
3477        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
3478                | PackageManager.MATCH_DIRECT_BOOT_AWARE)) != 0) {
3479            // Caller expressed an explicit opinion about what encryption
3480            // aware/unaware components they want to see, so fall through and
3481            // give them what they want
3482        } else {
3483            // Caller expressed no opinion, so match based on user state
3484            if (isUserKeyUnlocked(userId)) {
3485                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE;
3486            } else {
3487                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE;
3488            }
3489        }
3490        return flags;
3491    }
3492
3493    /**
3494     * Update given flags when being used to request {@link PackageInfo}.
3495     */
3496    private int updateFlagsForPackage(int flags, int userId, Object cookie) {
3497        boolean triaged = true;
3498        if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS
3499                | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) {
3500            // Caller is asking for component details, so they'd better be
3501            // asking for specific encryption matching behavior, or be triaged
3502            if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
3503                    | PackageManager.MATCH_DIRECT_BOOT_AWARE
3504                    | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
3505                triaged = false;
3506            }
3507        }
3508        if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES
3509                | PackageManager.MATCH_SYSTEM_ONLY
3510                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
3511            triaged = false;
3512        }
3513        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
3514            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
3515                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
3516        }
3517        return updateFlags(flags, userId);
3518    }
3519
3520    /**
3521     * Update given flags when being used to request {@link ApplicationInfo}.
3522     */
3523    private int updateFlagsForApplication(int flags, int userId, Object cookie) {
3524        return updateFlagsForPackage(flags, userId, cookie);
3525    }
3526
3527    /**
3528     * Update given flags when being used to request {@link ComponentInfo}.
3529     */
3530    private int updateFlagsForComponent(int flags, int userId, Object cookie) {
3531        if (cookie instanceof Intent) {
3532            if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) {
3533                flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
3534            }
3535        }
3536
3537        boolean triaged = true;
3538        // Caller is asking for component details, so they'd better be
3539        // asking for specific encryption matching behavior, or be triaged
3540        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
3541                | PackageManager.MATCH_DIRECT_BOOT_AWARE
3542                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
3543            triaged = false;
3544        }
3545        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
3546            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
3547                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
3548        }
3549
3550        return updateFlags(flags, userId);
3551    }
3552
3553    /**
3554     * Update given flags when being used to request {@link ResolveInfo}.
3555     */
3556    int updateFlagsForResolve(int flags, int userId, Object cookie) {
3557        // Safe mode means we shouldn't match any third-party components
3558        if (mSafeMode) {
3559            flags |= PackageManager.MATCH_SYSTEM_ONLY;
3560        }
3561
3562        return updateFlagsForComponent(flags, userId, cookie);
3563    }
3564
3565    @Override
3566    public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
3567        if (!sUserManager.exists(userId)) return null;
3568        flags = updateFlagsForComponent(flags, userId, component);
3569        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3570                false /* requireFullPermission */, false /* checkShell */, "get activity info");
3571        synchronized (mPackages) {
3572            PackageParser.Activity a = mActivities.mActivities.get(component);
3573
3574            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
3575            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
3576                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3577                if (ps == null) return null;
3578                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
3579                        userId);
3580            }
3581            if (mResolveComponentName.equals(component)) {
3582                return PackageParser.generateActivityInfo(mResolveActivity, flags,
3583                        new PackageUserState(), userId);
3584            }
3585        }
3586        return null;
3587    }
3588
3589    @Override
3590    public boolean activitySupportsIntent(ComponentName component, Intent intent,
3591            String resolvedType) {
3592        synchronized (mPackages) {
3593            if (component.equals(mResolveComponentName)) {
3594                // The resolver supports EVERYTHING!
3595                return true;
3596            }
3597            PackageParser.Activity a = mActivities.mActivities.get(component);
3598            if (a == null) {
3599                return false;
3600            }
3601            for (int i=0; i<a.intents.size(); i++) {
3602                if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
3603                        intent.getData(), intent.getCategories(), TAG) >= 0) {
3604                    return true;
3605                }
3606            }
3607            return false;
3608        }
3609    }
3610
3611    @Override
3612    public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
3613        if (!sUserManager.exists(userId)) return null;
3614        flags = updateFlagsForComponent(flags, userId, component);
3615        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3616                false /* requireFullPermission */, false /* checkShell */, "get receiver info");
3617        synchronized (mPackages) {
3618            PackageParser.Activity a = mReceivers.mActivities.get(component);
3619            if (DEBUG_PACKAGE_INFO) Log.v(
3620                TAG, "getReceiverInfo " + component + ": " + a);
3621            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
3622                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3623                if (ps == null) return null;
3624                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
3625                        userId);
3626            }
3627        }
3628        return null;
3629    }
3630
3631    @Override
3632    public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
3633        if (!sUserManager.exists(userId)) return null;
3634        flags = updateFlagsForComponent(flags, userId, component);
3635        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3636                false /* requireFullPermission */, false /* checkShell */, "get service info");
3637        synchronized (mPackages) {
3638            PackageParser.Service s = mServices.mServices.get(component);
3639            if (DEBUG_PACKAGE_INFO) Log.v(
3640                TAG, "getServiceInfo " + component + ": " + s);
3641            if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) {
3642                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3643                if (ps == null) return null;
3644                return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId),
3645                        userId);
3646            }
3647        }
3648        return null;
3649    }
3650
3651    @Override
3652    public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
3653        if (!sUserManager.exists(userId)) return null;
3654        flags = updateFlagsForComponent(flags, userId, component);
3655        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3656                false /* requireFullPermission */, false /* checkShell */, "get provider info");
3657        synchronized (mPackages) {
3658            PackageParser.Provider p = mProviders.mProviders.get(component);
3659            if (DEBUG_PACKAGE_INFO) Log.v(
3660                TAG, "getProviderInfo " + component + ": " + p);
3661            if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
3662                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3663                if (ps == null) return null;
3664                return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId),
3665                        userId);
3666            }
3667        }
3668        return null;
3669    }
3670
3671    @Override
3672    public String[] getSystemSharedLibraryNames() {
3673        Set<String> libSet;
3674        synchronized (mPackages) {
3675            libSet = mSharedLibraries.keySet();
3676            int size = libSet.size();
3677            if (size > 0) {
3678                String[] libs = new String[size];
3679                libSet.toArray(libs);
3680                return libs;
3681            }
3682        }
3683        return null;
3684    }
3685
3686    @Override
3687    public @NonNull String getServicesSystemSharedLibraryPackageName() {
3688        synchronized (mPackages) {
3689            return mServicesSystemSharedLibraryPackageName;
3690        }
3691    }
3692
3693    @Override
3694    public @NonNull String getSharedSystemSharedLibraryPackageName() {
3695        synchronized (mPackages) {
3696            return mSharedSystemSharedLibraryPackageName;
3697        }
3698    }
3699
3700    @Override
3701    public @NonNull ParceledListSlice<FeatureInfo> getSystemAvailableFeatures() {
3702        synchronized (mPackages) {
3703            final ArrayList<FeatureInfo> res = new ArrayList<>(mAvailableFeatures.values());
3704
3705            final FeatureInfo fi = new FeatureInfo();
3706            fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
3707                    FeatureInfo.GL_ES_VERSION_UNDEFINED);
3708            res.add(fi);
3709
3710            return new ParceledListSlice<>(res);
3711        }
3712    }
3713
3714    @Override
3715    public boolean hasSystemFeature(String name, int version) {
3716        synchronized (mPackages) {
3717            final FeatureInfo feat = mAvailableFeatures.get(name);
3718            if (feat == null) {
3719                return false;
3720            } else {
3721                return feat.version >= version;
3722            }
3723        }
3724    }
3725
3726    @Override
3727    public int checkPermission(String permName, String pkgName, int userId) {
3728        if (!sUserManager.exists(userId)) {
3729            return PackageManager.PERMISSION_DENIED;
3730        }
3731
3732        synchronized (mPackages) {
3733            final PackageParser.Package p = mPackages.get(pkgName);
3734            if (p != null && p.mExtras != null) {
3735                final PackageSetting ps = (PackageSetting) p.mExtras;
3736                final PermissionsState permissionsState = ps.getPermissionsState();
3737                if (permissionsState.hasPermission(permName, userId)) {
3738                    return PackageManager.PERMISSION_GRANTED;
3739                }
3740                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
3741                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
3742                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
3743                    return PackageManager.PERMISSION_GRANTED;
3744                }
3745            }
3746        }
3747
3748        return PackageManager.PERMISSION_DENIED;
3749    }
3750
3751    @Override
3752    public int checkUidPermission(String permName, int uid) {
3753        final int userId = UserHandle.getUserId(uid);
3754
3755        if (!sUserManager.exists(userId)) {
3756            return PackageManager.PERMISSION_DENIED;
3757        }
3758
3759        synchronized (mPackages) {
3760            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
3761            if (obj != null) {
3762                final SettingBase ps = (SettingBase) obj;
3763                final PermissionsState permissionsState = ps.getPermissionsState();
3764                if (permissionsState.hasPermission(permName, userId)) {
3765                    return PackageManager.PERMISSION_GRANTED;
3766                }
3767                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
3768                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
3769                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
3770                    return PackageManager.PERMISSION_GRANTED;
3771                }
3772            } else {
3773                ArraySet<String> perms = mSystemPermissions.get(uid);
3774                if (perms != null) {
3775                    if (perms.contains(permName)) {
3776                        return PackageManager.PERMISSION_GRANTED;
3777                    }
3778                    if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms
3779                            .contains(Manifest.permission.ACCESS_FINE_LOCATION)) {
3780                        return PackageManager.PERMISSION_GRANTED;
3781                    }
3782                }
3783            }
3784        }
3785
3786        return PackageManager.PERMISSION_DENIED;
3787    }
3788
3789    @Override
3790    public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) {
3791        if (UserHandle.getCallingUserId() != userId) {
3792            mContext.enforceCallingPermission(
3793                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
3794                    "isPermissionRevokedByPolicy for user " + userId);
3795        }
3796
3797        if (checkPermission(permission, packageName, userId)
3798                == PackageManager.PERMISSION_GRANTED) {
3799            return false;
3800        }
3801
3802        final long identity = Binder.clearCallingIdentity();
3803        try {
3804            final int flags = getPermissionFlags(permission, packageName, userId);
3805            return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0;
3806        } finally {
3807            Binder.restoreCallingIdentity(identity);
3808        }
3809    }
3810
3811    @Override
3812    public String getPermissionControllerPackageName() {
3813        synchronized (mPackages) {
3814            return mRequiredInstallerPackage;
3815        }
3816    }
3817
3818    /**
3819     * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS
3820     * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller.
3821     * @param checkShell whether to prevent shell from access if there's a debugging restriction
3822     * @param message the message to log on security exception
3823     */
3824    void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission,
3825            boolean checkShell, String message) {
3826        if (userId < 0) {
3827            throw new IllegalArgumentException("Invalid userId " + userId);
3828        }
3829        if (checkShell) {
3830            enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId);
3831        }
3832        if (userId == UserHandle.getUserId(callingUid)) return;
3833        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
3834            if (requireFullPermission) {
3835                mContext.enforceCallingOrSelfPermission(
3836                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
3837            } else {
3838                try {
3839                    mContext.enforceCallingOrSelfPermission(
3840                            android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
3841                } catch (SecurityException se) {
3842                    mContext.enforceCallingOrSelfPermission(
3843                            android.Manifest.permission.INTERACT_ACROSS_USERS, message);
3844                }
3845            }
3846        }
3847    }
3848
3849    void enforceShellRestriction(String restriction, int callingUid, int userHandle) {
3850        if (callingUid == Process.SHELL_UID) {
3851            if (userHandle >= 0
3852                    && sUserManager.hasUserRestriction(restriction, userHandle)) {
3853                throw new SecurityException("Shell does not have permission to access user "
3854                        + userHandle);
3855            } else if (userHandle < 0) {
3856                Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t"
3857                        + Debug.getCallers(3));
3858            }
3859        }
3860    }
3861
3862    private BasePermission findPermissionTreeLP(String permName) {
3863        for(BasePermission bp : mSettings.mPermissionTrees.values()) {
3864            if (permName.startsWith(bp.name) &&
3865                    permName.length() > bp.name.length() &&
3866                    permName.charAt(bp.name.length()) == '.') {
3867                return bp;
3868            }
3869        }
3870        return null;
3871    }
3872
3873    private BasePermission checkPermissionTreeLP(String permName) {
3874        if (permName != null) {
3875            BasePermission bp = findPermissionTreeLP(permName);
3876            if (bp != null) {
3877                if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) {
3878                    return bp;
3879                }
3880                throw new SecurityException("Calling uid "
3881                        + Binder.getCallingUid()
3882                        + " is not allowed to add to permission tree "
3883                        + bp.name + " owned by uid " + bp.uid);
3884            }
3885        }
3886        throw new SecurityException("No permission tree found for " + permName);
3887    }
3888
3889    static boolean compareStrings(CharSequence s1, CharSequence s2) {
3890        if (s1 == null) {
3891            return s2 == null;
3892        }
3893        if (s2 == null) {
3894            return false;
3895        }
3896        if (s1.getClass() != s2.getClass()) {
3897            return false;
3898        }
3899        return s1.equals(s2);
3900    }
3901
3902    static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
3903        if (pi1.icon != pi2.icon) return false;
3904        if (pi1.logo != pi2.logo) return false;
3905        if (pi1.protectionLevel != pi2.protectionLevel) return false;
3906        if (!compareStrings(pi1.name, pi2.name)) return false;
3907        if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
3908        // We'll take care of setting this one.
3909        if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
3910        // These are not currently stored in settings.
3911        //if (!compareStrings(pi1.group, pi2.group)) return false;
3912        //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
3913        //if (pi1.labelRes != pi2.labelRes) return false;
3914        //if (pi1.descriptionRes != pi2.descriptionRes) return false;
3915        return true;
3916    }
3917
3918    int permissionInfoFootprint(PermissionInfo info) {
3919        int size = info.name.length();
3920        if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length();
3921        if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length();
3922        return size;
3923    }
3924
3925    int calculateCurrentPermissionFootprintLocked(BasePermission tree) {
3926        int size = 0;
3927        for (BasePermission perm : mSettings.mPermissions.values()) {
3928            if (perm.uid == tree.uid) {
3929                size += perm.name.length() + permissionInfoFootprint(perm.perm.info);
3930            }
3931        }
3932        return size;
3933    }
3934
3935    void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) {
3936        // We calculate the max size of permissions defined by this uid and throw
3937        // if that plus the size of 'info' would exceed our stated maximum.
3938        if (tree.uid != Process.SYSTEM_UID) {
3939            final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree);
3940            if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) {
3941                throw new SecurityException("Permission tree size cap exceeded");
3942            }
3943        }
3944    }
3945
3946    boolean addPermissionLocked(PermissionInfo info, boolean async) {
3947        if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
3948            throw new SecurityException("Label must be specified in permission");
3949        }
3950        BasePermission tree = checkPermissionTreeLP(info.name);
3951        BasePermission bp = mSettings.mPermissions.get(info.name);
3952        boolean added = bp == null;
3953        boolean changed = true;
3954        int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel);
3955        if (added) {
3956            enforcePermissionCapLocked(info, tree);
3957            bp = new BasePermission(info.name, tree.sourcePackage,
3958                    BasePermission.TYPE_DYNAMIC);
3959        } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
3960            throw new SecurityException(
3961                    "Not allowed to modify non-dynamic permission "
3962                    + info.name);
3963        } else {
3964            if (bp.protectionLevel == fixedLevel
3965                    && bp.perm.owner.equals(tree.perm.owner)
3966                    && bp.uid == tree.uid
3967                    && comparePermissionInfos(bp.perm.info, info)) {
3968                changed = false;
3969            }
3970        }
3971        bp.protectionLevel = fixedLevel;
3972        info = new PermissionInfo(info);
3973        info.protectionLevel = fixedLevel;
3974        bp.perm = new PackageParser.Permission(tree.perm.owner, info);
3975        bp.perm.info.packageName = tree.perm.info.packageName;
3976        bp.uid = tree.uid;
3977        if (added) {
3978            mSettings.mPermissions.put(info.name, bp);
3979        }
3980        if (changed) {
3981            if (!async) {
3982                mSettings.writeLPr();
3983            } else {
3984                scheduleWriteSettingsLocked();
3985            }
3986        }
3987        return added;
3988    }
3989
3990    @Override
3991    public boolean addPermission(PermissionInfo info) {
3992        synchronized (mPackages) {
3993            return addPermissionLocked(info, false);
3994        }
3995    }
3996
3997    @Override
3998    public boolean addPermissionAsync(PermissionInfo info) {
3999        synchronized (mPackages) {
4000            return addPermissionLocked(info, true);
4001        }
4002    }
4003
4004    @Override
4005    public void removePermission(String name) {
4006        synchronized (mPackages) {
4007            checkPermissionTreeLP(name);
4008            BasePermission bp = mSettings.mPermissions.get(name);
4009            if (bp != null) {
4010                if (bp.type != BasePermission.TYPE_DYNAMIC) {
4011                    throw new SecurityException(
4012                            "Not allowed to modify non-dynamic permission "
4013                            + name);
4014                }
4015                mSettings.mPermissions.remove(name);
4016                mSettings.writeLPr();
4017            }
4018        }
4019    }
4020
4021    private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(PackageParser.Package pkg,
4022            BasePermission bp) {
4023        int index = pkg.requestedPermissions.indexOf(bp.name);
4024        if (index == -1) {
4025            throw new SecurityException("Package " + pkg.packageName
4026                    + " has not requested permission " + bp.name);
4027        }
4028        if (!bp.isRuntime() && !bp.isDevelopment()) {
4029            throw new SecurityException("Permission " + bp.name
4030                    + " is not a changeable permission type");
4031        }
4032    }
4033
4034    @Override
4035    public void grantRuntimePermission(String packageName, String name, final int userId) {
4036        if (!sUserManager.exists(userId)) {
4037            Log.e(TAG, "No such user:" + userId);
4038            return;
4039        }
4040
4041        mContext.enforceCallingOrSelfPermission(
4042                android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
4043                "grantRuntimePermission");
4044
4045        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4046                true /* requireFullPermission */, true /* checkShell */,
4047                "grantRuntimePermission");
4048
4049        final int uid;
4050        final SettingBase sb;
4051
4052        synchronized (mPackages) {
4053            final PackageParser.Package pkg = mPackages.get(packageName);
4054            if (pkg == null) {
4055                throw new IllegalArgumentException("Unknown package: " + packageName);
4056            }
4057
4058            final BasePermission bp = mSettings.mPermissions.get(name);
4059            if (bp == null) {
4060                throw new IllegalArgumentException("Unknown permission: " + name);
4061            }
4062
4063            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
4064
4065            // If a permission review is required for legacy apps we represent
4066            // their permissions as always granted runtime ones since we need
4067            // to keep the review required permission flag per user while an
4068            // install permission's state is shared across all users.
4069            if (Build.PERMISSIONS_REVIEW_REQUIRED
4070                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
4071                    && bp.isRuntime()) {
4072                return;
4073            }
4074
4075            uid = UserHandle.getUid(userId, pkg.applicationInfo.uid);
4076            sb = (SettingBase) pkg.mExtras;
4077            if (sb == null) {
4078                throw new IllegalArgumentException("Unknown package: " + packageName);
4079            }
4080
4081            final PermissionsState permissionsState = sb.getPermissionsState();
4082
4083            final int flags = permissionsState.getPermissionFlags(name, userId);
4084            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
4085                throw new SecurityException("Cannot grant system fixed permission "
4086                        + name + " for package " + packageName);
4087            }
4088
4089            if (bp.isDevelopment()) {
4090                // Development permissions must be handled specially, since they are not
4091                // normal runtime permissions.  For now they apply to all users.
4092                if (permissionsState.grantInstallPermission(bp) !=
4093                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
4094                    scheduleWriteSettingsLocked();
4095                }
4096                return;
4097            }
4098
4099            if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
4100                Slog.w(TAG, "Cannot grant runtime permission to a legacy app");
4101                return;
4102            }
4103
4104            final int result = permissionsState.grantRuntimePermission(bp, userId);
4105            switch (result) {
4106                case PermissionsState.PERMISSION_OPERATION_FAILURE: {
4107                    return;
4108                }
4109
4110                case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
4111                    final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
4112                    mHandler.post(new Runnable() {
4113                        @Override
4114                        public void run() {
4115                            killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED);
4116                        }
4117                    });
4118                }
4119                break;
4120            }
4121
4122            mOnPermissionChangeListeners.onPermissionsChanged(uid);
4123
4124            // Not critical if that is lost - app has to request again.
4125            mSettings.writeRuntimePermissionsForUserLPr(userId, false);
4126        }
4127
4128        // Only need to do this if user is initialized. Otherwise it's a new user
4129        // and there are no processes running as the user yet and there's no need
4130        // to make an expensive call to remount processes for the changed permissions.
4131        if (READ_EXTERNAL_STORAGE.equals(name)
4132                || WRITE_EXTERNAL_STORAGE.equals(name)) {
4133            final long token = Binder.clearCallingIdentity();
4134            try {
4135                if (sUserManager.isInitialized(userId)) {
4136                    MountServiceInternal mountServiceInternal = LocalServices.getService(
4137                            MountServiceInternal.class);
4138                    mountServiceInternal.onExternalStoragePolicyChanged(uid, packageName);
4139                }
4140            } finally {
4141                Binder.restoreCallingIdentity(token);
4142            }
4143        }
4144    }
4145
4146    @Override
4147    public void revokeRuntimePermission(String packageName, String name, int userId) {
4148        if (!sUserManager.exists(userId)) {
4149            Log.e(TAG, "No such user:" + userId);
4150            return;
4151        }
4152
4153        mContext.enforceCallingOrSelfPermission(
4154                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
4155                "revokeRuntimePermission");
4156
4157        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4158                true /* requireFullPermission */, true /* checkShell */,
4159                "revokeRuntimePermission");
4160
4161        final int appId;
4162
4163        synchronized (mPackages) {
4164            final PackageParser.Package pkg = mPackages.get(packageName);
4165            if (pkg == null) {
4166                throw new IllegalArgumentException("Unknown package: " + packageName);
4167            }
4168
4169            final BasePermission bp = mSettings.mPermissions.get(name);
4170            if (bp == null) {
4171                throw new IllegalArgumentException("Unknown permission: " + name);
4172            }
4173
4174            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
4175
4176            // If a permission review is required for legacy apps we represent
4177            // their permissions as always granted runtime ones since we need
4178            // to keep the review required permission flag per user while an
4179            // install permission's state is shared across all users.
4180            if (Build.PERMISSIONS_REVIEW_REQUIRED
4181                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
4182                    && bp.isRuntime()) {
4183                return;
4184            }
4185
4186            SettingBase sb = (SettingBase) pkg.mExtras;
4187            if (sb == null) {
4188                throw new IllegalArgumentException("Unknown package: " + packageName);
4189            }
4190
4191            final PermissionsState permissionsState = sb.getPermissionsState();
4192
4193            final int flags = permissionsState.getPermissionFlags(name, userId);
4194            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
4195                throw new SecurityException("Cannot revoke system fixed permission "
4196                        + name + " for package " + packageName);
4197            }
4198
4199            if (bp.isDevelopment()) {
4200                // Development permissions must be handled specially, since they are not
4201                // normal runtime permissions.  For now they apply to all users.
4202                if (permissionsState.revokeInstallPermission(bp) !=
4203                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
4204                    scheduleWriteSettingsLocked();
4205                }
4206                return;
4207            }
4208
4209            if (permissionsState.revokeRuntimePermission(bp, userId) ==
4210                    PermissionsState.PERMISSION_OPERATION_FAILURE) {
4211                return;
4212            }
4213
4214            mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid);
4215
4216            // Critical, after this call app should never have the permission.
4217            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
4218
4219            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
4220        }
4221
4222        killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
4223    }
4224
4225    @Override
4226    public void resetRuntimePermissions() {
4227        mContext.enforceCallingOrSelfPermission(
4228                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
4229                "revokeRuntimePermission");
4230
4231        int callingUid = Binder.getCallingUid();
4232        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
4233            mContext.enforceCallingOrSelfPermission(
4234                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
4235                    "resetRuntimePermissions");
4236        }
4237
4238        synchronized (mPackages) {
4239            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL);
4240            for (int userId : UserManagerService.getInstance().getUserIds()) {
4241                final int packageCount = mPackages.size();
4242                for (int i = 0; i < packageCount; i++) {
4243                    PackageParser.Package pkg = mPackages.valueAt(i);
4244                    if (!(pkg.mExtras instanceof PackageSetting)) {
4245                        continue;
4246                    }
4247                    PackageSetting ps = (PackageSetting) pkg.mExtras;
4248                    resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
4249                }
4250            }
4251        }
4252    }
4253
4254    @Override
4255    public int getPermissionFlags(String name, String packageName, int userId) {
4256        if (!sUserManager.exists(userId)) {
4257            return 0;
4258        }
4259
4260        enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags");
4261
4262        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4263                true /* requireFullPermission */, false /* checkShell */,
4264                "getPermissionFlags");
4265
4266        synchronized (mPackages) {
4267            final PackageParser.Package pkg = mPackages.get(packageName);
4268            if (pkg == null) {
4269                throw new IllegalArgumentException("Unknown package: " + packageName);
4270            }
4271
4272            final BasePermission bp = mSettings.mPermissions.get(name);
4273            if (bp == null) {
4274                throw new IllegalArgumentException("Unknown permission: " + name);
4275            }
4276
4277            SettingBase sb = (SettingBase) pkg.mExtras;
4278            if (sb == null) {
4279                throw new IllegalArgumentException("Unknown package: " + packageName);
4280            }
4281
4282            PermissionsState permissionsState = sb.getPermissionsState();
4283            return permissionsState.getPermissionFlags(name, userId);
4284        }
4285    }
4286
4287    @Override
4288    public void updatePermissionFlags(String name, String packageName, int flagMask,
4289            int flagValues, int userId) {
4290        if (!sUserManager.exists(userId)) {
4291            return;
4292        }
4293
4294        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags");
4295
4296        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4297                true /* requireFullPermission */, true /* checkShell */,
4298                "updatePermissionFlags");
4299
4300        // Only the system can change these flags and nothing else.
4301        if (getCallingUid() != Process.SYSTEM_UID) {
4302            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4303            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4304            flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
4305            flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
4306            flagValues &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
4307        }
4308
4309        synchronized (mPackages) {
4310            final PackageParser.Package pkg = mPackages.get(packageName);
4311            if (pkg == null) {
4312                throw new IllegalArgumentException("Unknown package: " + packageName);
4313            }
4314
4315            final BasePermission bp = mSettings.mPermissions.get(name);
4316            if (bp == null) {
4317                throw new IllegalArgumentException("Unknown permission: " + name);
4318            }
4319
4320            SettingBase sb = (SettingBase) pkg.mExtras;
4321            if (sb == null) {
4322                throw new IllegalArgumentException("Unknown package: " + packageName);
4323            }
4324
4325            PermissionsState permissionsState = sb.getPermissionsState();
4326
4327            boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null;
4328
4329            if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) {
4330                // Install and runtime permissions are stored in different places,
4331                // so figure out what permission changed and persist the change.
4332                if (permissionsState.getInstallPermissionState(name) != null) {
4333                    scheduleWriteSettingsLocked();
4334                } else if (permissionsState.getRuntimePermissionState(name, userId) != null
4335                        || hadState) {
4336                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
4337                }
4338            }
4339        }
4340    }
4341
4342    /**
4343     * Update the permission flags for all packages and runtime permissions of a user in order
4344     * to allow device or profile owner to remove POLICY_FIXED.
4345     */
4346    @Override
4347    public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) {
4348        if (!sUserManager.exists(userId)) {
4349            return;
4350        }
4351
4352        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps");
4353
4354        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4355                true /* requireFullPermission */, true /* checkShell */,
4356                "updatePermissionFlagsForAllApps");
4357
4358        // Only the system can change system fixed flags.
4359        if (getCallingUid() != Process.SYSTEM_UID) {
4360            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4361            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4362        }
4363
4364        synchronized (mPackages) {
4365            boolean changed = false;
4366            final int packageCount = mPackages.size();
4367            for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) {
4368                final PackageParser.Package pkg = mPackages.valueAt(pkgIndex);
4369                SettingBase sb = (SettingBase) pkg.mExtras;
4370                if (sb == null) {
4371                    continue;
4372                }
4373                PermissionsState permissionsState = sb.getPermissionsState();
4374                changed |= permissionsState.updatePermissionFlagsForAllPermissions(
4375                        userId, flagMask, flagValues);
4376            }
4377            if (changed) {
4378                mSettings.writeRuntimePermissionsForUserLPr(userId, false);
4379            }
4380        }
4381    }
4382
4383    private void enforceGrantRevokeRuntimePermissionPermissions(String message) {
4384        if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS)
4385                != PackageManager.PERMISSION_GRANTED
4386            && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS)
4387                != PackageManager.PERMISSION_GRANTED) {
4388            throw new SecurityException(message + " requires "
4389                    + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or "
4390                    + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS);
4391        }
4392    }
4393
4394    @Override
4395    public boolean shouldShowRequestPermissionRationale(String permissionName,
4396            String packageName, int userId) {
4397        if (UserHandle.getCallingUserId() != userId) {
4398            mContext.enforceCallingPermission(
4399                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
4400                    "canShowRequestPermissionRationale for user " + userId);
4401        }
4402
4403        final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId);
4404        if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) {
4405            return false;
4406        }
4407
4408        if (checkPermission(permissionName, packageName, userId)
4409                == PackageManager.PERMISSION_GRANTED) {
4410            return false;
4411        }
4412
4413        final int flags;
4414
4415        final long identity = Binder.clearCallingIdentity();
4416        try {
4417            flags = getPermissionFlags(permissionName,
4418                    packageName, userId);
4419        } finally {
4420            Binder.restoreCallingIdentity(identity);
4421        }
4422
4423        final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
4424                | PackageManager.FLAG_PERMISSION_POLICY_FIXED
4425                | PackageManager.FLAG_PERMISSION_USER_FIXED;
4426
4427        if ((flags & fixedFlags) != 0) {
4428            return false;
4429        }
4430
4431        return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0;
4432    }
4433
4434    @Override
4435    public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
4436        mContext.enforceCallingOrSelfPermission(
4437                Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS,
4438                "addOnPermissionsChangeListener");
4439
4440        synchronized (mPackages) {
4441            mOnPermissionChangeListeners.addListenerLocked(listener);
4442        }
4443    }
4444
4445    @Override
4446    public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
4447        synchronized (mPackages) {
4448            mOnPermissionChangeListeners.removeListenerLocked(listener);
4449        }
4450    }
4451
4452    @Override
4453    public boolean isProtectedBroadcast(String actionName) {
4454        synchronized (mPackages) {
4455            if (mProtectedBroadcasts.contains(actionName)) {
4456                return true;
4457            } else if (actionName != null) {
4458                // TODO: remove these terrible hacks
4459                if (actionName.startsWith("android.net.netmon.lingerExpired")
4460                        || actionName.startsWith("com.android.server.sip.SipWakeupTimer")
4461                        || actionName.startsWith("com.android.internal.telephony.data-reconnect")
4462                        || actionName.startsWith("android.net.netmon.launchCaptivePortalApp")) {
4463                    return true;
4464                }
4465            }
4466        }
4467        return false;
4468    }
4469
4470    @Override
4471    public int checkSignatures(String pkg1, String pkg2) {
4472        synchronized (mPackages) {
4473            final PackageParser.Package p1 = mPackages.get(pkg1);
4474            final PackageParser.Package p2 = mPackages.get(pkg2);
4475            if (p1 == null || p1.mExtras == null
4476                    || p2 == null || p2.mExtras == null) {
4477                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4478            }
4479            return compareSignatures(p1.mSignatures, p2.mSignatures);
4480        }
4481    }
4482
4483    @Override
4484    public int checkUidSignatures(int uid1, int uid2) {
4485        // Map to base uids.
4486        uid1 = UserHandle.getAppId(uid1);
4487        uid2 = UserHandle.getAppId(uid2);
4488        // reader
4489        synchronized (mPackages) {
4490            Signature[] s1;
4491            Signature[] s2;
4492            Object obj = mSettings.getUserIdLPr(uid1);
4493            if (obj != null) {
4494                if (obj instanceof SharedUserSetting) {
4495                    s1 = ((SharedUserSetting)obj).signatures.mSignatures;
4496                } else if (obj instanceof PackageSetting) {
4497                    s1 = ((PackageSetting)obj).signatures.mSignatures;
4498                } else {
4499                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4500                }
4501            } else {
4502                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4503            }
4504            obj = mSettings.getUserIdLPr(uid2);
4505            if (obj != null) {
4506                if (obj instanceof SharedUserSetting) {
4507                    s2 = ((SharedUserSetting)obj).signatures.mSignatures;
4508                } else if (obj instanceof PackageSetting) {
4509                    s2 = ((PackageSetting)obj).signatures.mSignatures;
4510                } else {
4511                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4512                }
4513            } else {
4514                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4515            }
4516            return compareSignatures(s1, s2);
4517        }
4518    }
4519
4520    /**
4521     * This method should typically only be used when granting or revoking
4522     * permissions, since the app may immediately restart after this call.
4523     * <p>
4524     * If you're doing surgery on app code/data, use {@link PackageFreezer} to
4525     * guard your work against the app being relaunched.
4526     */
4527    private void killUid(int appId, int userId, String reason) {
4528        final long identity = Binder.clearCallingIdentity();
4529        try {
4530            IActivityManager am = ActivityManagerNative.getDefault();
4531            if (am != null) {
4532                try {
4533                    am.killUid(appId, userId, reason);
4534                } catch (RemoteException e) {
4535                    /* ignore - same process */
4536                }
4537            }
4538        } finally {
4539            Binder.restoreCallingIdentity(identity);
4540        }
4541    }
4542
4543    /**
4544     * Compares two sets of signatures. Returns:
4545     * <br />
4546     * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null,
4547     * <br />
4548     * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null,
4549     * <br />
4550     * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null,
4551     * <br />
4552     * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical,
4553     * <br />
4554     * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ.
4555     */
4556    static int compareSignatures(Signature[] s1, Signature[] s2) {
4557        if (s1 == null) {
4558            return s2 == null
4559                    ? PackageManager.SIGNATURE_NEITHER_SIGNED
4560                    : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
4561        }
4562
4563        if (s2 == null) {
4564            return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
4565        }
4566
4567        if (s1.length != s2.length) {
4568            return PackageManager.SIGNATURE_NO_MATCH;
4569        }
4570
4571        // Since both signature sets are of size 1, we can compare without HashSets.
4572        if (s1.length == 1) {
4573            return s1[0].equals(s2[0]) ?
4574                    PackageManager.SIGNATURE_MATCH :
4575                    PackageManager.SIGNATURE_NO_MATCH;
4576        }
4577
4578        ArraySet<Signature> set1 = new ArraySet<Signature>();
4579        for (Signature sig : s1) {
4580            set1.add(sig);
4581        }
4582        ArraySet<Signature> set2 = new ArraySet<Signature>();
4583        for (Signature sig : s2) {
4584            set2.add(sig);
4585        }
4586        // Make sure s2 contains all signatures in s1.
4587        if (set1.equals(set2)) {
4588            return PackageManager.SIGNATURE_MATCH;
4589        }
4590        return PackageManager.SIGNATURE_NO_MATCH;
4591    }
4592
4593    /**
4594     * If the database version for this type of package (internal storage or
4595     * external storage) is less than the version where package signatures
4596     * were updated, return true.
4597     */
4598    private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
4599        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
4600        return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY;
4601    }
4602
4603    /**
4604     * Used for backward compatibility to make sure any packages with
4605     * certificate chains get upgraded to the new style. {@code existingSigs}
4606     * will be in the old format (since they were stored on disk from before the
4607     * system upgrade) and {@code scannedSigs} will be in the newer format.
4608     */
4609    private int compareSignaturesCompat(PackageSignatures existingSigs,
4610            PackageParser.Package scannedPkg) {
4611        if (!isCompatSignatureUpdateNeeded(scannedPkg)) {
4612            return PackageManager.SIGNATURE_NO_MATCH;
4613        }
4614
4615        ArraySet<Signature> existingSet = new ArraySet<Signature>();
4616        for (Signature sig : existingSigs.mSignatures) {
4617            existingSet.add(sig);
4618        }
4619        ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>();
4620        for (Signature sig : scannedPkg.mSignatures) {
4621            try {
4622                Signature[] chainSignatures = sig.getChainSignatures();
4623                for (Signature chainSig : chainSignatures) {
4624                    scannedCompatSet.add(chainSig);
4625                }
4626            } catch (CertificateEncodingException e) {
4627                scannedCompatSet.add(sig);
4628            }
4629        }
4630        /*
4631         * Make sure the expanded scanned set contains all signatures in the
4632         * existing one.
4633         */
4634        if (scannedCompatSet.equals(existingSet)) {
4635            // Migrate the old signatures to the new scheme.
4636            existingSigs.assignSignatures(scannedPkg.mSignatures);
4637            // The new KeySets will be re-added later in the scanning process.
4638            synchronized (mPackages) {
4639                mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName);
4640            }
4641            return PackageManager.SIGNATURE_MATCH;
4642        }
4643        return PackageManager.SIGNATURE_NO_MATCH;
4644    }
4645
4646    private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
4647        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
4648        return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER;
4649    }
4650
4651    private int compareSignaturesRecover(PackageSignatures existingSigs,
4652            PackageParser.Package scannedPkg) {
4653        if (!isRecoverSignatureUpdateNeeded(scannedPkg)) {
4654            return PackageManager.SIGNATURE_NO_MATCH;
4655        }
4656
4657        String msg = null;
4658        try {
4659            if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) {
4660                logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for "
4661                        + scannedPkg.packageName);
4662                return PackageManager.SIGNATURE_MATCH;
4663            }
4664        } catch (CertificateException e) {
4665            msg = e.getMessage();
4666        }
4667
4668        logCriticalInfo(Log.INFO,
4669                "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg);
4670        return PackageManager.SIGNATURE_NO_MATCH;
4671    }
4672
4673    @Override
4674    public List<String> getAllPackages() {
4675        synchronized (mPackages) {
4676            return new ArrayList<String>(mPackages.keySet());
4677        }
4678    }
4679
4680    @Override
4681    public String[] getPackagesForUid(int uid) {
4682        uid = UserHandle.getAppId(uid);
4683        // reader
4684        synchronized (mPackages) {
4685            Object obj = mSettings.getUserIdLPr(uid);
4686            if (obj instanceof SharedUserSetting) {
4687                final SharedUserSetting sus = (SharedUserSetting) obj;
4688                final int N = sus.packages.size();
4689                final String[] res = new String[N];
4690                final Iterator<PackageSetting> it = sus.packages.iterator();
4691                int i = 0;
4692                while (it.hasNext()) {
4693                    res[i++] = it.next().name;
4694                }
4695                return res;
4696            } else if (obj instanceof PackageSetting) {
4697                final PackageSetting ps = (PackageSetting) obj;
4698                return new String[] { ps.name };
4699            }
4700        }
4701        return null;
4702    }
4703
4704    @Override
4705    public String getNameForUid(int uid) {
4706        // reader
4707        synchronized (mPackages) {
4708            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4709            if (obj instanceof SharedUserSetting) {
4710                final SharedUserSetting sus = (SharedUserSetting) obj;
4711                return sus.name + ":" + sus.userId;
4712            } else if (obj instanceof PackageSetting) {
4713                final PackageSetting ps = (PackageSetting) obj;
4714                return ps.name;
4715            }
4716        }
4717        return null;
4718    }
4719
4720    @Override
4721    public int getUidForSharedUser(String sharedUserName) {
4722        if(sharedUserName == null) {
4723            return -1;
4724        }
4725        // reader
4726        synchronized (mPackages) {
4727            final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false);
4728            if (suid == null) {
4729                return -1;
4730            }
4731            return suid.userId;
4732        }
4733    }
4734
4735    @Override
4736    public int getFlagsForUid(int uid) {
4737        synchronized (mPackages) {
4738            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4739            if (obj instanceof SharedUserSetting) {
4740                final SharedUserSetting sus = (SharedUserSetting) obj;
4741                return sus.pkgFlags;
4742            } else if (obj instanceof PackageSetting) {
4743                final PackageSetting ps = (PackageSetting) obj;
4744                return ps.pkgFlags;
4745            }
4746        }
4747        return 0;
4748    }
4749
4750    @Override
4751    public int getPrivateFlagsForUid(int uid) {
4752        synchronized (mPackages) {
4753            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4754            if (obj instanceof SharedUserSetting) {
4755                final SharedUserSetting sus = (SharedUserSetting) obj;
4756                return sus.pkgPrivateFlags;
4757            } else if (obj instanceof PackageSetting) {
4758                final PackageSetting ps = (PackageSetting) obj;
4759                return ps.pkgPrivateFlags;
4760            }
4761        }
4762        return 0;
4763    }
4764
4765    @Override
4766    public boolean isUidPrivileged(int uid) {
4767        uid = UserHandle.getAppId(uid);
4768        // reader
4769        synchronized (mPackages) {
4770            Object obj = mSettings.getUserIdLPr(uid);
4771            if (obj instanceof SharedUserSetting) {
4772                final SharedUserSetting sus = (SharedUserSetting) obj;
4773                final Iterator<PackageSetting> it = sus.packages.iterator();
4774                while (it.hasNext()) {
4775                    if (it.next().isPrivileged()) {
4776                        return true;
4777                    }
4778                }
4779            } else if (obj instanceof PackageSetting) {
4780                final PackageSetting ps = (PackageSetting) obj;
4781                return ps.isPrivileged();
4782            }
4783        }
4784        return false;
4785    }
4786
4787    @Override
4788    public String[] getAppOpPermissionPackages(String permissionName) {
4789        synchronized (mPackages) {
4790            ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName);
4791            if (pkgs == null) {
4792                return null;
4793            }
4794            return pkgs.toArray(new String[pkgs.size()]);
4795        }
4796    }
4797
4798    @Override
4799    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
4800            int flags, int userId) {
4801        try {
4802            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveIntent");
4803
4804            if (!sUserManager.exists(userId)) return null;
4805            flags = updateFlagsForResolve(flags, userId, intent);
4806            enforceCrossUserPermission(Binder.getCallingUid(), userId,
4807                    false /*requireFullPermission*/, false /*checkShell*/, "resolve intent");
4808
4809            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
4810            final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType,
4811                    flags, userId);
4812            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
4813
4814            final ResolveInfo bestChoice =
4815                    chooseBestActivity(intent, resolvedType, flags, query, userId);
4816
4817            if (isEphemeralAllowed(intent, query, userId)) {
4818                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveEphemeral");
4819                final EphemeralResolveInfo ai =
4820                        getEphemeralResolveInfo(intent, resolvedType, userId);
4821                if (ai != null) {
4822                    if (DEBUG_EPHEMERAL) {
4823                        Slog.v(TAG, "Returning an EphemeralResolveInfo");
4824                    }
4825                    bestChoice.ephemeralInstaller = mEphemeralInstallerInfo;
4826                    bestChoice.ephemeralResolveInfo = ai;
4827                }
4828                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
4829            }
4830            return bestChoice;
4831        } finally {
4832            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
4833        }
4834    }
4835
4836    @Override
4837    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
4838            IntentFilter filter, int match, ComponentName activity) {
4839        final int userId = UserHandle.getCallingUserId();
4840        if (DEBUG_PREFERRED) {
4841            Log.v(TAG, "setLastChosenActivity intent=" + intent
4842                + " resolvedType=" + resolvedType
4843                + " flags=" + flags
4844                + " filter=" + filter
4845                + " match=" + match
4846                + " activity=" + activity);
4847            filter.dump(new PrintStreamPrinter(System.out), "    ");
4848        }
4849        intent.setComponent(null);
4850        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
4851                userId);
4852        // Find any earlier preferred or last chosen entries and nuke them
4853        findPreferredActivity(intent, resolvedType,
4854                flags, query, 0, false, true, false, userId);
4855        // Add the new activity as the last chosen for this filter
4856        addPreferredActivityInternal(filter, match, null, activity, false, userId,
4857                "Setting last chosen");
4858    }
4859
4860    @Override
4861    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
4862        final int userId = UserHandle.getCallingUserId();
4863        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
4864        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
4865                userId);
4866        return findPreferredActivity(intent, resolvedType, flags, query, 0,
4867                false, false, false, userId);
4868    }
4869
4870
4871    private boolean isEphemeralAllowed(
4872            Intent intent, List<ResolveInfo> resolvedActivites, int userId) {
4873        // Short circuit and return early if possible.
4874        if (DISABLE_EPHEMERAL_APPS) {
4875            return false;
4876        }
4877        final int callingUser = UserHandle.getCallingUserId();
4878        if (callingUser != UserHandle.USER_SYSTEM) {
4879            return false;
4880        }
4881        if (mEphemeralResolverConnection == null) {
4882            return false;
4883        }
4884        if (intent.getComponent() != null) {
4885            return false;
4886        }
4887        if (intent.getPackage() != null) {
4888            return false;
4889        }
4890        final boolean isWebUri = hasWebURI(intent);
4891        if (!isWebUri) {
4892            return false;
4893        }
4894        // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution.
4895        synchronized (mPackages) {
4896            final int count = resolvedActivites.size();
4897            for (int n = 0; n < count; n++) {
4898                ResolveInfo info = resolvedActivites.get(n);
4899                String packageName = info.activityInfo.packageName;
4900                PackageSetting ps = mSettings.mPackages.get(packageName);
4901                if (ps != null) {
4902                    // Try to get the status from User settings first
4903                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
4904                    int status = (int) (packedStatus >> 32);
4905                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS
4906                            || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
4907                        if (DEBUG_EPHEMERAL) {
4908                            Slog.v(TAG, "DENY ephemeral apps;"
4909                                + " pkg: " + packageName + ", status: " + status);
4910                        }
4911                        return false;
4912                    }
4913                }
4914            }
4915        }
4916        // We've exhausted all ways to deny ephemeral application; let the system look for them.
4917        return true;
4918    }
4919
4920    private EphemeralResolveInfo getEphemeralResolveInfo(Intent intent, String resolvedType,
4921            int userId) {
4922        MessageDigest digest = null;
4923        try {
4924            digest = MessageDigest.getInstance(EphemeralResolveInfo.SHA_ALGORITHM);
4925        } catch (NoSuchAlgorithmException e) {
4926            // If we can't create a digest, ignore ephemeral apps.
4927            return null;
4928        }
4929
4930        final byte[] hostBytes = intent.getData().getHost().getBytes();
4931        final byte[] digestBytes = digest.digest(hostBytes);
4932        int shaPrefix =
4933                digestBytes[0] << 24
4934                | digestBytes[1] << 16
4935                | digestBytes[2] << 8
4936                | digestBytes[3] << 0;
4937        final List<EphemeralResolveInfo> ephemeralResolveInfoList =
4938                mEphemeralResolverConnection.getEphemeralResolveInfoList(shaPrefix);
4939        if (ephemeralResolveInfoList == null || ephemeralResolveInfoList.size() == 0) {
4940            // No hash prefix match; there are no ephemeral apps for this domain.
4941            return null;
4942        }
4943        for (int i = ephemeralResolveInfoList.size() - 1; i >= 0; --i) {
4944            EphemeralResolveInfo ephemeralApplication = ephemeralResolveInfoList.get(i);
4945            if (!Arrays.equals(digestBytes, ephemeralApplication.getDigestBytes())) {
4946                continue;
4947            }
4948            final List<IntentFilter> filters = ephemeralApplication.getFilters();
4949            // No filters; this should never happen.
4950            if (filters.isEmpty()) {
4951                continue;
4952            }
4953            // We have a domain match; resolve the filters to see if anything matches.
4954            final EphemeralIntentResolver ephemeralResolver = new EphemeralIntentResolver();
4955            for (int j = filters.size() - 1; j >= 0; --j) {
4956                final EphemeralResolveIntentInfo intentInfo =
4957                        new EphemeralResolveIntentInfo(filters.get(j), ephemeralApplication);
4958                ephemeralResolver.addFilter(intentInfo);
4959            }
4960            List<EphemeralResolveInfo> matchedResolveInfoList = ephemeralResolver.queryIntent(
4961                    intent, resolvedType, false /*defaultOnly*/, userId);
4962            if (!matchedResolveInfoList.isEmpty()) {
4963                return matchedResolveInfoList.get(0);
4964            }
4965        }
4966        // Hash or filter mis-match; no ephemeral apps for this domain.
4967        return null;
4968    }
4969
4970    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
4971            int flags, List<ResolveInfo> query, int userId) {
4972        if (query != null) {
4973            final int N = query.size();
4974            if (N == 1) {
4975                return query.get(0);
4976            } else if (N > 1) {
4977                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
4978                // If there is more than one activity with the same priority,
4979                // then let the user decide between them.
4980                ResolveInfo r0 = query.get(0);
4981                ResolveInfo r1 = query.get(1);
4982                if (DEBUG_INTENT_MATCHING || debug) {
4983                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
4984                            + r1.activityInfo.name + "=" + r1.priority);
4985                }
4986                // If the first activity has a higher priority, or a different
4987                // default, then it is always desirable to pick it.
4988                if (r0.priority != r1.priority
4989                        || r0.preferredOrder != r1.preferredOrder
4990                        || r0.isDefault != r1.isDefault) {
4991                    return query.get(0);
4992                }
4993                // If we have saved a preference for a preferred activity for
4994                // this Intent, use that.
4995                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
4996                        flags, query, r0.priority, true, false, debug, userId);
4997                if (ri != null) {
4998                    return ri;
4999                }
5000                ri = new ResolveInfo(mResolveInfo);
5001                ri.activityInfo = new ActivityInfo(ri.activityInfo);
5002                ri.activityInfo.labelRes = ResolverActivity.getLabelRes(intent.getAction());
5003                ri.activityInfo.applicationInfo = new ApplicationInfo(
5004                        ri.activityInfo.applicationInfo);
5005                if (userId != 0) {
5006                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
5007                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
5008                }
5009                // Make sure that the resolver is displayable in car mode
5010                if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle();
5011                ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true);
5012                return ri;
5013            }
5014        }
5015        return null;
5016    }
5017
5018    private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
5019            int flags, List<ResolveInfo> query, boolean debug, int userId) {
5020        final int N = query.size();
5021        PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
5022                .get(userId);
5023        // Get the list of persistent preferred activities that handle the intent
5024        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
5025        List<PersistentPreferredActivity> pprefs = ppir != null
5026                ? ppir.queryIntent(intent, resolvedType,
5027                        (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
5028                : null;
5029        if (pprefs != null && pprefs.size() > 0) {
5030            final int M = pprefs.size();
5031            for (int i=0; i<M; i++) {
5032                final PersistentPreferredActivity ppa = pprefs.get(i);
5033                if (DEBUG_PREFERRED || debug) {
5034                    Slog.v(TAG, "Checking PersistentPreferredActivity ds="
5035                            + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
5036                            + "\n  component=" + ppa.mComponent);
5037                    ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
5038                }
5039                final ActivityInfo ai = getActivityInfo(ppa.mComponent,
5040                        flags | MATCH_DISABLED_COMPONENTS, userId);
5041                if (DEBUG_PREFERRED || debug) {
5042                    Slog.v(TAG, "Found persistent preferred activity:");
5043                    if (ai != null) {
5044                        ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
5045                    } else {
5046                        Slog.v(TAG, "  null");
5047                    }
5048                }
5049                if (ai == null) {
5050                    // This previously registered persistent preferred activity
5051                    // component is no longer known. Ignore it and do NOT remove it.
5052                    continue;
5053                }
5054                for (int j=0; j<N; j++) {
5055                    final ResolveInfo ri = query.get(j);
5056                    if (!ri.activityInfo.applicationInfo.packageName
5057                            .equals(ai.applicationInfo.packageName)) {
5058                        continue;
5059                    }
5060                    if (!ri.activityInfo.name.equals(ai.name)) {
5061                        continue;
5062                    }
5063                    //  Found a persistent preference that can handle the intent.
5064                    if (DEBUG_PREFERRED || debug) {
5065                        Slog.v(TAG, "Returning persistent preferred activity: " +
5066                                ri.activityInfo.packageName + "/" + ri.activityInfo.name);
5067                    }
5068                    return ri;
5069                }
5070            }
5071        }
5072        return null;
5073    }
5074
5075    // TODO: handle preferred activities missing while user has amnesia
5076    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
5077            List<ResolveInfo> query, int priority, boolean always,
5078            boolean removeMatches, boolean debug, int userId) {
5079        if (!sUserManager.exists(userId)) return null;
5080        flags = updateFlagsForResolve(flags, userId, intent);
5081        // writer
5082        synchronized (mPackages) {
5083            if (intent.getSelector() != null) {
5084                intent = intent.getSelector();
5085            }
5086            if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
5087
5088            // Try to find a matching persistent preferred activity.
5089            ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
5090                    debug, userId);
5091
5092            // If a persistent preferred activity matched, use it.
5093            if (pri != null) {
5094                return pri;
5095            }
5096
5097            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
5098            // Get the list of preferred activities that handle the intent
5099            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
5100            List<PreferredActivity> prefs = pir != null
5101                    ? pir.queryIntent(intent, resolvedType,
5102                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
5103                    : null;
5104            if (prefs != null && prefs.size() > 0) {
5105                boolean changed = false;
5106                try {
5107                    // First figure out how good the original match set is.
5108                    // We will only allow preferred activities that came
5109                    // from the same match quality.
5110                    int match = 0;
5111
5112                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
5113
5114                    final int N = query.size();
5115                    for (int j=0; j<N; j++) {
5116                        final ResolveInfo ri = query.get(j);
5117                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
5118                                + ": 0x" + Integer.toHexString(match));
5119                        if (ri.match > match) {
5120                            match = ri.match;
5121                        }
5122                    }
5123
5124                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
5125                            + Integer.toHexString(match));
5126
5127                    match &= IntentFilter.MATCH_CATEGORY_MASK;
5128                    final int M = prefs.size();
5129                    for (int i=0; i<M; i++) {
5130                        final PreferredActivity pa = prefs.get(i);
5131                        if (DEBUG_PREFERRED || debug) {
5132                            Slog.v(TAG, "Checking PreferredActivity ds="
5133                                    + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
5134                                    + "\n  component=" + pa.mPref.mComponent);
5135                            pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
5136                        }
5137                        if (pa.mPref.mMatch != match) {
5138                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
5139                                    + Integer.toHexString(pa.mPref.mMatch));
5140                            continue;
5141                        }
5142                        // If it's not an "always" type preferred activity and that's what we're
5143                        // looking for, skip it.
5144                        if (always && !pa.mPref.mAlways) {
5145                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
5146                            continue;
5147                        }
5148                        final ActivityInfo ai = getActivityInfo(
5149                                pa.mPref.mComponent, flags | MATCH_DISABLED_COMPONENTS
5150                                        | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
5151                                userId);
5152                        if (DEBUG_PREFERRED || debug) {
5153                            Slog.v(TAG, "Found preferred activity:");
5154                            if (ai != null) {
5155                                ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
5156                            } else {
5157                                Slog.v(TAG, "  null");
5158                            }
5159                        }
5160                        if (ai == null) {
5161                            // This previously registered preferred activity
5162                            // component is no longer known.  Most likely an update
5163                            // to the app was installed and in the new version this
5164                            // component no longer exists.  Clean it up by removing
5165                            // it from the preferred activities list, and skip it.
5166                            Slog.w(TAG, "Removing dangling preferred activity: "
5167                                    + pa.mPref.mComponent);
5168                            pir.removeFilter(pa);
5169                            changed = true;
5170                            continue;
5171                        }
5172                        for (int j=0; j<N; j++) {
5173                            final ResolveInfo ri = query.get(j);
5174                            if (!ri.activityInfo.applicationInfo.packageName
5175                                    .equals(ai.applicationInfo.packageName)) {
5176                                continue;
5177                            }
5178                            if (!ri.activityInfo.name.equals(ai.name)) {
5179                                continue;
5180                            }
5181
5182                            if (removeMatches) {
5183                                pir.removeFilter(pa);
5184                                changed = true;
5185                                if (DEBUG_PREFERRED) {
5186                                    Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
5187                                }
5188                                break;
5189                            }
5190
5191                            // Okay we found a previously set preferred or last chosen app.
5192                            // If the result set is different from when this
5193                            // was created, we need to clear it and re-ask the
5194                            // user their preference, if we're looking for an "always" type entry.
5195                            if (always && !pa.mPref.sameSet(query)) {
5196                                Slog.i(TAG, "Result set changed, dropping preferred activity for "
5197                                        + intent + " type " + resolvedType);
5198                                if (DEBUG_PREFERRED) {
5199                                    Slog.v(TAG, "Removing preferred activity since set changed "
5200                                            + pa.mPref.mComponent);
5201                                }
5202                                pir.removeFilter(pa);
5203                                // Re-add the filter as a "last chosen" entry (!always)
5204                                PreferredActivity lastChosen = new PreferredActivity(
5205                                        pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
5206                                pir.addFilter(lastChosen);
5207                                changed = true;
5208                                return null;
5209                            }
5210
5211                            // Yay! Either the set matched or we're looking for the last chosen
5212                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
5213                                    + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
5214                            return ri;
5215                        }
5216                    }
5217                } finally {
5218                    if (changed) {
5219                        if (DEBUG_PREFERRED) {
5220                            Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions");
5221                        }
5222                        scheduleWritePackageRestrictionsLocked(userId);
5223                    }
5224                }
5225            }
5226        }
5227        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
5228        return null;
5229    }
5230
5231    /*
5232     * Returns if intent can be forwarded from the sourceUserId to the targetUserId
5233     */
5234    @Override
5235    public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
5236            int targetUserId) {
5237        mContext.enforceCallingOrSelfPermission(
5238                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
5239        List<CrossProfileIntentFilter> matches =
5240                getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
5241        if (matches != null) {
5242            int size = matches.size();
5243            for (int i = 0; i < size; i++) {
5244                if (matches.get(i).getTargetUserId() == targetUserId) return true;
5245            }
5246        }
5247        if (hasWebURI(intent)) {
5248            // cross-profile app linking works only towards the parent.
5249            final UserInfo parent = getProfileParent(sourceUserId);
5250            synchronized(mPackages) {
5251                int flags = updateFlagsForResolve(0, parent.id, intent);
5252                CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr(
5253                        intent, resolvedType, flags, sourceUserId, parent.id);
5254                return xpDomainInfo != null;
5255            }
5256        }
5257        return false;
5258    }
5259
5260    private UserInfo getProfileParent(int userId) {
5261        final long identity = Binder.clearCallingIdentity();
5262        try {
5263            return sUserManager.getProfileParent(userId);
5264        } finally {
5265            Binder.restoreCallingIdentity(identity);
5266        }
5267    }
5268
5269    private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
5270            String resolvedType, int userId) {
5271        CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
5272        if (resolver != null) {
5273            return resolver.queryIntent(intent, resolvedType, false, userId);
5274        }
5275        return null;
5276    }
5277
5278    @Override
5279    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivities(Intent intent,
5280            String resolvedType, int flags, int userId) {
5281        try {
5282            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
5283
5284            return new ParceledListSlice<>(
5285                    queryIntentActivitiesInternal(intent, resolvedType, flags, userId));
5286        } finally {
5287            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
5288        }
5289    }
5290
5291    private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent,
5292            String resolvedType, int flags, int userId) {
5293        if (!sUserManager.exists(userId)) return Collections.emptyList();
5294        flags = updateFlagsForResolve(flags, userId, intent);
5295        enforceCrossUserPermission(Binder.getCallingUid(), userId,
5296                false /* requireFullPermission */, false /* checkShell */,
5297                "query intent activities");
5298        ComponentName comp = intent.getComponent();
5299        if (comp == null) {
5300            if (intent.getSelector() != null) {
5301                intent = intent.getSelector();
5302                comp = intent.getComponent();
5303            }
5304        }
5305
5306        if (comp != null) {
5307            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5308            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
5309            if (ai != null) {
5310                final ResolveInfo ri = new ResolveInfo();
5311                ri.activityInfo = ai;
5312                list.add(ri);
5313            }
5314            return list;
5315        }
5316
5317        // reader
5318        synchronized (mPackages) {
5319            final String pkgName = intent.getPackage();
5320            if (pkgName == null) {
5321                List<CrossProfileIntentFilter> matchingFilters =
5322                        getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
5323                // Check for results that need to skip the current profile.
5324                ResolveInfo xpResolveInfo  = querySkipCurrentProfileIntents(matchingFilters, intent,
5325                        resolvedType, flags, userId);
5326                if (xpResolveInfo != null) {
5327                    List<ResolveInfo> result = new ArrayList<ResolveInfo>(1);
5328                    result.add(xpResolveInfo);
5329                    return filterIfNotSystemUser(result, userId);
5330                }
5331
5332                // Check for results in the current profile.
5333                List<ResolveInfo> result = mActivities.queryIntent(
5334                        intent, resolvedType, flags, userId);
5335                result = filterIfNotSystemUser(result, userId);
5336
5337                // Check for cross profile results.
5338                boolean hasNonNegativePriorityResult = hasNonNegativePriority(result);
5339                xpResolveInfo = queryCrossProfileIntents(
5340                        matchingFilters, intent, resolvedType, flags, userId,
5341                        hasNonNegativePriorityResult);
5342                if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
5343                    boolean isVisibleToUser = filterIfNotSystemUser(
5344                            Collections.singletonList(xpResolveInfo), userId).size() > 0;
5345                    if (isVisibleToUser) {
5346                        result.add(xpResolveInfo);
5347                        Collections.sort(result, mResolvePrioritySorter);
5348                    }
5349                }
5350                if (hasWebURI(intent)) {
5351                    CrossProfileDomainInfo xpDomainInfo = null;
5352                    final UserInfo parent = getProfileParent(userId);
5353                    if (parent != null) {
5354                        xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType,
5355                                flags, userId, parent.id);
5356                    }
5357                    if (xpDomainInfo != null) {
5358                        if (xpResolveInfo != null) {
5359                            // If we didn't remove it, the cross-profile ResolveInfo would be twice
5360                            // in the result.
5361                            result.remove(xpResolveInfo);
5362                        }
5363                        if (result.size() == 0) {
5364                            result.add(xpDomainInfo.resolveInfo);
5365                            return result;
5366                        }
5367                    } else if (result.size() <= 1) {
5368                        return result;
5369                    }
5370                    result = filterCandidatesWithDomainPreferredActivitiesLPr(intent, flags, result,
5371                            xpDomainInfo, userId);
5372                    Collections.sort(result, mResolvePrioritySorter);
5373                }
5374                return result;
5375            }
5376            final PackageParser.Package pkg = mPackages.get(pkgName);
5377            if (pkg != null) {
5378                return filterIfNotSystemUser(
5379                        mActivities.queryIntentForPackage(
5380                                intent, resolvedType, flags, pkg.activities, userId),
5381                        userId);
5382            }
5383            return new ArrayList<ResolveInfo>();
5384        }
5385    }
5386
5387    private static class CrossProfileDomainInfo {
5388        /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */
5389        ResolveInfo resolveInfo;
5390        /* Best domain verification status of the activities found in the other profile */
5391        int bestDomainVerificationStatus;
5392    }
5393
5394    private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent,
5395            String resolvedType, int flags, int sourceUserId, int parentUserId) {
5396        if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING,
5397                sourceUserId)) {
5398            return null;
5399        }
5400        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
5401                resolvedType, flags, parentUserId);
5402
5403        if (resultTargetUser == null || resultTargetUser.isEmpty()) {
5404            return null;
5405        }
5406        CrossProfileDomainInfo result = null;
5407        int size = resultTargetUser.size();
5408        for (int i = 0; i < size; i++) {
5409            ResolveInfo riTargetUser = resultTargetUser.get(i);
5410            // Intent filter verification is only for filters that specify a host. So don't return
5411            // those that handle all web uris.
5412            if (riTargetUser.handleAllWebDataURI) {
5413                continue;
5414            }
5415            String packageName = riTargetUser.activityInfo.packageName;
5416            PackageSetting ps = mSettings.mPackages.get(packageName);
5417            if (ps == null) {
5418                continue;
5419            }
5420            long verificationState = getDomainVerificationStatusLPr(ps, parentUserId);
5421            int status = (int)(verificationState >> 32);
5422            if (result == null) {
5423                result = new CrossProfileDomainInfo();
5424                result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(),
5425                        sourceUserId, parentUserId);
5426                result.bestDomainVerificationStatus = status;
5427            } else {
5428                result.bestDomainVerificationStatus = bestDomainVerificationStatus(status,
5429                        result.bestDomainVerificationStatus);
5430            }
5431        }
5432        // Don't consider matches with status NEVER across profiles.
5433        if (result != null && result.bestDomainVerificationStatus
5434                == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5435            return null;
5436        }
5437        return result;
5438    }
5439
5440    /**
5441     * Verification statuses are ordered from the worse to the best, except for
5442     * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse.
5443     */
5444    private int bestDomainVerificationStatus(int status1, int status2) {
5445        if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5446            return status2;
5447        }
5448        if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5449            return status1;
5450        }
5451        return (int) MathUtils.max(status1, status2);
5452    }
5453
5454    private boolean isUserEnabled(int userId) {
5455        long callingId = Binder.clearCallingIdentity();
5456        try {
5457            UserInfo userInfo = sUserManager.getUserInfo(userId);
5458            return userInfo != null && userInfo.isEnabled();
5459        } finally {
5460            Binder.restoreCallingIdentity(callingId);
5461        }
5462    }
5463
5464    /**
5465     * Filter out activities with systemUserOnly flag set, when current user is not System.
5466     *
5467     * @return filtered list
5468     */
5469    private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) {
5470        if (userId == UserHandle.USER_SYSTEM) {
5471            return resolveInfos;
5472        }
5473        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
5474            ResolveInfo info = resolveInfos.get(i);
5475            if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) {
5476                resolveInfos.remove(i);
5477            }
5478        }
5479        return resolveInfos;
5480    }
5481
5482    /**
5483     * @param resolveInfos list of resolve infos in descending priority order
5484     * @return if the list contains a resolve info with non-negative priority
5485     */
5486    private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) {
5487        return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0;
5488    }
5489
5490    private static boolean hasWebURI(Intent intent) {
5491        if (intent.getData() == null) {
5492            return false;
5493        }
5494        final String scheme = intent.getScheme();
5495        if (TextUtils.isEmpty(scheme)) {
5496            return false;
5497        }
5498        return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS);
5499    }
5500
5501    private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent,
5502            int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo,
5503            int userId) {
5504        final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0;
5505
5506        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
5507            Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " +
5508                    candidates.size());
5509        }
5510
5511        ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>();
5512        ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>();
5513        ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>();
5514        ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>();
5515        ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>();
5516        ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>();
5517
5518        synchronized (mPackages) {
5519            final int count = candidates.size();
5520            // First, try to use linked apps. Partition the candidates into four lists:
5521            // one for the final results, one for the "do not use ever", one for "undefined status"
5522            // and finally one for "browser app type".
5523            for (int n=0; n<count; n++) {
5524                ResolveInfo info = candidates.get(n);
5525                String packageName = info.activityInfo.packageName;
5526                PackageSetting ps = mSettings.mPackages.get(packageName);
5527                if (ps != null) {
5528                    // Add to the special match all list (Browser use case)
5529                    if (info.handleAllWebDataURI) {
5530                        matchAllList.add(info);
5531                        continue;
5532                    }
5533                    // Try to get the status from User settings first
5534                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
5535                    int status = (int)(packedStatus >> 32);
5536                    int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
5537                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
5538                        if (DEBUG_DOMAIN_VERIFICATION) {
5539                            Slog.i(TAG, "  + always: " + info.activityInfo.packageName
5540                                    + " : linkgen=" + linkGeneration);
5541                        }
5542                        // Use link-enabled generation as preferredOrder, i.e.
5543                        // prefer newly-enabled over earlier-enabled.
5544                        info.preferredOrder = linkGeneration;
5545                        alwaysList.add(info);
5546                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5547                        if (DEBUG_DOMAIN_VERIFICATION) {
5548                            Slog.i(TAG, "  + never: " + info.activityInfo.packageName);
5549                        }
5550                        neverList.add(info);
5551                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
5552                        if (DEBUG_DOMAIN_VERIFICATION) {
5553                            Slog.i(TAG, "  + always-ask: " + info.activityInfo.packageName);
5554                        }
5555                        alwaysAskList.add(info);
5556                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED ||
5557                            status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) {
5558                        if (DEBUG_DOMAIN_VERIFICATION) {
5559                            Slog.i(TAG, "  + ask: " + info.activityInfo.packageName);
5560                        }
5561                        undefinedList.add(info);
5562                    }
5563                }
5564            }
5565
5566            // We'll want to include browser possibilities in a few cases
5567            boolean includeBrowser = false;
5568
5569            // First try to add the "always" resolution(s) for the current user, if any
5570            if (alwaysList.size() > 0) {
5571                result.addAll(alwaysList);
5572            } else {
5573                // Add all undefined apps as we want them to appear in the disambiguation dialog.
5574                result.addAll(undefinedList);
5575                // Maybe add one for the other profile.
5576                if (xpDomainInfo != null && (
5577                        xpDomainInfo.bestDomainVerificationStatus
5578                        != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) {
5579                    result.add(xpDomainInfo.resolveInfo);
5580                }
5581                includeBrowser = true;
5582            }
5583
5584            // The presence of any 'always ask' alternatives means we'll also offer browsers.
5585            // If there were 'always' entries their preferred order has been set, so we also
5586            // back that off to make the alternatives equivalent
5587            if (alwaysAskList.size() > 0) {
5588                for (ResolveInfo i : result) {
5589                    i.preferredOrder = 0;
5590                }
5591                result.addAll(alwaysAskList);
5592                includeBrowser = true;
5593            }
5594
5595            if (includeBrowser) {
5596                // Also add browsers (all of them or only the default one)
5597                if (DEBUG_DOMAIN_VERIFICATION) {
5598                    Slog.v(TAG, "   ...including browsers in candidate set");
5599                }
5600                if ((matchFlags & MATCH_ALL) != 0) {
5601                    result.addAll(matchAllList);
5602                } else {
5603                    // Browser/generic handling case.  If there's a default browser, go straight
5604                    // to that (but only if there is no other higher-priority match).
5605                    final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
5606                    int maxMatchPrio = 0;
5607                    ResolveInfo defaultBrowserMatch = null;
5608                    final int numCandidates = matchAllList.size();
5609                    for (int n = 0; n < numCandidates; n++) {
5610                        ResolveInfo info = matchAllList.get(n);
5611                        // track the highest overall match priority...
5612                        if (info.priority > maxMatchPrio) {
5613                            maxMatchPrio = info.priority;
5614                        }
5615                        // ...and the highest-priority default browser match
5616                        if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) {
5617                            if (defaultBrowserMatch == null
5618                                    || (defaultBrowserMatch.priority < info.priority)) {
5619                                if (debug) {
5620                                    Slog.v(TAG, "Considering default browser match " + info);
5621                                }
5622                                defaultBrowserMatch = info;
5623                            }
5624                        }
5625                    }
5626                    if (defaultBrowserMatch != null
5627                            && defaultBrowserMatch.priority >= maxMatchPrio
5628                            && !TextUtils.isEmpty(defaultBrowserPackageName))
5629                    {
5630                        if (debug) {
5631                            Slog.v(TAG, "Default browser match " + defaultBrowserMatch);
5632                        }
5633                        result.add(defaultBrowserMatch);
5634                    } else {
5635                        result.addAll(matchAllList);
5636                    }
5637                }
5638
5639                // If there is nothing selected, add all candidates and remove the ones that the user
5640                // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state
5641                if (result.size() == 0) {
5642                    result.addAll(candidates);
5643                    result.removeAll(neverList);
5644                }
5645            }
5646        }
5647        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
5648            Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " +
5649                    result.size());
5650            for (ResolveInfo info : result) {
5651                Slog.v(TAG, "  + " + info.activityInfo);
5652            }
5653        }
5654        return result;
5655    }
5656
5657    // Returns a packed value as a long:
5658    //
5659    // high 'int'-sized word: link status: undefined/ask/never/always.
5660    // low 'int'-sized word: relative priority among 'always' results.
5661    private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) {
5662        long result = ps.getDomainVerificationStatusForUser(userId);
5663        // if none available, get the master status
5664        if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
5665            if (ps.getIntentFilterVerificationInfo() != null) {
5666                result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32;
5667            }
5668        }
5669        return result;
5670    }
5671
5672    private ResolveInfo querySkipCurrentProfileIntents(
5673            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
5674            int flags, int sourceUserId) {
5675        if (matchingFilters != null) {
5676            int size = matchingFilters.size();
5677            for (int i = 0; i < size; i ++) {
5678                CrossProfileIntentFilter filter = matchingFilters.get(i);
5679                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
5680                    // Checking if there are activities in the target user that can handle the
5681                    // intent.
5682                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
5683                            resolvedType, flags, sourceUserId);
5684                    if (resolveInfo != null) {
5685                        return resolveInfo;
5686                    }
5687                }
5688            }
5689        }
5690        return null;
5691    }
5692
5693    // Return matching ResolveInfo in target user if any.
5694    private ResolveInfo queryCrossProfileIntents(
5695            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
5696            int flags, int sourceUserId, boolean matchInCurrentProfile) {
5697        if (matchingFilters != null) {
5698            // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
5699            // match the same intent. For performance reasons, it is better not to
5700            // run queryIntent twice for the same userId
5701            SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
5702            int size = matchingFilters.size();
5703            for (int i = 0; i < size; i++) {
5704                CrossProfileIntentFilter filter = matchingFilters.get(i);
5705                int targetUserId = filter.getTargetUserId();
5706                boolean skipCurrentProfile =
5707                        (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0;
5708                boolean skipCurrentProfileIfNoMatchFound =
5709                        (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0;
5710                if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId)
5711                        && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) {
5712                    // Checking if there are activities in the target user that can handle the
5713                    // intent.
5714                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
5715                            resolvedType, flags, sourceUserId);
5716                    if (resolveInfo != null) return resolveInfo;
5717                    alreadyTriedUserIds.put(targetUserId, true);
5718                }
5719            }
5720        }
5721        return null;
5722    }
5723
5724    /**
5725     * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that
5726     * will forward the intent to the filter's target user.
5727     * Otherwise, returns null.
5728     */
5729    private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent,
5730            String resolvedType, int flags, int sourceUserId) {
5731        int targetUserId = filter.getTargetUserId();
5732        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
5733                resolvedType, flags, targetUserId);
5734        if (resultTargetUser != null && isUserEnabled(targetUserId)) {
5735            // If all the matches in the target profile are suspended, return null.
5736            for (int i = resultTargetUser.size() - 1; i >= 0; i--) {
5737                if ((resultTargetUser.get(i).activityInfo.applicationInfo.flags
5738                        & ApplicationInfo.FLAG_SUSPENDED) == 0) {
5739                    return createForwardingResolveInfoUnchecked(filter, sourceUserId,
5740                            targetUserId);
5741                }
5742            }
5743        }
5744        return null;
5745    }
5746
5747    private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter,
5748            int sourceUserId, int targetUserId) {
5749        ResolveInfo forwardingResolveInfo = new ResolveInfo();
5750        long ident = Binder.clearCallingIdentity();
5751        boolean targetIsProfile;
5752        try {
5753            targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile();
5754        } finally {
5755            Binder.restoreCallingIdentity(ident);
5756        }
5757        String className;
5758        if (targetIsProfile) {
5759            className = FORWARD_INTENT_TO_MANAGED_PROFILE;
5760        } else {
5761            className = FORWARD_INTENT_TO_PARENT;
5762        }
5763        ComponentName forwardingActivityComponentName = new ComponentName(
5764                mAndroidApplication.packageName, className);
5765        ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
5766                sourceUserId);
5767        if (!targetIsProfile) {
5768            forwardingActivityInfo.showUserIcon = targetUserId;
5769            forwardingResolveInfo.noResourceId = true;
5770        }
5771        forwardingResolveInfo.activityInfo = forwardingActivityInfo;
5772        forwardingResolveInfo.priority = 0;
5773        forwardingResolveInfo.preferredOrder = 0;
5774        forwardingResolveInfo.match = 0;
5775        forwardingResolveInfo.isDefault = true;
5776        forwardingResolveInfo.filter = filter;
5777        forwardingResolveInfo.targetUserId = targetUserId;
5778        return forwardingResolveInfo;
5779    }
5780
5781    @Override
5782    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
5783            Intent[] specifics, String[] specificTypes, Intent intent,
5784            String resolvedType, int flags, int userId) {
5785        return new ParceledListSlice<>(queryIntentActivityOptionsInternal(caller, specifics,
5786                specificTypes, intent, resolvedType, flags, userId));
5787    }
5788
5789    private @NonNull List<ResolveInfo> queryIntentActivityOptionsInternal(ComponentName caller,
5790            Intent[] specifics, String[] specificTypes, Intent intent,
5791            String resolvedType, int flags, int userId) {
5792        if (!sUserManager.exists(userId)) return Collections.emptyList();
5793        flags = updateFlagsForResolve(flags, userId, intent);
5794        enforceCrossUserPermission(Binder.getCallingUid(), userId,
5795                false /* requireFullPermission */, false /* checkShell */,
5796                "query intent activity options");
5797        final String resultsAction = intent.getAction();
5798
5799        final List<ResolveInfo> results = queryIntentActivitiesInternal(intent, resolvedType, flags
5800                | PackageManager.GET_RESOLVED_FILTER, userId);
5801
5802        if (DEBUG_INTENT_MATCHING) {
5803            Log.v(TAG, "Query " + intent + ": " + results);
5804        }
5805
5806        int specificsPos = 0;
5807        int N;
5808
5809        // todo: note that the algorithm used here is O(N^2).  This
5810        // isn't a problem in our current environment, but if we start running
5811        // into situations where we have more than 5 or 10 matches then this
5812        // should probably be changed to something smarter...
5813
5814        // First we go through and resolve each of the specific items
5815        // that were supplied, taking care of removing any corresponding
5816        // duplicate items in the generic resolve list.
5817        if (specifics != null) {
5818            for (int i=0; i<specifics.length; i++) {
5819                final Intent sintent = specifics[i];
5820                if (sintent == null) {
5821                    continue;
5822                }
5823
5824                if (DEBUG_INTENT_MATCHING) {
5825                    Log.v(TAG, "Specific #" + i + ": " + sintent);
5826                }
5827
5828                String action = sintent.getAction();
5829                if (resultsAction != null && resultsAction.equals(action)) {
5830                    // If this action was explicitly requested, then don't
5831                    // remove things that have it.
5832                    action = null;
5833                }
5834
5835                ResolveInfo ri = null;
5836                ActivityInfo ai = null;
5837
5838                ComponentName comp = sintent.getComponent();
5839                if (comp == null) {
5840                    ri = resolveIntent(
5841                        sintent,
5842                        specificTypes != null ? specificTypes[i] : null,
5843                            flags, userId);
5844                    if (ri == null) {
5845                        continue;
5846                    }
5847                    if (ri == mResolveInfo) {
5848                        // ACK!  Must do something better with this.
5849                    }
5850                    ai = ri.activityInfo;
5851                    comp = new ComponentName(ai.applicationInfo.packageName,
5852                            ai.name);
5853                } else {
5854                    ai = getActivityInfo(comp, flags, userId);
5855                    if (ai == null) {
5856                        continue;
5857                    }
5858                }
5859
5860                // Look for any generic query activities that are duplicates
5861                // of this specific one, and remove them from the results.
5862                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
5863                N = results.size();
5864                int j;
5865                for (j=specificsPos; j<N; j++) {
5866                    ResolveInfo sri = results.get(j);
5867                    if ((sri.activityInfo.name.equals(comp.getClassName())
5868                            && sri.activityInfo.applicationInfo.packageName.equals(
5869                                    comp.getPackageName()))
5870                        || (action != null && sri.filter.matchAction(action))) {
5871                        results.remove(j);
5872                        if (DEBUG_INTENT_MATCHING) Log.v(
5873                            TAG, "Removing duplicate item from " + j
5874                            + " due to specific " + specificsPos);
5875                        if (ri == null) {
5876                            ri = sri;
5877                        }
5878                        j--;
5879                        N--;
5880                    }
5881                }
5882
5883                // Add this specific item to its proper place.
5884                if (ri == null) {
5885                    ri = new ResolveInfo();
5886                    ri.activityInfo = ai;
5887                }
5888                results.add(specificsPos, ri);
5889                ri.specificIndex = i;
5890                specificsPos++;
5891            }
5892        }
5893
5894        // Now we go through the remaining generic results and remove any
5895        // duplicate actions that are found here.
5896        N = results.size();
5897        for (int i=specificsPos; i<N-1; i++) {
5898            final ResolveInfo rii = results.get(i);
5899            if (rii.filter == null) {
5900                continue;
5901            }
5902
5903            // Iterate over all of the actions of this result's intent
5904            // filter...  typically this should be just one.
5905            final Iterator<String> it = rii.filter.actionsIterator();
5906            if (it == null) {
5907                continue;
5908            }
5909            while (it.hasNext()) {
5910                final String action = it.next();
5911                if (resultsAction != null && resultsAction.equals(action)) {
5912                    // If this action was explicitly requested, then don't
5913                    // remove things that have it.
5914                    continue;
5915                }
5916                for (int j=i+1; j<N; j++) {
5917                    final ResolveInfo rij = results.get(j);
5918                    if (rij.filter != null && rij.filter.hasAction(action)) {
5919                        results.remove(j);
5920                        if (DEBUG_INTENT_MATCHING) Log.v(
5921                            TAG, "Removing duplicate item from " + j
5922                            + " due to action " + action + " at " + i);
5923                        j--;
5924                        N--;
5925                    }
5926                }
5927            }
5928
5929            // If the caller didn't request filter information, drop it now
5930            // so we don't have to marshall/unmarshall it.
5931            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
5932                rii.filter = null;
5933            }
5934        }
5935
5936        // Filter out the caller activity if so requested.
5937        if (caller != null) {
5938            N = results.size();
5939            for (int i=0; i<N; i++) {
5940                ActivityInfo ainfo = results.get(i).activityInfo;
5941                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
5942                        && caller.getClassName().equals(ainfo.name)) {
5943                    results.remove(i);
5944                    break;
5945                }
5946            }
5947        }
5948
5949        // If the caller didn't request filter information,
5950        // drop them now so we don't have to
5951        // marshall/unmarshall it.
5952        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
5953            N = results.size();
5954            for (int i=0; i<N; i++) {
5955                results.get(i).filter = null;
5956            }
5957        }
5958
5959        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
5960        return results;
5961    }
5962
5963    @Override
5964    public @NonNull ParceledListSlice<ResolveInfo> queryIntentReceivers(Intent intent,
5965            String resolvedType, int flags, int userId) {
5966        return new ParceledListSlice<>(
5967                queryIntentReceiversInternal(intent, resolvedType, flags, userId));
5968    }
5969
5970    private @NonNull List<ResolveInfo> queryIntentReceiversInternal(Intent intent,
5971            String resolvedType, int flags, int userId) {
5972        if (!sUserManager.exists(userId)) return Collections.emptyList();
5973        flags = updateFlagsForResolve(flags, userId, intent);
5974        ComponentName comp = intent.getComponent();
5975        if (comp == null) {
5976            if (intent.getSelector() != null) {
5977                intent = intent.getSelector();
5978                comp = intent.getComponent();
5979            }
5980        }
5981        if (comp != null) {
5982            List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5983            ActivityInfo ai = getReceiverInfo(comp, flags, userId);
5984            if (ai != null) {
5985                ResolveInfo ri = new ResolveInfo();
5986                ri.activityInfo = ai;
5987                list.add(ri);
5988            }
5989            return list;
5990        }
5991
5992        // reader
5993        synchronized (mPackages) {
5994            String pkgName = intent.getPackage();
5995            if (pkgName == null) {
5996                return mReceivers.queryIntent(intent, resolvedType, flags, userId);
5997            }
5998            final PackageParser.Package pkg = mPackages.get(pkgName);
5999            if (pkg != null) {
6000                return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers,
6001                        userId);
6002            }
6003            return Collections.emptyList();
6004        }
6005    }
6006
6007    @Override
6008    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
6009        if (!sUserManager.exists(userId)) return null;
6010        flags = updateFlagsForResolve(flags, userId, intent);
6011        List<ResolveInfo> query = queryIntentServicesInternal(intent, resolvedType, flags, userId);
6012        if (query != null) {
6013            if (query.size() >= 1) {
6014                // If there is more than one service with the same priority,
6015                // just arbitrarily pick the first one.
6016                return query.get(0);
6017            }
6018        }
6019        return null;
6020    }
6021
6022    @Override
6023    public @NonNull ParceledListSlice<ResolveInfo> queryIntentServices(Intent intent,
6024            String resolvedType, int flags, int userId) {
6025        return new ParceledListSlice<>(
6026                queryIntentServicesInternal(intent, resolvedType, flags, userId));
6027    }
6028
6029    private @NonNull List<ResolveInfo> queryIntentServicesInternal(Intent intent,
6030            String resolvedType, int flags, int userId) {
6031        if (!sUserManager.exists(userId)) return Collections.emptyList();
6032        flags = updateFlagsForResolve(flags, userId, intent);
6033        ComponentName comp = intent.getComponent();
6034        if (comp == null) {
6035            if (intent.getSelector() != null) {
6036                intent = intent.getSelector();
6037                comp = intent.getComponent();
6038            }
6039        }
6040        if (comp != null) {
6041            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
6042            final ServiceInfo si = getServiceInfo(comp, flags, userId);
6043            if (si != null) {
6044                final ResolveInfo ri = new ResolveInfo();
6045                ri.serviceInfo = si;
6046                list.add(ri);
6047            }
6048            return list;
6049        }
6050
6051        // reader
6052        synchronized (mPackages) {
6053            String pkgName = intent.getPackage();
6054            if (pkgName == null) {
6055                return mServices.queryIntent(intent, resolvedType, flags, userId);
6056            }
6057            final PackageParser.Package pkg = mPackages.get(pkgName);
6058            if (pkg != null) {
6059                return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
6060                        userId);
6061            }
6062            return Collections.emptyList();
6063        }
6064    }
6065
6066    @Override
6067    public @NonNull ParceledListSlice<ResolveInfo> queryIntentContentProviders(Intent intent,
6068            String resolvedType, int flags, int userId) {
6069        return new ParceledListSlice<>(
6070                queryIntentContentProvidersInternal(intent, resolvedType, flags, userId));
6071    }
6072
6073    private @NonNull List<ResolveInfo> queryIntentContentProvidersInternal(
6074            Intent intent, String resolvedType, int flags, int userId) {
6075        if (!sUserManager.exists(userId)) return Collections.emptyList();
6076        flags = updateFlagsForResolve(flags, userId, intent);
6077        ComponentName comp = intent.getComponent();
6078        if (comp == null) {
6079            if (intent.getSelector() != null) {
6080                intent = intent.getSelector();
6081                comp = intent.getComponent();
6082            }
6083        }
6084        if (comp != null) {
6085            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
6086            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
6087            if (pi != null) {
6088                final ResolveInfo ri = new ResolveInfo();
6089                ri.providerInfo = pi;
6090                list.add(ri);
6091            }
6092            return list;
6093        }
6094
6095        // reader
6096        synchronized (mPackages) {
6097            String pkgName = intent.getPackage();
6098            if (pkgName == null) {
6099                return mProviders.queryIntent(intent, resolvedType, flags, userId);
6100            }
6101            final PackageParser.Package pkg = mPackages.get(pkgName);
6102            if (pkg != null) {
6103                return mProviders.queryIntentForPackage(
6104                        intent, resolvedType, flags, pkg.providers, userId);
6105            }
6106            return Collections.emptyList();
6107        }
6108    }
6109
6110    @Override
6111    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
6112        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
6113        flags = updateFlagsForPackage(flags, userId, null);
6114        final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0;
6115        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6116                true /* requireFullPermission */, false /* checkShell */,
6117                "get installed packages");
6118
6119        // writer
6120        synchronized (mPackages) {
6121            ArrayList<PackageInfo> list;
6122            if (listUninstalled) {
6123                list = new ArrayList<PackageInfo>(mSettings.mPackages.size());
6124                for (PackageSetting ps : mSettings.mPackages.values()) {
6125                    final PackageInfo pi;
6126                    if (ps.pkg != null) {
6127                        pi = generatePackageInfo(ps, flags, userId);
6128                    } else {
6129                        pi = generatePackageInfo(ps, flags, userId);
6130                    }
6131                    if (pi != null) {
6132                        list.add(pi);
6133                    }
6134                }
6135            } else {
6136                list = new ArrayList<PackageInfo>(mPackages.size());
6137                for (PackageParser.Package p : mPackages.values()) {
6138                    final PackageInfo pi =
6139                            generatePackageInfo((PackageSetting)p.mExtras, flags, userId);
6140                    if (pi != null) {
6141                        list.add(pi);
6142                    }
6143                }
6144            }
6145
6146            return new ParceledListSlice<PackageInfo>(list);
6147        }
6148    }
6149
6150    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
6151            String[] permissions, boolean[] tmp, int flags, int userId) {
6152        int numMatch = 0;
6153        final PermissionsState permissionsState = ps.getPermissionsState();
6154        for (int i=0; i<permissions.length; i++) {
6155            final String permission = permissions[i];
6156            if (permissionsState.hasPermission(permission, userId)) {
6157                tmp[i] = true;
6158                numMatch++;
6159            } else {
6160                tmp[i] = false;
6161            }
6162        }
6163        if (numMatch == 0) {
6164            return;
6165        }
6166        final PackageInfo pi;
6167        if (ps.pkg != null) {
6168            pi = generatePackageInfo(ps, flags, userId);
6169        } else {
6170            pi = generatePackageInfo(ps, flags, userId);
6171        }
6172        // The above might return null in cases of uninstalled apps or install-state
6173        // skew across users/profiles.
6174        if (pi != null) {
6175            if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
6176                if (numMatch == permissions.length) {
6177                    pi.requestedPermissions = permissions;
6178                } else {
6179                    pi.requestedPermissions = new String[numMatch];
6180                    numMatch = 0;
6181                    for (int i=0; i<permissions.length; i++) {
6182                        if (tmp[i]) {
6183                            pi.requestedPermissions[numMatch] = permissions[i];
6184                            numMatch++;
6185                        }
6186                    }
6187                }
6188            }
6189            list.add(pi);
6190        }
6191    }
6192
6193    @Override
6194    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
6195            String[] permissions, int flags, int userId) {
6196        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
6197        flags = updateFlagsForPackage(flags, userId, permissions);
6198        final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0;
6199
6200        // writer
6201        synchronized (mPackages) {
6202            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
6203            boolean[] tmpBools = new boolean[permissions.length];
6204            if (listUninstalled) {
6205                for (PackageSetting ps : mSettings.mPackages.values()) {
6206                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId);
6207                }
6208            } else {
6209                for (PackageParser.Package pkg : mPackages.values()) {
6210                    PackageSetting ps = (PackageSetting)pkg.mExtras;
6211                    if (ps != null) {
6212                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
6213                                userId);
6214                    }
6215                }
6216            }
6217
6218            return new ParceledListSlice<PackageInfo>(list);
6219        }
6220    }
6221
6222    @Override
6223    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
6224        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
6225        flags = updateFlagsForApplication(flags, userId, null);
6226        final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0;
6227
6228        // writer
6229        synchronized (mPackages) {
6230            ArrayList<ApplicationInfo> list;
6231            if (listUninstalled) {
6232                list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size());
6233                for (PackageSetting ps : mSettings.mPackages.values()) {
6234                    ApplicationInfo ai;
6235                    if (ps.pkg != null) {
6236                        ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
6237                                ps.readUserState(userId), userId);
6238                    } else {
6239                        ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId);
6240                    }
6241                    if (ai != null) {
6242                        list.add(ai);
6243                    }
6244                }
6245            } else {
6246                list = new ArrayList<ApplicationInfo>(mPackages.size());
6247                for (PackageParser.Package p : mPackages.values()) {
6248                    if (p.mExtras != null) {
6249                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
6250                                ((PackageSetting)p.mExtras).readUserState(userId), userId);
6251                        if (ai != null) {
6252                            list.add(ai);
6253                        }
6254                    }
6255                }
6256            }
6257
6258            return new ParceledListSlice<ApplicationInfo>(list);
6259        }
6260    }
6261
6262    @Override
6263    public ParceledListSlice<EphemeralApplicationInfo> getEphemeralApplications(int userId) {
6264        if (DISABLE_EPHEMERAL_APPS) {
6265            return null;
6266        }
6267
6268        mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS,
6269                "getEphemeralApplications");
6270        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6271                true /* requireFullPermission */, false /* checkShell */,
6272                "getEphemeralApplications");
6273        synchronized (mPackages) {
6274            List<EphemeralApplicationInfo> ephemeralApps = mEphemeralApplicationRegistry
6275                    .getEphemeralApplicationsLPw(userId);
6276            if (ephemeralApps != null) {
6277                return new ParceledListSlice<>(ephemeralApps);
6278            }
6279        }
6280        return null;
6281    }
6282
6283    @Override
6284    public boolean isEphemeralApplication(String packageName, int userId) {
6285        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6286                true /* requireFullPermission */, false /* checkShell */,
6287                "isEphemeral");
6288        if (DISABLE_EPHEMERAL_APPS) {
6289            return false;
6290        }
6291
6292        if (!isCallerSameApp(packageName)) {
6293            return false;
6294        }
6295        synchronized (mPackages) {
6296            PackageParser.Package pkg = mPackages.get(packageName);
6297            if (pkg != null) {
6298                return pkg.applicationInfo.isEphemeralApp();
6299            }
6300        }
6301        return false;
6302    }
6303
6304    @Override
6305    public byte[] getEphemeralApplicationCookie(String packageName, int userId) {
6306        if (DISABLE_EPHEMERAL_APPS) {
6307            return null;
6308        }
6309
6310        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6311                true /* requireFullPermission */, false /* checkShell */,
6312                "getCookie");
6313        if (!isCallerSameApp(packageName)) {
6314            return null;
6315        }
6316        synchronized (mPackages) {
6317            return mEphemeralApplicationRegistry.getEphemeralApplicationCookieLPw(
6318                    packageName, userId);
6319        }
6320    }
6321
6322    @Override
6323    public boolean setEphemeralApplicationCookie(String packageName, byte[] cookie, int userId) {
6324        if (DISABLE_EPHEMERAL_APPS) {
6325            return true;
6326        }
6327
6328        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6329                true /* requireFullPermission */, true /* checkShell */,
6330                "setCookie");
6331        if (!isCallerSameApp(packageName)) {
6332            return false;
6333        }
6334        synchronized (mPackages) {
6335            return mEphemeralApplicationRegistry.setEphemeralApplicationCookieLPw(
6336                    packageName, cookie, userId);
6337        }
6338    }
6339
6340    @Override
6341    public Bitmap getEphemeralApplicationIcon(String packageName, int userId) {
6342        if (DISABLE_EPHEMERAL_APPS) {
6343            return null;
6344        }
6345
6346        mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS,
6347                "getEphemeralApplicationIcon");
6348        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6349                true /* requireFullPermission */, false /* checkShell */,
6350                "getEphemeralApplicationIcon");
6351        synchronized (mPackages) {
6352            return mEphemeralApplicationRegistry.getEphemeralApplicationIconLPw(
6353                    packageName, userId);
6354        }
6355    }
6356
6357    private boolean isCallerSameApp(String packageName) {
6358        PackageParser.Package pkg = mPackages.get(packageName);
6359        return pkg != null
6360                && UserHandle.getAppId(Binder.getCallingUid()) == pkg.applicationInfo.uid;
6361    }
6362
6363    @Override
6364    public @NonNull ParceledListSlice<ApplicationInfo> getPersistentApplications(int flags) {
6365        return new ParceledListSlice<>(getPersistentApplicationsInternal(flags));
6366    }
6367
6368    private @NonNull List<ApplicationInfo> getPersistentApplicationsInternal(int flags) {
6369        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
6370
6371        // reader
6372        synchronized (mPackages) {
6373            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
6374            final int userId = UserHandle.getCallingUserId();
6375            while (i.hasNext()) {
6376                final PackageParser.Package p = i.next();
6377                if (p.applicationInfo == null) continue;
6378
6379                final boolean matchesUnaware = ((flags & MATCH_DIRECT_BOOT_UNAWARE) != 0)
6380                        && !p.applicationInfo.isDirectBootAware();
6381                final boolean matchesAware = ((flags & MATCH_DIRECT_BOOT_AWARE) != 0)
6382                        && p.applicationInfo.isDirectBootAware();
6383
6384                if ((p.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0
6385                        && (!mSafeMode || isSystemApp(p))
6386                        && (matchesUnaware || matchesAware)) {
6387                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
6388                    if (ps != null) {
6389                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
6390                                ps.readUserState(userId), userId);
6391                        if (ai != null) {
6392                            finalList.add(ai);
6393                        }
6394                    }
6395                }
6396            }
6397        }
6398
6399        return finalList;
6400    }
6401
6402    @Override
6403    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
6404        if (!sUserManager.exists(userId)) return null;
6405        flags = updateFlagsForComponent(flags, userId, name);
6406        // reader
6407        synchronized (mPackages) {
6408            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
6409            PackageSetting ps = provider != null
6410                    ? mSettings.mPackages.get(provider.owner.packageName)
6411                    : null;
6412            return ps != null
6413                    && mSettings.isEnabledAndMatchLPr(provider.info, flags, userId)
6414                    ? PackageParser.generateProviderInfo(provider, flags,
6415                            ps.readUserState(userId), userId)
6416                    : null;
6417        }
6418    }
6419
6420    /**
6421     * @deprecated
6422     */
6423    @Deprecated
6424    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
6425        // reader
6426        synchronized (mPackages) {
6427            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
6428                    .entrySet().iterator();
6429            final int userId = UserHandle.getCallingUserId();
6430            while (i.hasNext()) {
6431                Map.Entry<String, PackageParser.Provider> entry = i.next();
6432                PackageParser.Provider p = entry.getValue();
6433                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
6434
6435                if (ps != null && p.syncable
6436                        && (!mSafeMode || (p.info.applicationInfo.flags
6437                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
6438                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
6439                            ps.readUserState(userId), userId);
6440                    if (info != null) {
6441                        outNames.add(entry.getKey());
6442                        outInfo.add(info);
6443                    }
6444                }
6445            }
6446        }
6447    }
6448
6449    @Override
6450    public @NonNull ParceledListSlice<ProviderInfo> queryContentProviders(String processName,
6451            int uid, int flags) {
6452        final int userId = processName != null ? UserHandle.getUserId(uid)
6453                : UserHandle.getCallingUserId();
6454        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
6455        flags = updateFlagsForComponent(flags, userId, processName);
6456
6457        ArrayList<ProviderInfo> finalList = null;
6458        // reader
6459        synchronized (mPackages) {
6460            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
6461            while (i.hasNext()) {
6462                final PackageParser.Provider p = i.next();
6463                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
6464                if (ps != null && p.info.authority != null
6465                        && (processName == null
6466                                || (p.info.processName.equals(processName)
6467                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
6468                        && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
6469                    if (finalList == null) {
6470                        finalList = new ArrayList<ProviderInfo>(3);
6471                    }
6472                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
6473                            ps.readUserState(userId), userId);
6474                    if (info != null) {
6475                        finalList.add(info);
6476                    }
6477                }
6478            }
6479        }
6480
6481        if (finalList != null) {
6482            Collections.sort(finalList, mProviderInitOrderSorter);
6483            return new ParceledListSlice<ProviderInfo>(finalList);
6484        }
6485
6486        return ParceledListSlice.emptyList();
6487    }
6488
6489    @Override
6490    public InstrumentationInfo getInstrumentationInfo(ComponentName name, int flags) {
6491        // reader
6492        synchronized (mPackages) {
6493            final PackageParser.Instrumentation i = mInstrumentation.get(name);
6494            return PackageParser.generateInstrumentationInfo(i, flags);
6495        }
6496    }
6497
6498    @Override
6499    public @NonNull ParceledListSlice<InstrumentationInfo> queryInstrumentation(
6500            String targetPackage, int flags) {
6501        return new ParceledListSlice<>(queryInstrumentationInternal(targetPackage, flags));
6502    }
6503
6504    private @NonNull List<InstrumentationInfo> queryInstrumentationInternal(String targetPackage,
6505            int flags) {
6506        ArrayList<InstrumentationInfo> finalList = new ArrayList<InstrumentationInfo>();
6507
6508        // reader
6509        synchronized (mPackages) {
6510            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
6511            while (i.hasNext()) {
6512                final PackageParser.Instrumentation p = i.next();
6513                if (targetPackage == null
6514                        || targetPackage.equals(p.info.targetPackage)) {
6515                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
6516                            flags);
6517                    if (ii != null) {
6518                        finalList.add(ii);
6519                    }
6520                }
6521            }
6522        }
6523
6524        return finalList;
6525    }
6526
6527    private void createIdmapsForPackageLI(PackageParser.Package pkg) {
6528        ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName);
6529        if (overlays == null) {
6530            Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages");
6531            return;
6532        }
6533        for (PackageParser.Package opkg : overlays.values()) {
6534            // Not much to do if idmap fails: we already logged the error
6535            // and we certainly don't want to abort installation of pkg simply
6536            // because an overlay didn't fit properly. For these reasons,
6537            // ignore the return value of createIdmapForPackagePairLI.
6538            createIdmapForPackagePairLI(pkg, opkg);
6539        }
6540    }
6541
6542    private boolean createIdmapForPackagePairLI(PackageParser.Package pkg,
6543            PackageParser.Package opkg) {
6544        if (!opkg.mTrustedOverlay) {
6545            Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " +
6546                    opkg.baseCodePath + ": overlay not trusted");
6547            return false;
6548        }
6549        ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName);
6550        if (overlaySet == null) {
6551            Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " +
6552                    opkg.baseCodePath + " but target package has no known overlays");
6553            return false;
6554        }
6555        final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
6556        // TODO: generate idmap for split APKs
6557        try {
6558            mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid);
6559        } catch (InstallerException e) {
6560            Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and "
6561                    + opkg.baseCodePath);
6562            return false;
6563        }
6564        PackageParser.Package[] overlayArray =
6565            overlaySet.values().toArray(new PackageParser.Package[0]);
6566        Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() {
6567            public int compare(PackageParser.Package p1, PackageParser.Package p2) {
6568                return p1.mOverlayPriority - p2.mOverlayPriority;
6569            }
6570        };
6571        Arrays.sort(overlayArray, cmp);
6572
6573        pkg.applicationInfo.resourceDirs = new String[overlayArray.length];
6574        int i = 0;
6575        for (PackageParser.Package p : overlayArray) {
6576            pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath;
6577        }
6578        return true;
6579    }
6580
6581    private void scanDirTracedLI(File dir, final int parseFlags, int scanFlags, long currentTime) {
6582        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir");
6583        try {
6584            scanDirLI(dir, parseFlags, scanFlags, currentTime);
6585        } finally {
6586            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6587        }
6588    }
6589
6590    private void scanDirLI(File dir, final int parseFlags, int scanFlags, long currentTime) {
6591        final File[] files = dir.listFiles();
6592        if (ArrayUtils.isEmpty(files)) {
6593            Log.d(TAG, "No files in app dir " + dir);
6594            return;
6595        }
6596
6597        if (DEBUG_PACKAGE_SCANNING) {
6598            Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags
6599                    + " flags=0x" + Integer.toHexString(parseFlags));
6600        }
6601
6602        for (File file : files) {
6603            final boolean isPackage = (isApkFile(file) || file.isDirectory())
6604                    && !PackageInstallerService.isStageName(file.getName());
6605            if (!isPackage) {
6606                // Ignore entries which are not packages
6607                continue;
6608            }
6609            try {
6610                scanPackageTracedLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK,
6611                        scanFlags, currentTime, null);
6612            } catch (PackageManagerException e) {
6613                Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage());
6614
6615                // Delete invalid userdata apps
6616                if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
6617                        e.error == PackageManager.INSTALL_FAILED_INVALID_APK) {
6618                    logCriticalInfo(Log.WARN, "Deleting invalid package at " + file);
6619                    removeCodePathLI(file);
6620                }
6621            }
6622        }
6623    }
6624
6625    private static File getSettingsProblemFile() {
6626        File dataDir = Environment.getDataDirectory();
6627        File systemDir = new File(dataDir, "system");
6628        File fname = new File(systemDir, "uiderrors.txt");
6629        return fname;
6630    }
6631
6632    static void reportSettingsProblem(int priority, String msg) {
6633        logCriticalInfo(priority, msg);
6634    }
6635
6636    static void logCriticalInfo(int priority, String msg) {
6637        Slog.println(priority, TAG, msg);
6638        EventLogTags.writePmCriticalInfo(msg);
6639        try {
6640            File fname = getSettingsProblemFile();
6641            FileOutputStream out = new FileOutputStream(fname, true);
6642            PrintWriter pw = new FastPrintWriter(out);
6643            SimpleDateFormat formatter = new SimpleDateFormat();
6644            String dateString = formatter.format(new Date(System.currentTimeMillis()));
6645            pw.println(dateString + ": " + msg);
6646            pw.close();
6647            FileUtils.setPermissions(
6648                    fname.toString(),
6649                    FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
6650                    -1, -1);
6651        } catch (java.io.IOException e) {
6652        }
6653    }
6654
6655    private void collectCertificatesLI(PackageSetting ps, PackageParser.Package pkg, File srcFile,
6656            final int policyFlags) throws PackageManagerException {
6657        if (ps != null
6658                && ps.codePath.equals(srcFile)
6659                && ps.timeStamp == srcFile.lastModified()
6660                && !isCompatSignatureUpdateNeeded(pkg)
6661                && !isRecoverSignatureUpdateNeeded(pkg)) {
6662            long mSigningKeySetId = ps.keySetData.getProperSigningKeySet();
6663            KeySetManagerService ksms = mSettings.mKeySetManagerService;
6664            ArraySet<PublicKey> signingKs;
6665            synchronized (mPackages) {
6666                signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId);
6667            }
6668            if (ps.signatures.mSignatures != null
6669                    && ps.signatures.mSignatures.length != 0
6670                    && signingKs != null) {
6671                // Optimization: reuse the existing cached certificates
6672                // if the package appears to be unchanged.
6673                pkg.mSignatures = ps.signatures.mSignatures;
6674                pkg.mSigningKeys = signingKs;
6675                return;
6676            }
6677
6678            Slog.w(TAG, "PackageSetting for " + ps.name
6679                    + " is missing signatures.  Collecting certs again to recover them.");
6680        } else {
6681            Log.i(TAG, srcFile.toString() + " changed; collecting certs");
6682        }
6683
6684        try {
6685            PackageParser.collectCertificates(pkg, policyFlags);
6686        } catch (PackageParserException e) {
6687            throw PackageManagerException.from(e);
6688        }
6689    }
6690
6691    /**
6692     *  Traces a package scan.
6693     *  @see #scanPackageLI(File, int, int, long, UserHandle)
6694     */
6695    private PackageParser.Package scanPackageTracedLI(File scanFile, final int parseFlags,
6696            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
6697        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage");
6698        try {
6699            return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user);
6700        } finally {
6701            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6702        }
6703    }
6704
6705    /**
6706     *  Scans a package and returns the newly parsed package.
6707     *  Returns {@code null} in case of errors and the error code is stored in mLastScanError
6708     */
6709    private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags,
6710            long currentTime, UserHandle user) throws PackageManagerException {
6711        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
6712        PackageParser pp = new PackageParser();
6713        pp.setSeparateProcesses(mSeparateProcesses);
6714        pp.setOnlyCoreApps(mOnlyCore);
6715        pp.setDisplayMetrics(mMetrics);
6716
6717        if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) {
6718            parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY;
6719        }
6720
6721        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
6722        final PackageParser.Package pkg;
6723        try {
6724            pkg = pp.parsePackage(scanFile, parseFlags);
6725        } catch (PackageParserException e) {
6726            throw PackageManagerException.from(e);
6727        } finally {
6728            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6729        }
6730
6731        return scanPackageLI(pkg, scanFile, parseFlags, scanFlags, currentTime, user);
6732    }
6733
6734    /**
6735     *  Scans a package and returns the newly parsed package.
6736     *  @throws PackageManagerException on a parse error.
6737     */
6738    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, File scanFile,
6739            final int policyFlags, int scanFlags, long currentTime, UserHandle user)
6740            throws PackageManagerException {
6741        // If the package has children and this is the first dive in the function
6742        // we scan the package with the SCAN_CHECK_ONLY flag set to see whether all
6743        // packages (parent and children) would be successfully scanned before the
6744        // actual scan since scanning mutates internal state and we want to atomically
6745        // install the package and its children.
6746        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
6747            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
6748                scanFlags |= SCAN_CHECK_ONLY;
6749            }
6750        } else {
6751            scanFlags &= ~SCAN_CHECK_ONLY;
6752        }
6753
6754        // Scan the parent
6755        PackageParser.Package scannedPkg = scanPackageInternalLI(pkg, scanFile, policyFlags,
6756                scanFlags, currentTime, user);
6757
6758        // Scan the children
6759        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
6760        for (int i = 0; i < childCount; i++) {
6761            PackageParser.Package childPackage = pkg.childPackages.get(i);
6762            scanPackageInternalLI(childPackage, scanFile, policyFlags, scanFlags,
6763                    currentTime, user);
6764        }
6765
6766
6767        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
6768            return scanPackageLI(pkg, scanFile, policyFlags, scanFlags, currentTime, user);
6769        }
6770
6771        return scannedPkg;
6772    }
6773
6774    /**
6775     *  Scans a package and returns the newly parsed package.
6776     *  @throws PackageManagerException on a parse error.
6777     */
6778    private PackageParser.Package scanPackageInternalLI(PackageParser.Package pkg, File scanFile,
6779            int policyFlags, int scanFlags, long currentTime, UserHandle user)
6780            throws PackageManagerException {
6781        PackageSetting ps = null;
6782        PackageSetting updatedPkg;
6783        // reader
6784        synchronized (mPackages) {
6785            // Look to see if we already know about this package.
6786            String oldName = mSettings.mRenamedPackages.get(pkg.packageName);
6787            if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
6788                // This package has been renamed to its original name.  Let's
6789                // use that.
6790                ps = mSettings.peekPackageLPr(oldName);
6791            }
6792            // If there was no original package, see one for the real package name.
6793            if (ps == null) {
6794                ps = mSettings.peekPackageLPr(pkg.packageName);
6795            }
6796            // Check to see if this package could be hiding/updating a system
6797            // package.  Must look for it either under the original or real
6798            // package name depending on our state.
6799            updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName);
6800            if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg);
6801
6802            // If this is a package we don't know about on the system partition, we
6803            // may need to remove disabled child packages on the system partition
6804            // or may need to not add child packages if the parent apk is updated
6805            // on the data partition and no longer defines this child package.
6806            if ((policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) {
6807                // If this is a parent package for an updated system app and this system
6808                // app got an OTA update which no longer defines some of the child packages
6809                // we have to prune them from the disabled system packages.
6810                PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName);
6811                if (disabledPs != null) {
6812                    final int scannedChildCount = (pkg.childPackages != null)
6813                            ? pkg.childPackages.size() : 0;
6814                    final int disabledChildCount = disabledPs.childPackageNames != null
6815                            ? disabledPs.childPackageNames.size() : 0;
6816                    for (int i = 0; i < disabledChildCount; i++) {
6817                        String disabledChildPackageName = disabledPs.childPackageNames.get(i);
6818                        boolean disabledPackageAvailable = false;
6819                        for (int j = 0; j < scannedChildCount; j++) {
6820                            PackageParser.Package childPkg = pkg.childPackages.get(j);
6821                            if (childPkg.packageName.equals(disabledChildPackageName)) {
6822                                disabledPackageAvailable = true;
6823                                break;
6824                            }
6825                         }
6826                         if (!disabledPackageAvailable) {
6827                             mSettings.removeDisabledSystemPackageLPw(disabledChildPackageName);
6828                         }
6829                    }
6830                }
6831            }
6832        }
6833
6834        boolean updatedPkgBetter = false;
6835        // First check if this is a system package that may involve an update
6836        if (updatedPkg != null && (policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) {
6837            // If new package is not located in "/system/priv-app" (e.g. due to an OTA),
6838            // it needs to drop FLAG_PRIVILEGED.
6839            if (locationIsPrivileged(scanFile)) {
6840                updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
6841            } else {
6842                updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
6843            }
6844
6845            if (ps != null && !ps.codePath.equals(scanFile)) {
6846                // The path has changed from what was last scanned...  check the
6847                // version of the new path against what we have stored to determine
6848                // what to do.
6849                if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath);
6850                if (pkg.mVersionCode <= ps.versionCode) {
6851                    // The system package has been updated and the code path does not match
6852                    // Ignore entry. Skip it.
6853                    if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile
6854                            + " ignored: updated version " + ps.versionCode
6855                            + " better than this " + pkg.mVersionCode);
6856                    if (!updatedPkg.codePath.equals(scanFile)) {
6857                        Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg "
6858                                + ps.name + " changing from " + updatedPkg.codePathString
6859                                + " to " + scanFile);
6860                        updatedPkg.codePath = scanFile;
6861                        updatedPkg.codePathString = scanFile.toString();
6862                        updatedPkg.resourcePath = scanFile;
6863                        updatedPkg.resourcePathString = scanFile.toString();
6864                    }
6865                    updatedPkg.pkg = pkg;
6866                    updatedPkg.versionCode = pkg.mVersionCode;
6867
6868                    // Update the disabled system child packages to point to the package too.
6869                    final int childCount = updatedPkg.childPackageNames != null
6870                            ? updatedPkg.childPackageNames.size() : 0;
6871                    for (int i = 0; i < childCount; i++) {
6872                        String childPackageName = updatedPkg.childPackageNames.get(i);
6873                        PackageSetting updatedChildPkg = mSettings.getDisabledSystemPkgLPr(
6874                                childPackageName);
6875                        if (updatedChildPkg != null) {
6876                            updatedChildPkg.pkg = pkg;
6877                            updatedChildPkg.versionCode = pkg.mVersionCode;
6878                        }
6879                    }
6880
6881                    throw new PackageManagerException(Log.WARN, "Package " + ps.name + " at "
6882                            + scanFile + " ignored: updated version " + ps.versionCode
6883                            + " better than this " + pkg.mVersionCode);
6884                } else {
6885                    // The current app on the system partition is better than
6886                    // what we have updated to on the data partition; switch
6887                    // back to the system partition version.
6888                    // At this point, its safely assumed that package installation for
6889                    // apps in system partition will go through. If not there won't be a working
6890                    // version of the app
6891                    // writer
6892                    synchronized (mPackages) {
6893                        // Just remove the loaded entries from package lists.
6894                        mPackages.remove(ps.name);
6895                    }
6896
6897                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
6898                            + " reverting from " + ps.codePathString
6899                            + ": new version " + pkg.mVersionCode
6900                            + " better than installed " + ps.versionCode);
6901
6902                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
6903                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
6904                    synchronized (mInstallLock) {
6905                        args.cleanUpResourcesLI();
6906                    }
6907                    synchronized (mPackages) {
6908                        mSettings.enableSystemPackageLPw(ps.name);
6909                    }
6910                    updatedPkgBetter = true;
6911                }
6912            }
6913        }
6914
6915        if (updatedPkg != null) {
6916            // An updated system app will not have the PARSE_IS_SYSTEM flag set
6917            // initially
6918            policyFlags |= PackageParser.PARSE_IS_SYSTEM;
6919
6920            // An updated privileged app will not have the PARSE_IS_PRIVILEGED
6921            // flag set initially
6922            if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
6923                policyFlags |= PackageParser.PARSE_IS_PRIVILEGED;
6924            }
6925        }
6926
6927        // Verify certificates against what was last scanned
6928        collectCertificatesLI(ps, pkg, scanFile, policyFlags);
6929
6930        /*
6931         * A new system app appeared, but we already had a non-system one of the
6932         * same name installed earlier.
6933         */
6934        boolean shouldHideSystemApp = false;
6935        if (updatedPkg == null && ps != null
6936                && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) {
6937            /*
6938             * Check to make sure the signatures match first. If they don't,
6939             * wipe the installed application and its data.
6940             */
6941            if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures)
6942                    != PackageManager.SIGNATURE_MATCH) {
6943                logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but"
6944                        + " signatures don't match existing userdata copy; removing");
6945                try (PackageFreezer freezer = freezePackage(pkg.packageName,
6946                        "scanPackageInternalLI")) {
6947                    deletePackageLIF(pkg.packageName, null, true, null, 0, null, false, null);
6948                }
6949                ps = null;
6950            } else {
6951                /*
6952                 * If the newly-added system app is an older version than the
6953                 * already installed version, hide it. It will be scanned later
6954                 * and re-added like an update.
6955                 */
6956                if (pkg.mVersionCode <= ps.versionCode) {
6957                    shouldHideSystemApp = true;
6958                    logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile
6959                            + " but new version " + pkg.mVersionCode + " better than installed "
6960                            + ps.versionCode + "; hiding system");
6961                } else {
6962                    /*
6963                     * The newly found system app is a newer version that the
6964                     * one previously installed. Simply remove the
6965                     * already-installed application and replace it with our own
6966                     * while keeping the application data.
6967                     */
6968                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
6969                            + " reverting from " + ps.codePathString + ": new version "
6970                            + pkg.mVersionCode + " better than installed " + ps.versionCode);
6971                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
6972                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
6973                    synchronized (mInstallLock) {
6974                        args.cleanUpResourcesLI();
6975                    }
6976                }
6977            }
6978        }
6979
6980        // The apk is forward locked (not public) if its code and resources
6981        // are kept in different files. (except for app in either system or
6982        // vendor path).
6983        // TODO grab this value from PackageSettings
6984        if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
6985            if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
6986                policyFlags |= PackageParser.PARSE_FORWARD_LOCK;
6987            }
6988        }
6989
6990        // TODO: extend to support forward-locked splits
6991        String resourcePath = null;
6992        String baseResourcePath = null;
6993        if ((policyFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) {
6994            if (ps != null && ps.resourcePathString != null) {
6995                resourcePath = ps.resourcePathString;
6996                baseResourcePath = ps.resourcePathString;
6997            } else {
6998                // Should not happen at all. Just log an error.
6999                Slog.e(TAG, "Resource path not set for package " + pkg.packageName);
7000            }
7001        } else {
7002            resourcePath = pkg.codePath;
7003            baseResourcePath = pkg.baseCodePath;
7004        }
7005
7006        // Set application objects path explicitly.
7007        pkg.setApplicationVolumeUuid(pkg.volumeUuid);
7008        pkg.setApplicationInfoCodePath(pkg.codePath);
7009        pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
7010        pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
7011        pkg.setApplicationInfoResourcePath(resourcePath);
7012        pkg.setApplicationInfoBaseResourcePath(baseResourcePath);
7013        pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
7014
7015        // Note that we invoke the following method only if we are about to unpack an application
7016        PackageParser.Package scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags
7017                | SCAN_UPDATE_SIGNATURE, currentTime, user);
7018
7019        /*
7020         * If the system app should be overridden by a previously installed
7021         * data, hide the system app now and let the /data/app scan pick it up
7022         * again.
7023         */
7024        if (shouldHideSystemApp) {
7025            synchronized (mPackages) {
7026                mSettings.disableSystemPackageLPw(pkg.packageName, true);
7027            }
7028        }
7029
7030        return scannedPkg;
7031    }
7032
7033    private static String fixProcessName(String defProcessName,
7034            String processName, int uid) {
7035        if (processName == null) {
7036            return defProcessName;
7037        }
7038        return processName;
7039    }
7040
7041    private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg)
7042            throws PackageManagerException {
7043        if (pkgSetting.signatures.mSignatures != null) {
7044            // Already existing package. Make sure signatures match
7045            boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures)
7046                    == PackageManager.SIGNATURE_MATCH;
7047            if (!match) {
7048                match = compareSignaturesCompat(pkgSetting.signatures, pkg)
7049                        == PackageManager.SIGNATURE_MATCH;
7050            }
7051            if (!match) {
7052                match = compareSignaturesRecover(pkgSetting.signatures, pkg)
7053                        == PackageManager.SIGNATURE_MATCH;
7054            }
7055            if (!match) {
7056                throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
7057                        + pkg.packageName + " signatures do not match the "
7058                        + "previously installed version; ignoring!");
7059            }
7060        }
7061
7062        // Check for shared user signatures
7063        if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
7064            // Already existing package. Make sure signatures match
7065            boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
7066                    pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
7067            if (!match) {
7068                match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg)
7069                        == PackageManager.SIGNATURE_MATCH;
7070            }
7071            if (!match) {
7072                match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg)
7073                        == PackageManager.SIGNATURE_MATCH;
7074            }
7075            if (!match) {
7076                throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
7077                        "Package " + pkg.packageName
7078                        + " has no signatures that match those in shared user "
7079                        + pkgSetting.sharedUser.name + "; ignoring!");
7080            }
7081        }
7082    }
7083
7084    /**
7085     * Enforces that only the system UID or root's UID can call a method exposed
7086     * via Binder.
7087     *
7088     * @param message used as message if SecurityException is thrown
7089     * @throws SecurityException if the caller is not system or root
7090     */
7091    private static final void enforceSystemOrRoot(String message) {
7092        final int uid = Binder.getCallingUid();
7093        if (uid != Process.SYSTEM_UID && uid != 0) {
7094            throw new SecurityException(message);
7095        }
7096    }
7097
7098    @Override
7099    public void performFstrimIfNeeded() {
7100        enforceSystemOrRoot("Only the system can request fstrim");
7101
7102        // Before everything else, see whether we need to fstrim.
7103        try {
7104            IMountService ms = PackageHelper.getMountService();
7105            if (ms != null) {
7106                final boolean isUpgrade = isUpgrade();
7107                boolean doTrim = isUpgrade;
7108                if (doTrim) {
7109                    Slog.w(TAG, "Running disk maintenance immediately due to system update");
7110                } else {
7111                    final long interval = android.provider.Settings.Global.getLong(
7112                            mContext.getContentResolver(),
7113                            android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL,
7114                            DEFAULT_MANDATORY_FSTRIM_INTERVAL);
7115                    if (interval > 0) {
7116                        final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance();
7117                        if (timeSinceLast > interval) {
7118                            doTrim = true;
7119                            Slog.w(TAG, "No disk maintenance in " + timeSinceLast
7120                                    + "; running immediately");
7121                        }
7122                    }
7123                }
7124                if (doTrim) {
7125                    if (!isFirstBoot()) {
7126                        try {
7127                            ActivityManagerNative.getDefault().showBootMessage(
7128                                    mContext.getResources().getString(
7129                                            R.string.android_upgrading_fstrim), true);
7130                        } catch (RemoteException e) {
7131                        }
7132                    }
7133                    ms.runMaintenance();
7134                }
7135            } else {
7136                Slog.e(TAG, "Mount service unavailable!");
7137            }
7138        } catch (RemoteException e) {
7139            // Can't happen; MountService is local
7140        }
7141    }
7142
7143    @Override
7144    public void updatePackagesIfNeeded() {
7145        enforceSystemOrRoot("Only the system can request package update");
7146
7147        // We need to re-extract after an OTA.
7148        boolean causeUpgrade = isUpgrade();
7149
7150        // First boot or factory reset.
7151        // Note: we also handle devices that are upgrading to N right now as if it is their
7152        //       first boot, as they do not have profile data.
7153        boolean causeFirstBoot = isFirstBoot() || mIsPreNUpgrade;
7154
7155        // We need to re-extract after a pruned cache, as AoT-ed files will be out of date.
7156        boolean causePrunedCache = VMRuntime.didPruneDalvikCache();
7157
7158        if (!causeUpgrade && !causeFirstBoot && !causePrunedCache) {
7159            return;
7160        }
7161
7162        List<PackageParser.Package> pkgs;
7163        synchronized (mPackages) {
7164            pkgs = PackageManagerServiceUtils.getPackagesForDexopt(mPackages.values(), this);
7165        }
7166
7167        int curr = 0;
7168        int total = pkgs.size();
7169        for (PackageParser.Package pkg : pkgs) {
7170            curr++;
7171
7172            if (!PackageDexOptimizer.canOptimizePackage(pkg)) {
7173                if (DEBUG_DEXOPT) {
7174                    Log.i(TAG, "Skipping update of of non-optimizable app " + pkg.packageName);
7175                }
7176                continue;
7177            }
7178
7179            if (DEBUG_DEXOPT) {
7180                Log.i(TAG, "Extracting app " + curr + " of " + total + ": " + pkg.packageName);
7181            }
7182
7183            if (!isFirstBoot()) {
7184                try {
7185                    ActivityManagerNative.getDefault().showBootMessage(
7186                            mContext.getResources().getString(R.string.android_upgrading_apk,
7187                                    curr, total), true);
7188                } catch (RemoteException e) {
7189                }
7190            }
7191
7192            performDexOpt(pkg.packageName,
7193                    null /* instructionSet */,
7194                    true /* checkProfiles */,
7195                    causeFirstBoot ? REASON_FIRST_BOOT : REASON_BOOT,
7196                    false /* force */);
7197        }
7198    }
7199
7200    @Override
7201    public void notifyPackageUse(String packageName, int reason) {
7202        synchronized (mPackages) {
7203            PackageParser.Package p = mPackages.get(packageName);
7204            if (p == null) {
7205                return;
7206            }
7207            p.mLastPackageUsageTimeInMills[reason] = System.currentTimeMillis();
7208        }
7209    }
7210
7211    // TODO: this is not used nor needed. Delete it.
7212    @Override
7213    public boolean performDexOptIfNeeded(String packageName, String instructionSet) {
7214        return performDexOptTraced(packageName, instructionSet, false /* checkProfiles */,
7215                getFullCompilerFilter(), false /* force */);
7216    }
7217
7218    @Override
7219    public boolean performDexOpt(String packageName, String instructionSet,
7220            boolean checkProfiles, int compileReason, boolean force) {
7221        return performDexOptTraced(packageName, instructionSet, checkProfiles,
7222                getCompilerFilterForReason(compileReason), force);
7223    }
7224
7225    @Override
7226    public boolean performDexOptMode(String packageName, String instructionSet,
7227            boolean checkProfiles, String targetCompilerFilter, boolean force) {
7228        return performDexOptTraced(packageName, instructionSet, checkProfiles,
7229                targetCompilerFilter, force);
7230    }
7231
7232    private boolean performDexOptTraced(String packageName, String instructionSet,
7233                boolean checkProfiles, String targetCompilerFilter, boolean force) {
7234        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
7235        try {
7236            return performDexOptInternal(packageName, instructionSet, checkProfiles,
7237                    targetCompilerFilter, force);
7238        } finally {
7239            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7240        }
7241    }
7242
7243    // Run dexopt on a given package. Returns true if dexopt did not fail, i.e.
7244    // if the package can now be considered up to date for the given filter.
7245    private boolean performDexOptInternal(String packageName, String instructionSet,
7246                boolean checkProfiles, String targetCompilerFilter, boolean force) {
7247        PackageParser.Package p;
7248        final String targetInstructionSet;
7249        synchronized (mPackages) {
7250            p = mPackages.get(packageName);
7251            if (p == null) {
7252                return false;
7253            }
7254            mPackageUsage.write(false);
7255
7256            targetInstructionSet = instructionSet != null ? instructionSet :
7257                    getPrimaryInstructionSet(p.applicationInfo);
7258        }
7259        long callingId = Binder.clearCallingIdentity();
7260        try {
7261            synchronized (mInstallLock) {
7262                final String[] instructionSets = new String[] { targetInstructionSet };
7263                int result = performDexOptInternalWithDependenciesLI(p, instructionSets,
7264                        checkProfiles, targetCompilerFilter, force);
7265                return result != PackageDexOptimizer.DEX_OPT_FAILED;
7266            }
7267        } finally {
7268            Binder.restoreCallingIdentity(callingId);
7269        }
7270    }
7271
7272    public ArraySet<String> getOptimizablePackages() {
7273        ArraySet<String> pkgs = new ArraySet<String>();
7274        synchronized (mPackages) {
7275            for (PackageParser.Package p : mPackages.values()) {
7276                if (PackageDexOptimizer.canOptimizePackage(p)) {
7277                    pkgs.add(p.packageName);
7278                }
7279            }
7280        }
7281        return pkgs;
7282    }
7283
7284    private int performDexOptInternalWithDependenciesLI(PackageParser.Package p,
7285            String instructionSets[], boolean checkProfiles, String targetCompilerFilter,
7286            boolean force) {
7287        // Select the dex optimizer based on the force parameter.
7288        // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to
7289        //       allocate an object here.
7290        PackageDexOptimizer pdo = force
7291                ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer)
7292                : mPackageDexOptimizer;
7293
7294        // Optimize all dependencies first. Note: we ignore the return value and march on
7295        // on errors.
7296        Collection<PackageParser.Package> deps = findSharedNonSystemLibraries(p);
7297        if (!deps.isEmpty()) {
7298            for (PackageParser.Package depPackage : deps) {
7299                // TODO: Analyze and investigate if we (should) profile libraries.
7300                // Currently this will do a full compilation of the library by default.
7301                pdo.performDexOpt(depPackage, instructionSets, false /* checkProfiles */,
7302                        getCompilerFilterForReason(REASON_NON_SYSTEM_LIBRARY));
7303            }
7304        }
7305
7306        return pdo.performDexOpt(p, instructionSets, checkProfiles, targetCompilerFilter);
7307    }
7308
7309    Collection<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package p) {
7310        if (p.usesLibraries != null || p.usesOptionalLibraries != null) {
7311            ArrayList<PackageParser.Package> retValue = new ArrayList<>();
7312            Set<String> collectedNames = new HashSet<>();
7313            findSharedNonSystemLibrariesRecursive(p, retValue, collectedNames);
7314
7315            retValue.remove(p);
7316
7317            return retValue;
7318        } else {
7319            return Collections.emptyList();
7320        }
7321    }
7322
7323    private void findSharedNonSystemLibrariesRecursive(PackageParser.Package p,
7324            Collection<PackageParser.Package> collected, Set<String> collectedNames) {
7325        if (!collectedNames.contains(p.packageName)) {
7326            collectedNames.add(p.packageName);
7327            collected.add(p);
7328
7329            if (p.usesLibraries != null) {
7330                findSharedNonSystemLibrariesRecursive(p.usesLibraries, collected, collectedNames);
7331            }
7332            if (p.usesOptionalLibraries != null) {
7333                findSharedNonSystemLibrariesRecursive(p.usesOptionalLibraries, collected,
7334                        collectedNames);
7335            }
7336        }
7337    }
7338
7339    private void findSharedNonSystemLibrariesRecursive(Collection<String> libs,
7340            Collection<PackageParser.Package> collected, Set<String> collectedNames) {
7341        for (String libName : libs) {
7342            PackageParser.Package libPkg = findSharedNonSystemLibrary(libName);
7343            if (libPkg != null) {
7344                findSharedNonSystemLibrariesRecursive(libPkg, collected, collectedNames);
7345            }
7346        }
7347    }
7348
7349    private PackageParser.Package findSharedNonSystemLibrary(String libName) {
7350        synchronized (mPackages) {
7351            PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName);
7352            if (lib != null && lib.apk != null) {
7353                return mPackages.get(lib.apk);
7354            }
7355        }
7356        return null;
7357    }
7358
7359    public void shutdown() {
7360        mPackageUsage.write(true);
7361    }
7362
7363    @Override
7364    public void forceDexOpt(String packageName) {
7365        enforceSystemOrRoot("forceDexOpt");
7366
7367        PackageParser.Package pkg;
7368        synchronized (mPackages) {
7369            pkg = mPackages.get(packageName);
7370            if (pkg == null) {
7371                throw new IllegalArgumentException("Unknown package: " + packageName);
7372            }
7373        }
7374
7375        synchronized (mInstallLock) {
7376            final String[] instructionSets = new String[] {
7377                    getPrimaryInstructionSet(pkg.applicationInfo) };
7378
7379            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
7380
7381            // Whoever is calling forceDexOpt wants a fully compiled package.
7382            // Don't use profiles since that may cause compilation to be skipped.
7383            final int res = performDexOptInternalWithDependenciesLI(pkg, instructionSets,
7384                    false /* checkProfiles */, getCompilerFilterForReason(REASON_FORCED_DEXOPT),
7385                    true /* force */);
7386
7387            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7388            if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) {
7389                throw new IllegalStateException("Failed to dexopt: " + res);
7390            }
7391        }
7392    }
7393
7394    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
7395        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
7396            Slog.w(TAG, "Unable to update from " + oldPkg.name
7397                    + " to " + newPkg.packageName
7398                    + ": old package not in system partition");
7399            return false;
7400        } else if (mPackages.get(oldPkg.name) != null) {
7401            Slog.w(TAG, "Unable to update from " + oldPkg.name
7402                    + " to " + newPkg.packageName
7403                    + ": old package still exists");
7404            return false;
7405        }
7406        return true;
7407    }
7408
7409    void removeCodePathLI(File codePath) {
7410        if (codePath.isDirectory()) {
7411            try {
7412                mInstaller.rmPackageDir(codePath.getAbsolutePath());
7413            } catch (InstallerException e) {
7414                Slog.w(TAG, "Failed to remove code path", e);
7415            }
7416        } else {
7417            codePath.delete();
7418        }
7419    }
7420
7421    private int[] resolveUserIds(int userId) {
7422        return (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() : new int[] { userId };
7423    }
7424
7425    private void clearAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
7426        if (pkg == null) {
7427            Slog.wtf(TAG, "Package was null!", new Throwable());
7428            return;
7429        }
7430        clearAppDataLeafLIF(pkg, userId, flags);
7431        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7432        for (int i = 0; i < childCount; i++) {
7433            clearAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
7434        }
7435    }
7436
7437    private void clearAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
7438        final PackageSetting ps;
7439        synchronized (mPackages) {
7440            ps = mSettings.mPackages.get(pkg.packageName);
7441        }
7442        for (int realUserId : resolveUserIds(userId)) {
7443            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
7444            try {
7445                mInstaller.clearAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
7446                        ceDataInode);
7447            } catch (InstallerException e) {
7448                Slog.w(TAG, String.valueOf(e));
7449            }
7450        }
7451    }
7452
7453    private void destroyAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
7454        if (pkg == null) {
7455            Slog.wtf(TAG, "Package was null!", new Throwable());
7456            return;
7457        }
7458        destroyAppDataLeafLIF(pkg, userId, flags);
7459        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7460        for (int i = 0; i < childCount; i++) {
7461            destroyAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
7462        }
7463    }
7464
7465    private void destroyAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
7466        final PackageSetting ps;
7467        synchronized (mPackages) {
7468            ps = mSettings.mPackages.get(pkg.packageName);
7469        }
7470        for (int realUserId : resolveUserIds(userId)) {
7471            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
7472            try {
7473                mInstaller.destroyAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
7474                        ceDataInode);
7475            } catch (InstallerException e) {
7476                Slog.w(TAG, String.valueOf(e));
7477            }
7478        }
7479    }
7480
7481    private void destroyAppProfilesLIF(PackageParser.Package pkg) {
7482        if (pkg == null) {
7483            Slog.wtf(TAG, "Package was null!", new Throwable());
7484            return;
7485        }
7486        destroyAppProfilesLeafLIF(pkg);
7487        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7488        for (int i = 0; i < childCount; i++) {
7489            destroyAppProfilesLeafLIF(pkg.childPackages.get(i));
7490        }
7491    }
7492
7493    private void destroyAppProfilesLeafLIF(PackageParser.Package pkg) {
7494        try {
7495            mInstaller.destroyAppProfiles(pkg.packageName);
7496        } catch (InstallerException e) {
7497            Slog.w(TAG, String.valueOf(e));
7498        }
7499    }
7500
7501    private void clearAppProfilesLIF(PackageParser.Package pkg) {
7502        if (pkg == null) {
7503            Slog.wtf(TAG, "Package was null!", new Throwable());
7504            return;
7505        }
7506        clearAppProfilesLeafLIF(pkg);
7507        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7508        for (int i = 0; i < childCount; i++) {
7509            clearAppProfilesLeafLIF(pkg.childPackages.get(i));
7510        }
7511    }
7512
7513    private void clearAppProfilesLeafLIF(PackageParser.Package pkg) {
7514        try {
7515            mInstaller.clearAppProfiles(pkg.packageName);
7516        } catch (InstallerException e) {
7517            Slog.w(TAG, String.valueOf(e));
7518        }
7519    }
7520
7521    private void setInstallAndUpdateTime(PackageParser.Package pkg, long firstInstallTime,
7522            long lastUpdateTime) {
7523        // Set parent install/update time
7524        PackageSetting ps = (PackageSetting) pkg.mExtras;
7525        if (ps != null) {
7526            ps.firstInstallTime = firstInstallTime;
7527            ps.lastUpdateTime = lastUpdateTime;
7528        }
7529        // Set children install/update time
7530        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7531        for (int i = 0; i < childCount; i++) {
7532            PackageParser.Package childPkg = pkg.childPackages.get(i);
7533            ps = (PackageSetting) childPkg.mExtras;
7534            if (ps != null) {
7535                ps.firstInstallTime = firstInstallTime;
7536                ps.lastUpdateTime = lastUpdateTime;
7537            }
7538        }
7539    }
7540
7541    private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file,
7542            PackageParser.Package changingLib) {
7543        if (file.path != null) {
7544            usesLibraryFiles.add(file.path);
7545            return;
7546        }
7547        PackageParser.Package p = mPackages.get(file.apk);
7548        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
7549            // If we are doing this while in the middle of updating a library apk,
7550            // then we need to make sure to use that new apk for determining the
7551            // dependencies here.  (We haven't yet finished committing the new apk
7552            // to the package manager state.)
7553            if (p == null || p.packageName.equals(changingLib.packageName)) {
7554                p = changingLib;
7555            }
7556        }
7557        if (p != null) {
7558            usesLibraryFiles.addAll(p.getAllCodePaths());
7559        }
7560    }
7561
7562    private void updateSharedLibrariesLPw(PackageParser.Package pkg,
7563            PackageParser.Package changingLib) throws PackageManagerException {
7564        if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) {
7565            final ArraySet<String> usesLibraryFiles = new ArraySet<>();
7566            int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0;
7567            for (int i=0; i<N; i++) {
7568                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i));
7569                if (file == null) {
7570                    throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
7571                            "Package " + pkg.packageName + " requires unavailable shared library "
7572                            + pkg.usesLibraries.get(i) + "; failing!");
7573                }
7574                addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
7575            }
7576            N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0;
7577            for (int i=0; i<N; i++) {
7578                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i));
7579                if (file == null) {
7580                    Slog.w(TAG, "Package " + pkg.packageName
7581                            + " desires unavailable shared library "
7582                            + pkg.usesOptionalLibraries.get(i) + "; ignoring!");
7583                } else {
7584                    addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
7585                }
7586            }
7587            N = usesLibraryFiles.size();
7588            if (N > 0) {
7589                pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]);
7590            } else {
7591                pkg.usesLibraryFiles = null;
7592            }
7593        }
7594    }
7595
7596    private static boolean hasString(List<String> list, List<String> which) {
7597        if (list == null) {
7598            return false;
7599        }
7600        for (int i=list.size()-1; i>=0; i--) {
7601            for (int j=which.size()-1; j>=0; j--) {
7602                if (which.get(j).equals(list.get(i))) {
7603                    return true;
7604                }
7605            }
7606        }
7607        return false;
7608    }
7609
7610    private void updateAllSharedLibrariesLPw() {
7611        for (PackageParser.Package pkg : mPackages.values()) {
7612            try {
7613                updateSharedLibrariesLPw(pkg, null);
7614            } catch (PackageManagerException e) {
7615                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
7616            }
7617        }
7618    }
7619
7620    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
7621            PackageParser.Package changingPkg) {
7622        ArrayList<PackageParser.Package> res = null;
7623        for (PackageParser.Package pkg : mPackages.values()) {
7624            if (hasString(pkg.usesLibraries, changingPkg.libraryNames)
7625                    || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) {
7626                if (res == null) {
7627                    res = new ArrayList<PackageParser.Package>();
7628                }
7629                res.add(pkg);
7630                try {
7631                    updateSharedLibrariesLPw(pkg, changingPkg);
7632                } catch (PackageManagerException e) {
7633                    Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
7634                }
7635            }
7636        }
7637        return res;
7638    }
7639
7640    /**
7641     * Derive the value of the {@code cpuAbiOverride} based on the provided
7642     * value and an optional stored value from the package settings.
7643     */
7644    private static String deriveAbiOverride(String abiOverride, PackageSetting settings) {
7645        String cpuAbiOverride = null;
7646
7647        if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) {
7648            cpuAbiOverride = null;
7649        } else if (abiOverride != null) {
7650            cpuAbiOverride = abiOverride;
7651        } else if (settings != null) {
7652            cpuAbiOverride = settings.cpuAbiOverrideString;
7653        }
7654
7655        return cpuAbiOverride;
7656    }
7657
7658    private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg,
7659            final int policyFlags, int scanFlags, long currentTime, UserHandle user)
7660                    throws PackageManagerException {
7661        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage");
7662        // If the package has children and this is the first dive in the function
7663        // we recursively scan the package with the SCAN_CHECK_ONLY flag set to see
7664        // whether all packages (parent and children) would be successfully scanned
7665        // before the actual scan since scanning mutates internal state and we want
7666        // to atomically install the package and its children.
7667        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
7668            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
7669                scanFlags |= SCAN_CHECK_ONLY;
7670            }
7671        } else {
7672            scanFlags &= ~SCAN_CHECK_ONLY;
7673        }
7674
7675        final PackageParser.Package scannedPkg;
7676        try {
7677            // Scan the parent
7678            scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags, currentTime, user);
7679            // Scan the children
7680            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7681            for (int i = 0; i < childCount; i++) {
7682                PackageParser.Package childPkg = pkg.childPackages.get(i);
7683                scanPackageLI(childPkg, policyFlags,
7684                        scanFlags, currentTime, user);
7685            }
7686        } finally {
7687            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7688        }
7689
7690        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
7691            return scanPackageTracedLI(pkg, policyFlags, scanFlags, currentTime, user);
7692        }
7693
7694        return scannedPkg;
7695    }
7696
7697    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, final int policyFlags,
7698            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
7699        boolean success = false;
7700        try {
7701            final PackageParser.Package res = scanPackageDirtyLI(pkg, policyFlags, scanFlags,
7702                    currentTime, user);
7703            success = true;
7704            return res;
7705        } finally {
7706            if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
7707                // DELETE_DATA_ON_FAILURES is only used by frozen paths
7708                destroyAppDataLIF(pkg, UserHandle.USER_ALL,
7709                        StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
7710                destroyAppProfilesLIF(pkg);
7711            }
7712        }
7713    }
7714
7715    /**
7716     * Returns {@code true} if the given file contains code. Otherwise {@code false}.
7717     */
7718    private static boolean apkHasCode(String fileName) {
7719        StrictJarFile jarFile = null;
7720        try {
7721            jarFile = new StrictJarFile(fileName,
7722                    false /*verify*/, false /*signatureSchemeRollbackProtectionsEnforced*/);
7723            return jarFile.findEntry("classes.dex") != null;
7724        } catch (IOException ignore) {
7725        } finally {
7726            try {
7727                jarFile.close();
7728            } catch (IOException ignore) {}
7729        }
7730        return false;
7731    }
7732
7733    /**
7734     * Enforces code policy for the package. This ensures that if an APK has
7735     * declared hasCode="true" in its manifest that the APK actually contains
7736     * code.
7737     *
7738     * @throws PackageManagerException If bytecode could not be found when it should exist
7739     */
7740    private static void enforceCodePolicy(PackageParser.Package pkg)
7741            throws PackageManagerException {
7742        final boolean shouldHaveCode =
7743                (pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) != 0;
7744        if (shouldHaveCode && !apkHasCode(pkg.baseCodePath)) {
7745            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
7746                    "Package " + pkg.baseCodePath + " code is missing");
7747        }
7748
7749        if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
7750            for (int i = 0; i < pkg.splitCodePaths.length; i++) {
7751                final boolean splitShouldHaveCode =
7752                        (pkg.splitFlags[i] & ApplicationInfo.FLAG_HAS_CODE) != 0;
7753                if (splitShouldHaveCode && !apkHasCode(pkg.splitCodePaths[i])) {
7754                    throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
7755                            "Package " + pkg.splitCodePaths[i] + " code is missing");
7756                }
7757            }
7758        }
7759    }
7760
7761    private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg,
7762            final int policyFlags, final int scanFlags, long currentTime, UserHandle user)
7763            throws PackageManagerException {
7764        final File scanFile = new File(pkg.codePath);
7765        if (pkg.applicationInfo.getCodePath() == null ||
7766                pkg.applicationInfo.getResourcePath() == null) {
7767            // Bail out. The resource and code paths haven't been set.
7768            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
7769                    "Code and resource paths haven't been set correctly");
7770        }
7771
7772        // Apply policy
7773        if ((policyFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
7774            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
7775            if (pkg.applicationInfo.isDirectBootAware()) {
7776                // we're direct boot aware; set for all components
7777                for (PackageParser.Service s : pkg.services) {
7778                    s.info.encryptionAware = s.info.directBootAware = true;
7779                }
7780                for (PackageParser.Provider p : pkg.providers) {
7781                    p.info.encryptionAware = p.info.directBootAware = true;
7782                }
7783                for (PackageParser.Activity a : pkg.activities) {
7784                    a.info.encryptionAware = a.info.directBootAware = true;
7785                }
7786                for (PackageParser.Activity r : pkg.receivers) {
7787                    r.info.encryptionAware = r.info.directBootAware = true;
7788                }
7789            }
7790        } else {
7791            // Only allow system apps to be flagged as core apps.
7792            pkg.coreApp = false;
7793            // clear flags not applicable to regular apps
7794            pkg.applicationInfo.privateFlags &=
7795                    ~ApplicationInfo.PRIVATE_FLAG_DEFAULT_TO_DEVICE_PROTECTED_STORAGE;
7796            pkg.applicationInfo.privateFlags &=
7797                    ~ApplicationInfo.PRIVATE_FLAG_DIRECT_BOOT_AWARE;
7798        }
7799        pkg.mTrustedOverlay = (policyFlags&PackageParser.PARSE_TRUSTED_OVERLAY) != 0;
7800
7801        if ((policyFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) {
7802            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
7803        }
7804
7805        if ((policyFlags & PackageParser.PARSE_ENFORCE_CODE) != 0) {
7806            enforceCodePolicy(pkg);
7807        }
7808
7809        if (mCustomResolverComponentName != null &&
7810                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
7811            setUpCustomResolverActivity(pkg);
7812        }
7813
7814        if (pkg.packageName.equals("android")) {
7815            synchronized (mPackages) {
7816                if (mAndroidApplication != null) {
7817                    Slog.w(TAG, "*************************************************");
7818                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
7819                    Slog.w(TAG, " file=" + scanFile);
7820                    Slog.w(TAG, "*************************************************");
7821                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
7822                            "Core android package being redefined.  Skipping.");
7823                }
7824
7825                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
7826                    // Set up information for our fall-back user intent resolution activity.
7827                    mPlatformPackage = pkg;
7828                    pkg.mVersionCode = mSdkVersion;
7829                    mAndroidApplication = pkg.applicationInfo;
7830
7831                    if (!mResolverReplaced) {
7832                        mResolveActivity.applicationInfo = mAndroidApplication;
7833                        mResolveActivity.name = ResolverActivity.class.getName();
7834                        mResolveActivity.packageName = mAndroidApplication.packageName;
7835                        mResolveActivity.processName = "system:ui";
7836                        mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
7837                        mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
7838                        mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
7839                        mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert;
7840                        mResolveActivity.exported = true;
7841                        mResolveActivity.enabled = true;
7842                        mResolveInfo.activityInfo = mResolveActivity;
7843                        mResolveInfo.priority = 0;
7844                        mResolveInfo.preferredOrder = 0;
7845                        mResolveInfo.match = 0;
7846                        mResolveComponentName = new ComponentName(
7847                                mAndroidApplication.packageName, mResolveActivity.name);
7848                    }
7849                }
7850            }
7851        }
7852
7853        if (DEBUG_PACKAGE_SCANNING) {
7854            if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
7855                Log.d(TAG, "Scanning package " + pkg.packageName);
7856        }
7857
7858        synchronized (mPackages) {
7859            if (mPackages.containsKey(pkg.packageName)
7860                    || mSharedLibraries.containsKey(pkg.packageName)) {
7861                throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
7862                        "Application package " + pkg.packageName
7863                                + " already installed.  Skipping duplicate.");
7864            }
7865
7866            // If we're only installing presumed-existing packages, require that the
7867            // scanned APK is both already known and at the path previously established
7868            // for it.  Previously unknown packages we pick up normally, but if we have an
7869            // a priori expectation about this package's install presence, enforce it.
7870            // With a singular exception for new system packages. When an OTA contains
7871            // a new system package, we allow the codepath to change from a system location
7872            // to the user-installed location. If we don't allow this change, any newer,
7873            // user-installed version of the application will be ignored.
7874            if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) {
7875                if (mExpectingBetter.containsKey(pkg.packageName)) {
7876                    logCriticalInfo(Log.WARN,
7877                            "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName);
7878                } else {
7879                    PackageSetting known = mSettings.peekPackageLPr(pkg.packageName);
7880                    if (known != null) {
7881                        if (DEBUG_PACKAGE_SCANNING) {
7882                            Log.d(TAG, "Examining " + pkg.codePath
7883                                    + " and requiring known paths " + known.codePathString
7884                                    + " & " + known.resourcePathString);
7885                        }
7886                        if (!pkg.applicationInfo.getCodePath().equals(known.codePathString)
7887                                || !pkg.applicationInfo.getResourcePath().equals(
7888                                known.resourcePathString)) {
7889                            throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED,
7890                                    "Application package " + pkg.packageName
7891                                            + " found at " + pkg.applicationInfo.getCodePath()
7892                                            + " but expected at " + known.codePathString
7893                                            + "; ignoring.");
7894                        }
7895                    }
7896                }
7897            }
7898        }
7899
7900        // Initialize package source and resource directories
7901        File destCodeFile = new File(pkg.applicationInfo.getCodePath());
7902        File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
7903
7904        SharedUserSetting suid = null;
7905        PackageSetting pkgSetting = null;
7906
7907        if (!isSystemApp(pkg)) {
7908            // Only system apps can use these features.
7909            pkg.mOriginalPackages = null;
7910            pkg.mRealPackage = null;
7911            pkg.mAdoptPermissions = null;
7912        }
7913
7914        // Getting the package setting may have a side-effect, so if we
7915        // are only checking if scan would succeed, stash a copy of the
7916        // old setting to restore at the end.
7917        PackageSetting nonMutatedPs = null;
7918
7919        // writer
7920        synchronized (mPackages) {
7921            if (pkg.mSharedUserId != null) {
7922                suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true);
7923                if (suid == null) {
7924                    throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
7925                            "Creating application package " + pkg.packageName
7926                            + " for shared user failed");
7927                }
7928                if (DEBUG_PACKAGE_SCANNING) {
7929                    if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
7930                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId
7931                                + "): packages=" + suid.packages);
7932                }
7933            }
7934
7935            // Check if we are renaming from an original package name.
7936            PackageSetting origPackage = null;
7937            String realName = null;
7938            if (pkg.mOriginalPackages != null) {
7939                // This package may need to be renamed to a previously
7940                // installed name.  Let's check on that...
7941                final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage);
7942                if (pkg.mOriginalPackages.contains(renamed)) {
7943                    // This package had originally been installed as the
7944                    // original name, and we have already taken care of
7945                    // transitioning to the new one.  Just update the new
7946                    // one to continue using the old name.
7947                    realName = pkg.mRealPackage;
7948                    if (!pkg.packageName.equals(renamed)) {
7949                        // Callers into this function may have already taken
7950                        // care of renaming the package; only do it here if
7951                        // it is not already done.
7952                        pkg.setPackageName(renamed);
7953                    }
7954
7955                } else {
7956                    for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
7957                        if ((origPackage = mSettings.peekPackageLPr(
7958                                pkg.mOriginalPackages.get(i))) != null) {
7959                            // We do have the package already installed under its
7960                            // original name...  should we use it?
7961                            if (!verifyPackageUpdateLPr(origPackage, pkg)) {
7962                                // New package is not compatible with original.
7963                                origPackage = null;
7964                                continue;
7965                            } else if (origPackage.sharedUser != null) {
7966                                // Make sure uid is compatible between packages.
7967                                if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
7968                                    Slog.w(TAG, "Unable to migrate data from " + origPackage.name
7969                                            + " to " + pkg.packageName + ": old uid "
7970                                            + origPackage.sharedUser.name
7971                                            + " differs from " + pkg.mSharedUserId);
7972                                    origPackage = null;
7973                                    continue;
7974                                }
7975                                // TODO: Add case when shared user id is added [b/28144775]
7976                            } else {
7977                                if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
7978                                        + pkg.packageName + " to old name " + origPackage.name);
7979                            }
7980                            break;
7981                        }
7982                    }
7983                }
7984            }
7985
7986            if (mTransferedPackages.contains(pkg.packageName)) {
7987                Slog.w(TAG, "Package " + pkg.packageName
7988                        + " was transferred to another, but its .apk remains");
7989            }
7990
7991            // See comments in nonMutatedPs declaration
7992            if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
7993                PackageSetting foundPs = mSettings.peekPackageLPr(pkg.packageName);
7994                if (foundPs != null) {
7995                    nonMutatedPs = new PackageSetting(foundPs);
7996                }
7997            }
7998
7999            // Just create the setting, don't add it yet. For already existing packages
8000            // the PkgSetting exists already and doesn't have to be created.
8001            pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile,
8002                    destResourceFile, pkg.applicationInfo.nativeLibraryRootDir,
8003                    pkg.applicationInfo.primaryCpuAbi,
8004                    pkg.applicationInfo.secondaryCpuAbi,
8005                    pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags,
8006                    user, false);
8007            if (pkgSetting == null) {
8008                throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
8009                        "Creating application package " + pkg.packageName + " failed");
8010            }
8011
8012            if (pkgSetting.origPackage != null) {
8013                // If we are first transitioning from an original package,
8014                // fix up the new package's name now.  We need to do this after
8015                // looking up the package under its new name, so getPackageLP
8016                // can take care of fiddling things correctly.
8017                pkg.setPackageName(origPackage.name);
8018
8019                // File a report about this.
8020                String msg = "New package " + pkgSetting.realName
8021                        + " renamed to replace old package " + pkgSetting.name;
8022                reportSettingsProblem(Log.WARN, msg);
8023
8024                // Make a note of it.
8025                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
8026                    mTransferedPackages.add(origPackage.name);
8027                }
8028
8029                // No longer need to retain this.
8030                pkgSetting.origPackage = null;
8031            }
8032
8033            if ((scanFlags & SCAN_CHECK_ONLY) == 0 && realName != null) {
8034                // Make a note of it.
8035                mTransferedPackages.add(pkg.packageName);
8036            }
8037
8038            if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) {
8039                pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
8040            }
8041
8042            if ((policyFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
8043                // Check all shared libraries and map to their actual file path.
8044                // We only do this here for apps not on a system dir, because those
8045                // are the only ones that can fail an install due to this.  We
8046                // will take care of the system apps by updating all of their
8047                // library paths after the scan is done.
8048                updateSharedLibrariesLPw(pkg, null);
8049            }
8050
8051            if (mFoundPolicyFile) {
8052                SELinuxMMAC.assignSeinfoValue(pkg);
8053            }
8054
8055            pkg.applicationInfo.uid = pkgSetting.appId;
8056            pkg.mExtras = pkgSetting;
8057            if (shouldCheckUpgradeKeySetLP(pkgSetting, scanFlags)) {
8058                if (checkUpgradeKeySetLP(pkgSetting, pkg)) {
8059                    // We just determined the app is signed correctly, so bring
8060                    // over the latest parsed certs.
8061                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
8062                } else {
8063                    if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
8064                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
8065                                "Package " + pkg.packageName + " upgrade keys do not match the "
8066                                + "previously installed version");
8067                    } else {
8068                        pkgSetting.signatures.mSignatures = pkg.mSignatures;
8069                        String msg = "System package " + pkg.packageName
8070                            + " signature changed; retaining data.";
8071                        reportSettingsProblem(Log.WARN, msg);
8072                    }
8073                }
8074            } else {
8075                try {
8076                    verifySignaturesLP(pkgSetting, pkg);
8077                    // We just determined the app is signed correctly, so bring
8078                    // over the latest parsed certs.
8079                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
8080                } catch (PackageManagerException e) {
8081                    if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
8082                        throw e;
8083                    }
8084                    // The signature has changed, but this package is in the system
8085                    // image...  let's recover!
8086                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
8087                    // However...  if this package is part of a shared user, but it
8088                    // doesn't match the signature of the shared user, let's fail.
8089                    // What this means is that you can't change the signatures
8090                    // associated with an overall shared user, which doesn't seem all
8091                    // that unreasonable.
8092                    if (pkgSetting.sharedUser != null) {
8093                        if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
8094                                              pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
8095                            throw new PackageManagerException(
8096                                    INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
8097                                            "Signature mismatch for shared user: "
8098                                            + pkgSetting.sharedUser);
8099                        }
8100                    }
8101                    // File a report about this.
8102                    String msg = "System package " + pkg.packageName
8103                        + " signature changed; retaining data.";
8104                    reportSettingsProblem(Log.WARN, msg);
8105                }
8106            }
8107            // Verify that this new package doesn't have any content providers
8108            // that conflict with existing packages.  Only do this if the
8109            // package isn't already installed, since we don't want to break
8110            // things that are installed.
8111            if ((scanFlags & SCAN_NEW_INSTALL) != 0) {
8112                final int N = pkg.providers.size();
8113                int i;
8114                for (i=0; i<N; i++) {
8115                    PackageParser.Provider p = pkg.providers.get(i);
8116                    if (p.info.authority != null) {
8117                        String names[] = p.info.authority.split(";");
8118                        for (int j = 0; j < names.length; j++) {
8119                            if (mProvidersByAuthority.containsKey(names[j])) {
8120                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
8121                                final String otherPackageName =
8122                                        ((other != null && other.getComponentName() != null) ?
8123                                                other.getComponentName().getPackageName() : "?");
8124                                throw new PackageManagerException(
8125                                        INSTALL_FAILED_CONFLICTING_PROVIDER,
8126                                                "Can't install because provider name " + names[j]
8127                                                + " (in package " + pkg.applicationInfo.packageName
8128                                                + ") is already used by " + otherPackageName);
8129                            }
8130                        }
8131                    }
8132                }
8133            }
8134
8135            if ((scanFlags & SCAN_CHECK_ONLY) == 0 && pkg.mAdoptPermissions != null) {
8136                // This package wants to adopt ownership of permissions from
8137                // another package.
8138                for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
8139                    final String origName = pkg.mAdoptPermissions.get(i);
8140                    final PackageSetting orig = mSettings.peekPackageLPr(origName);
8141                    if (orig != null) {
8142                        if (verifyPackageUpdateLPr(orig, pkg)) {
8143                            Slog.i(TAG, "Adopting permissions from " + origName + " to "
8144                                    + pkg.packageName);
8145                            mSettings.transferPermissionsLPw(origName, pkg.packageName);
8146                        }
8147                    }
8148                }
8149            }
8150        }
8151
8152        final String pkgName = pkg.packageName;
8153
8154        final long scanFileTime = scanFile.lastModified();
8155        final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0;
8156        pkg.applicationInfo.processName = fixProcessName(
8157                pkg.applicationInfo.packageName,
8158                pkg.applicationInfo.processName,
8159                pkg.applicationInfo.uid);
8160
8161        if (pkg != mPlatformPackage) {
8162            // Get all of our default paths setup
8163            pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM);
8164        }
8165
8166        final String path = scanFile.getPath();
8167        final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
8168
8169        if ((scanFlags & SCAN_NEW_INSTALL) == 0) {
8170            derivePackageAbi(pkg, scanFile, cpuAbiOverride, true /* extract libs */);
8171
8172            // Some system apps still use directory structure for native libraries
8173            // in which case we might end up not detecting abi solely based on apk
8174            // structure. Try to detect abi based on directory structure.
8175            if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() &&
8176                    pkg.applicationInfo.primaryCpuAbi == null) {
8177                setBundledAppAbisAndRoots(pkg, pkgSetting);
8178                setNativeLibraryPaths(pkg);
8179            }
8180
8181        } else {
8182            if ((scanFlags & SCAN_MOVE) != 0) {
8183                // We haven't run dex-opt for this move (since we've moved the compiled output too)
8184                // but we already have this packages package info in the PackageSetting. We just
8185                // use that and derive the native library path based on the new codepath.
8186                pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString;
8187                pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString;
8188            }
8189
8190            // Set native library paths again. For moves, the path will be updated based on the
8191            // ABIs we've determined above. For non-moves, the path will be updated based on the
8192            // ABIs we determined during compilation, but the path will depend on the final
8193            // package path (after the rename away from the stage path).
8194            setNativeLibraryPaths(pkg);
8195        }
8196
8197        // This is a special case for the "system" package, where the ABI is
8198        // dictated by the zygote configuration (and init.rc). We should keep track
8199        // of this ABI so that we can deal with "normal" applications that run under
8200        // the same UID correctly.
8201        if (mPlatformPackage == pkg) {
8202            pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
8203                    Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
8204        }
8205
8206        // If there's a mismatch between the abi-override in the package setting
8207        // and the abiOverride specified for the install. Warn about this because we
8208        // would've already compiled the app without taking the package setting into
8209        // account.
8210        if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) {
8211            if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) {
8212                Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride +
8213                        " for package " + pkg.packageName);
8214            }
8215        }
8216
8217        pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
8218        pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
8219        pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
8220
8221        // Copy the derived override back to the parsed package, so that we can
8222        // update the package settings accordingly.
8223        pkg.cpuAbiOverride = cpuAbiOverride;
8224
8225        if (DEBUG_ABI_SELECTION) {
8226            Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName
8227                    + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
8228                    + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
8229        }
8230
8231        // Push the derived path down into PackageSettings so we know what to
8232        // clean up at uninstall time.
8233        pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
8234
8235        if (DEBUG_ABI_SELECTION) {
8236            Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
8237                    " primary=" + pkg.applicationInfo.primaryCpuAbi +
8238                    " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
8239        }
8240
8241        if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
8242            // We don't do this here during boot because we can do it all
8243            // at once after scanning all existing packages.
8244            //
8245            // We also do this *before* we perform dexopt on this package, so that
8246            // we can avoid redundant dexopts, and also to make sure we've got the
8247            // code and package path correct.
8248            adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages,
8249                    pkg, true /* boot complete */);
8250        }
8251
8252        if (mFactoryTest && pkg.requestedPermissions.contains(
8253                android.Manifest.permission.FACTORY_TEST)) {
8254            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
8255        }
8256
8257        ArrayList<PackageParser.Package> clientLibPkgs = null;
8258
8259        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
8260            if (nonMutatedPs != null) {
8261                synchronized (mPackages) {
8262                    mSettings.mPackages.put(nonMutatedPs.name, nonMutatedPs);
8263                }
8264            }
8265            return pkg;
8266        }
8267
8268        // Only privileged apps and updated privileged apps can add child packages.
8269        if (pkg.childPackages != null && !pkg.childPackages.isEmpty()) {
8270            if ((policyFlags & PARSE_IS_PRIVILEGED) == 0) {
8271                throw new PackageManagerException("Only privileged apps and updated "
8272                        + "privileged apps can add child packages. Ignoring package "
8273                        + pkg.packageName);
8274            }
8275            final int childCount = pkg.childPackages.size();
8276            for (int i = 0; i < childCount; i++) {
8277                PackageParser.Package childPkg = pkg.childPackages.get(i);
8278                if (mSettings.hasOtherDisabledSystemPkgWithChildLPr(pkg.packageName,
8279                        childPkg.packageName)) {
8280                    throw new PackageManagerException("Cannot override a child package of "
8281                            + "another disabled system app. Ignoring package " + pkg.packageName);
8282                }
8283            }
8284        }
8285
8286        // writer
8287        synchronized (mPackages) {
8288            if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
8289                // Only system apps can add new shared libraries.
8290                if (pkg.libraryNames != null) {
8291                    for (int i=0; i<pkg.libraryNames.size(); i++) {
8292                        String name = pkg.libraryNames.get(i);
8293                        boolean allowed = false;
8294                        if (pkg.isUpdatedSystemApp()) {
8295                            // New library entries can only be added through the
8296                            // system image.  This is important to get rid of a lot
8297                            // of nasty edge cases: for example if we allowed a non-
8298                            // system update of the app to add a library, then uninstalling
8299                            // the update would make the library go away, and assumptions
8300                            // we made such as through app install filtering would now
8301                            // have allowed apps on the device which aren't compatible
8302                            // with it.  Better to just have the restriction here, be
8303                            // conservative, and create many fewer cases that can negatively
8304                            // impact the user experience.
8305                            final PackageSetting sysPs = mSettings
8306                                    .getDisabledSystemPkgLPr(pkg.packageName);
8307                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
8308                                for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) {
8309                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
8310                                        allowed = true;
8311                                        break;
8312                                    }
8313                                }
8314                            }
8315                        } else {
8316                            allowed = true;
8317                        }
8318                        if (allowed) {
8319                            if (!mSharedLibraries.containsKey(name)) {
8320                                mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName));
8321                            } else if (!name.equals(pkg.packageName)) {
8322                                Slog.w(TAG, "Package " + pkg.packageName + " library "
8323                                        + name + " already exists; skipping");
8324                            }
8325                        } else {
8326                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
8327                                    + name + " that is not declared on system image; skipping");
8328                        }
8329                    }
8330                    if ((scanFlags & SCAN_BOOTING) == 0) {
8331                        // If we are not booting, we need to update any applications
8332                        // that are clients of our shared library.  If we are booting,
8333                        // this will all be done once the scan is complete.
8334                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
8335                    }
8336                }
8337            }
8338        }
8339
8340        if ((scanFlags & SCAN_BOOTING) != 0) {
8341            // No apps can run during boot scan, so they don't need to be frozen
8342        } else if ((scanFlags & SCAN_DONT_KILL_APP) != 0) {
8343            // Caller asked to not kill app, so it's probably not frozen
8344        } else if ((scanFlags & SCAN_IGNORE_FROZEN) != 0) {
8345            // Caller asked us to ignore frozen check for some reason; they
8346            // probably didn't know the package name
8347        } else {
8348            // We're doing major surgery on this package, so it better be frozen
8349            // right now to keep it from launching
8350            checkPackageFrozen(pkgName);
8351        }
8352
8353        // Also need to kill any apps that are dependent on the library.
8354        if (clientLibPkgs != null) {
8355            for (int i=0; i<clientLibPkgs.size(); i++) {
8356                PackageParser.Package clientPkg = clientLibPkgs.get(i);
8357                killApplication(clientPkg.applicationInfo.packageName,
8358                        clientPkg.applicationInfo.uid, "update lib");
8359            }
8360        }
8361
8362        // Make sure we're not adding any bogus keyset info
8363        KeySetManagerService ksms = mSettings.mKeySetManagerService;
8364        ksms.assertScannedPackageValid(pkg);
8365
8366        // writer
8367        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
8368
8369        boolean createIdmapFailed = false;
8370        synchronized (mPackages) {
8371            // We don't expect installation to fail beyond this point
8372
8373            // Add the new setting to mSettings
8374            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
8375            // Add the new setting to mPackages
8376            mPackages.put(pkg.applicationInfo.packageName, pkg);
8377            // Make sure we don't accidentally delete its data.
8378            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
8379            while (iter.hasNext()) {
8380                PackageCleanItem item = iter.next();
8381                if (pkgName.equals(item.packageName)) {
8382                    iter.remove();
8383                }
8384            }
8385
8386            // Take care of first install / last update times.
8387            if (currentTime != 0) {
8388                if (pkgSetting.firstInstallTime == 0) {
8389                    pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
8390                } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) {
8391                    pkgSetting.lastUpdateTime = currentTime;
8392                }
8393            } else if (pkgSetting.firstInstallTime == 0) {
8394                // We need *something*.  Take time time stamp of the file.
8395                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
8396            } else if ((policyFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
8397                if (scanFileTime != pkgSetting.timeStamp) {
8398                    // A package on the system image has changed; consider this
8399                    // to be an update.
8400                    pkgSetting.lastUpdateTime = scanFileTime;
8401                }
8402            }
8403
8404            // Add the package's KeySets to the global KeySetManagerService
8405            ksms.addScannedPackageLPw(pkg);
8406
8407            int N = pkg.providers.size();
8408            StringBuilder r = null;
8409            int i;
8410            for (i=0; i<N; i++) {
8411                PackageParser.Provider p = pkg.providers.get(i);
8412                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
8413                        p.info.processName, pkg.applicationInfo.uid);
8414                mProviders.addProvider(p);
8415                p.syncable = p.info.isSyncable;
8416                if (p.info.authority != null) {
8417                    String names[] = p.info.authority.split(";");
8418                    p.info.authority = null;
8419                    for (int j = 0; j < names.length; j++) {
8420                        if (j == 1 && p.syncable) {
8421                            // We only want the first authority for a provider to possibly be
8422                            // syncable, so if we already added this provider using a different
8423                            // authority clear the syncable flag. We copy the provider before
8424                            // changing it because the mProviders object contains a reference
8425                            // to a provider that we don't want to change.
8426                            // Only do this for the second authority since the resulting provider
8427                            // object can be the same for all future authorities for this provider.
8428                            p = new PackageParser.Provider(p);
8429                            p.syncable = false;
8430                        }
8431                        if (!mProvidersByAuthority.containsKey(names[j])) {
8432                            mProvidersByAuthority.put(names[j], p);
8433                            if (p.info.authority == null) {
8434                                p.info.authority = names[j];
8435                            } else {
8436                                p.info.authority = p.info.authority + ";" + names[j];
8437                            }
8438                            if (DEBUG_PACKAGE_SCANNING) {
8439                                if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
8440                                    Log.d(TAG, "Registered content provider: " + names[j]
8441                                            + ", className = " + p.info.name + ", isSyncable = "
8442                                            + p.info.isSyncable);
8443                            }
8444                        } else {
8445                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
8446                            Slog.w(TAG, "Skipping provider name " + names[j] +
8447                                    " (in package " + pkg.applicationInfo.packageName +
8448                                    "): name already used by "
8449                                    + ((other != null && other.getComponentName() != null)
8450                                            ? other.getComponentName().getPackageName() : "?"));
8451                        }
8452                    }
8453                }
8454                if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8455                    if (r == null) {
8456                        r = new StringBuilder(256);
8457                    } else {
8458                        r.append(' ');
8459                    }
8460                    r.append(p.info.name);
8461                }
8462            }
8463            if (r != null) {
8464                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
8465            }
8466
8467            N = pkg.services.size();
8468            r = null;
8469            for (i=0; i<N; i++) {
8470                PackageParser.Service s = pkg.services.get(i);
8471                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
8472                        s.info.processName, pkg.applicationInfo.uid);
8473                mServices.addService(s);
8474                if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8475                    if (r == null) {
8476                        r = new StringBuilder(256);
8477                    } else {
8478                        r.append(' ');
8479                    }
8480                    r.append(s.info.name);
8481                }
8482            }
8483            if (r != null) {
8484                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
8485            }
8486
8487            N = pkg.receivers.size();
8488            r = null;
8489            for (i=0; i<N; i++) {
8490                PackageParser.Activity a = pkg.receivers.get(i);
8491                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
8492                        a.info.processName, pkg.applicationInfo.uid);
8493                mReceivers.addActivity(a, "receiver");
8494                if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8495                    if (r == null) {
8496                        r = new StringBuilder(256);
8497                    } else {
8498                        r.append(' ');
8499                    }
8500                    r.append(a.info.name);
8501                }
8502            }
8503            if (r != null) {
8504                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
8505            }
8506
8507            N = pkg.activities.size();
8508            r = null;
8509            for (i=0; i<N; i++) {
8510                PackageParser.Activity a = pkg.activities.get(i);
8511                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
8512                        a.info.processName, pkg.applicationInfo.uid);
8513                mActivities.addActivity(a, "activity");
8514                if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8515                    if (r == null) {
8516                        r = new StringBuilder(256);
8517                    } else {
8518                        r.append(' ');
8519                    }
8520                    r.append(a.info.name);
8521                }
8522            }
8523            if (r != null) {
8524                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
8525            }
8526
8527            N = pkg.permissionGroups.size();
8528            r = null;
8529            for (i=0; i<N; i++) {
8530                PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
8531                PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
8532                if (cur == null) {
8533                    mPermissionGroups.put(pg.info.name, pg);
8534                    if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8535                        if (r == null) {
8536                            r = new StringBuilder(256);
8537                        } else {
8538                            r.append(' ');
8539                        }
8540                        r.append(pg.info.name);
8541                    }
8542                } else {
8543                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
8544                            + pg.info.packageName + " ignored: original from "
8545                            + cur.info.packageName);
8546                    if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8547                        if (r == null) {
8548                            r = new StringBuilder(256);
8549                        } else {
8550                            r.append(' ');
8551                        }
8552                        r.append("DUP:");
8553                        r.append(pg.info.name);
8554                    }
8555                }
8556            }
8557            if (r != null) {
8558                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permission Groups: " + r);
8559            }
8560
8561            N = pkg.permissions.size();
8562            r = null;
8563            for (i=0; i<N; i++) {
8564                PackageParser.Permission p = pkg.permissions.get(i);
8565
8566                // Assume by default that we did not install this permission into the system.
8567                p.info.flags &= ~PermissionInfo.FLAG_INSTALLED;
8568
8569                // Now that permission groups have a special meaning, we ignore permission
8570                // groups for legacy apps to prevent unexpected behavior. In particular,
8571                // permissions for one app being granted to someone just becase they happen
8572                // to be in a group defined by another app (before this had no implications).
8573                if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) {
8574                    p.group = mPermissionGroups.get(p.info.group);
8575                    // Warn for a permission in an unknown group.
8576                    if (p.info.group != null && p.group == null) {
8577                        Slog.w(TAG, "Permission " + p.info.name + " from package "
8578                                + p.info.packageName + " in an unknown group " + p.info.group);
8579                    }
8580                }
8581
8582                ArrayMap<String, BasePermission> permissionMap =
8583                        p.tree ? mSettings.mPermissionTrees
8584                                : mSettings.mPermissions;
8585                BasePermission bp = permissionMap.get(p.info.name);
8586
8587                // Allow system apps to redefine non-system permissions
8588                if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) {
8589                    final boolean currentOwnerIsSystem = (bp.perm != null
8590                            && isSystemApp(bp.perm.owner));
8591                    if (isSystemApp(p.owner)) {
8592                        if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) {
8593                            // It's a built-in permission and no owner, take ownership now
8594                            bp.packageSetting = pkgSetting;
8595                            bp.perm = p;
8596                            bp.uid = pkg.applicationInfo.uid;
8597                            bp.sourcePackage = p.info.packageName;
8598                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
8599                        } else if (!currentOwnerIsSystem) {
8600                            String msg = "New decl " + p.owner + " of permission  "
8601                                    + p.info.name + " is system; overriding " + bp.sourcePackage;
8602                            reportSettingsProblem(Log.WARN, msg);
8603                            bp = null;
8604                        }
8605                    }
8606                }
8607
8608                if (bp == null) {
8609                    bp = new BasePermission(p.info.name, p.info.packageName,
8610                            BasePermission.TYPE_NORMAL);
8611                    permissionMap.put(p.info.name, bp);
8612                }
8613
8614                if (bp.perm == null) {
8615                    if (bp.sourcePackage == null
8616                            || bp.sourcePackage.equals(p.info.packageName)) {
8617                        BasePermission tree = findPermissionTreeLP(p.info.name);
8618                        if (tree == null
8619                                || tree.sourcePackage.equals(p.info.packageName)) {
8620                            bp.packageSetting = pkgSetting;
8621                            bp.perm = p;
8622                            bp.uid = pkg.applicationInfo.uid;
8623                            bp.sourcePackage = p.info.packageName;
8624                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
8625                            if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8626                                if (r == null) {
8627                                    r = new StringBuilder(256);
8628                                } else {
8629                                    r.append(' ');
8630                                }
8631                                r.append(p.info.name);
8632                            }
8633                        } else {
8634                            Slog.w(TAG, "Permission " + p.info.name + " from package "
8635                                    + p.info.packageName + " ignored: base tree "
8636                                    + tree.name + " is from package "
8637                                    + tree.sourcePackage);
8638                        }
8639                    } else {
8640                        Slog.w(TAG, "Permission " + p.info.name + " from package "
8641                                + p.info.packageName + " ignored: original from "
8642                                + bp.sourcePackage);
8643                    }
8644                } else if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8645                    if (r == null) {
8646                        r = new StringBuilder(256);
8647                    } else {
8648                        r.append(' ');
8649                    }
8650                    r.append("DUP:");
8651                    r.append(p.info.name);
8652                }
8653                if (bp.perm == p) {
8654                    bp.protectionLevel = p.info.protectionLevel;
8655                }
8656            }
8657
8658            if (r != null) {
8659                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permissions: " + r);
8660            }
8661
8662            N = pkg.instrumentation.size();
8663            r = null;
8664            for (i=0; i<N; i++) {
8665                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
8666                a.info.packageName = pkg.applicationInfo.packageName;
8667                a.info.sourceDir = pkg.applicationInfo.sourceDir;
8668                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
8669                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
8670                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
8671                a.info.dataDir = pkg.applicationInfo.dataDir;
8672                a.info.deviceProtectedDataDir = pkg.applicationInfo.deviceProtectedDataDir;
8673                a.info.credentialProtectedDataDir = pkg.applicationInfo.credentialProtectedDataDir;
8674
8675                // TODO: Update instrumentation.nativeLibraryDir as well ? Does it
8676                // need other information about the application, like the ABI and what not ?
8677                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
8678                mInstrumentation.put(a.getComponentName(), a);
8679                if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8680                    if (r == null) {
8681                        r = new StringBuilder(256);
8682                    } else {
8683                        r.append(' ');
8684                    }
8685                    r.append(a.info.name);
8686                }
8687            }
8688            if (r != null) {
8689                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
8690            }
8691
8692            if (pkg.protectedBroadcasts != null) {
8693                N = pkg.protectedBroadcasts.size();
8694                for (i=0; i<N; i++) {
8695                    mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
8696                }
8697            }
8698
8699            pkgSetting.setTimeStamp(scanFileTime);
8700
8701            // Create idmap files for pairs of (packages, overlay packages).
8702            // Note: "android", ie framework-res.apk, is handled by native layers.
8703            if (pkg.mOverlayTarget != null) {
8704                // This is an overlay package.
8705                if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) {
8706                    if (!mOverlays.containsKey(pkg.mOverlayTarget)) {
8707                        mOverlays.put(pkg.mOverlayTarget,
8708                                new ArrayMap<String, PackageParser.Package>());
8709                    }
8710                    ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget);
8711                    map.put(pkg.packageName, pkg);
8712                    PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget);
8713                    if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) {
8714                        createIdmapFailed = true;
8715                    }
8716                }
8717            } else if (mOverlays.containsKey(pkg.packageName) &&
8718                    !pkg.packageName.equals("android")) {
8719                // This is a regular package, with one or more known overlay packages.
8720                createIdmapsForPackageLI(pkg);
8721            }
8722        }
8723
8724        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8725
8726        if (createIdmapFailed) {
8727            throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
8728                    "scanPackageLI failed to createIdmap");
8729        }
8730        return pkg;
8731    }
8732
8733    /**
8734     * Derive the ABI of a non-system package located at {@code scanFile}. This information
8735     * is derived purely on the basis of the contents of {@code scanFile} and
8736     * {@code cpuAbiOverride}.
8737     *
8738     * If {@code extractLibs} is true, native libraries are extracted from the app if required.
8739     */
8740    private void derivePackageAbi(PackageParser.Package pkg, File scanFile,
8741                                 String cpuAbiOverride, boolean extractLibs)
8742            throws PackageManagerException {
8743        // TODO: We can probably be smarter about this stuff. For installed apps,
8744        // we can calculate this information at install time once and for all. For
8745        // system apps, we can probably assume that this information doesn't change
8746        // after the first boot scan. As things stand, we do lots of unnecessary work.
8747
8748        // Give ourselves some initial paths; we'll come back for another
8749        // pass once we've determined ABI below.
8750        setNativeLibraryPaths(pkg);
8751
8752        // We would never need to extract libs for forward-locked and external packages,
8753        // since the container service will do it for us. We shouldn't attempt to
8754        // extract libs from system app when it was not updated.
8755        if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() ||
8756                (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) {
8757            extractLibs = false;
8758        }
8759
8760        final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
8761        final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
8762
8763        NativeLibraryHelper.Handle handle = null;
8764        try {
8765            handle = NativeLibraryHelper.Handle.create(pkg);
8766            // TODO(multiArch): This can be null for apps that didn't go through the
8767            // usual installation process. We can calculate it again, like we
8768            // do during install time.
8769            //
8770            // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
8771            // unnecessary.
8772            final File nativeLibraryRoot = new File(nativeLibraryRootStr);
8773
8774            // Null out the abis so that they can be recalculated.
8775            pkg.applicationInfo.primaryCpuAbi = null;
8776            pkg.applicationInfo.secondaryCpuAbi = null;
8777            if (isMultiArch(pkg.applicationInfo)) {
8778                // Warn if we've set an abiOverride for multi-lib packages..
8779                // By definition, we need to copy both 32 and 64 bit libraries for
8780                // such packages.
8781                if (pkg.cpuAbiOverride != null
8782                        && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
8783                    Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
8784                }
8785
8786                int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
8787                int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
8788                if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
8789                    if (extractLibs) {
8790                        abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
8791                                nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
8792                                useIsaSpecificSubdirs);
8793                    } else {
8794                        abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
8795                    }
8796                }
8797
8798                maybeThrowExceptionForMultiArchCopy(
8799                        "Error unpackaging 32 bit native libs for multiarch app.", abi32);
8800
8801                if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
8802                    if (extractLibs) {
8803                        abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
8804                                nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
8805                                useIsaSpecificSubdirs);
8806                    } else {
8807                        abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
8808                    }
8809                }
8810
8811                maybeThrowExceptionForMultiArchCopy(
8812                        "Error unpackaging 64 bit native libs for multiarch app.", abi64);
8813
8814                if (abi64 >= 0) {
8815                    pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
8816                }
8817
8818                if (abi32 >= 0) {
8819                    final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
8820                    if (abi64 >= 0) {
8821                        if (pkg.use32bitAbi) {
8822                            pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi;
8823                            pkg.applicationInfo.primaryCpuAbi = abi;
8824                        } else {
8825                            pkg.applicationInfo.secondaryCpuAbi = abi;
8826                        }
8827                    } else {
8828                        pkg.applicationInfo.primaryCpuAbi = abi;
8829                    }
8830                }
8831
8832            } else {
8833                String[] abiList = (cpuAbiOverride != null) ?
8834                        new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
8835
8836                // Enable gross and lame hacks for apps that are built with old
8837                // SDK tools. We must scan their APKs for renderscript bitcode and
8838                // not launch them if it's present. Don't bother checking on devices
8839                // that don't have 64 bit support.
8840                boolean needsRenderScriptOverride = false;
8841                if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
8842                        NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
8843                    abiList = Build.SUPPORTED_32_BIT_ABIS;
8844                    needsRenderScriptOverride = true;
8845                }
8846
8847                final int copyRet;
8848                if (extractLibs) {
8849                    copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
8850                            nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
8851                } else {
8852                    copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
8853                }
8854
8855                if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
8856                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
8857                            "Error unpackaging native libs for app, errorCode=" + copyRet);
8858                }
8859
8860                if (copyRet >= 0) {
8861                    pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
8862                } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
8863                    pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
8864                } else if (needsRenderScriptOverride) {
8865                    pkg.applicationInfo.primaryCpuAbi = abiList[0];
8866                }
8867            }
8868        } catch (IOException ioe) {
8869            Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
8870        } finally {
8871            IoUtils.closeQuietly(handle);
8872        }
8873
8874        // Now that we've calculated the ABIs and determined if it's an internal app,
8875        // we will go ahead and populate the nativeLibraryPath.
8876        setNativeLibraryPaths(pkg);
8877    }
8878
8879    /**
8880     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
8881     * i.e, so that all packages can be run inside a single process if required.
8882     *
8883     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
8884     * this function will either try and make the ABI for all packages in {@code packagesForUser}
8885     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
8886     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
8887     * updating a package that belongs to a shared user.
8888     *
8889     * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
8890     * adds unnecessary complexity.
8891     */
8892    private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser,
8893            PackageParser.Package scannedPackage, boolean bootComplete) {
8894        String requiredInstructionSet = null;
8895        if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
8896            requiredInstructionSet = VMRuntime.getInstructionSet(
8897                     scannedPackage.applicationInfo.primaryCpuAbi);
8898        }
8899
8900        PackageSetting requirer = null;
8901        for (PackageSetting ps : packagesForUser) {
8902            // If packagesForUser contains scannedPackage, we skip it. This will happen
8903            // when scannedPackage is an update of an existing package. Without this check,
8904            // we will never be able to change the ABI of any package belonging to a shared
8905            // user, even if it's compatible with other packages.
8906            if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
8907                if (ps.primaryCpuAbiString == null) {
8908                    continue;
8909                }
8910
8911                final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
8912                if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
8913                    // We have a mismatch between instruction sets (say arm vs arm64) warn about
8914                    // this but there's not much we can do.
8915                    String errorMessage = "Instruction set mismatch, "
8916                            + ((requirer == null) ? "[caller]" : requirer)
8917                            + " requires " + requiredInstructionSet + " whereas " + ps
8918                            + " requires " + instructionSet;
8919                    Slog.w(TAG, errorMessage);
8920                }
8921
8922                if (requiredInstructionSet == null) {
8923                    requiredInstructionSet = instructionSet;
8924                    requirer = ps;
8925                }
8926            }
8927        }
8928
8929        if (requiredInstructionSet != null) {
8930            String adjustedAbi;
8931            if (requirer != null) {
8932                // requirer != null implies that either scannedPackage was null or that scannedPackage
8933                // did not require an ABI, in which case we have to adjust scannedPackage to match
8934                // the ABI of the set (which is the same as requirer's ABI)
8935                adjustedAbi = requirer.primaryCpuAbiString;
8936                if (scannedPackage != null) {
8937                    scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
8938                }
8939            } else {
8940                // requirer == null implies that we're updating all ABIs in the set to
8941                // match scannedPackage.
8942                adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
8943            }
8944
8945            for (PackageSetting ps : packagesForUser) {
8946                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
8947                    if (ps.primaryCpuAbiString != null) {
8948                        continue;
8949                    }
8950
8951                    ps.primaryCpuAbiString = adjustedAbi;
8952                    if (ps.pkg != null && ps.pkg.applicationInfo != null &&
8953                            !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) {
8954                        ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
8955                        Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi
8956                                + " (requirer="
8957                                + (requirer == null ? "null" : requirer.pkg.packageName)
8958                                + ", scannedPackage="
8959                                + (scannedPackage != null ? scannedPackage.packageName : "null")
8960                                + ")");
8961                        try {
8962                            mInstaller.rmdex(ps.codePathString,
8963                                    getDexCodeInstructionSet(getPreferredInstructionSet()));
8964                        } catch (InstallerException ignored) {
8965                        }
8966                    }
8967                }
8968            }
8969        }
8970    }
8971
8972    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
8973        synchronized (mPackages) {
8974            mResolverReplaced = true;
8975            // Set up information for custom user intent resolution activity.
8976            mResolveActivity.applicationInfo = pkg.applicationInfo;
8977            mResolveActivity.name = mCustomResolverComponentName.getClassName();
8978            mResolveActivity.packageName = pkg.applicationInfo.packageName;
8979            mResolveActivity.processName = pkg.applicationInfo.packageName;
8980            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
8981            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
8982                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
8983            mResolveActivity.theme = 0;
8984            mResolveActivity.exported = true;
8985            mResolveActivity.enabled = true;
8986            mResolveInfo.activityInfo = mResolveActivity;
8987            mResolveInfo.priority = 0;
8988            mResolveInfo.preferredOrder = 0;
8989            mResolveInfo.match = 0;
8990            mResolveComponentName = mCustomResolverComponentName;
8991            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
8992                    mResolveComponentName);
8993        }
8994    }
8995
8996    private void setUpEphemeralInstallerActivityLP(ComponentName installerComponent) {
8997        final PackageParser.Package pkg = mPackages.get(installerComponent.getPackageName());
8998
8999        // Set up information for ephemeral installer activity
9000        mEphemeralInstallerActivity.applicationInfo = pkg.applicationInfo;
9001        mEphemeralInstallerActivity.name = mEphemeralInstallerComponent.getClassName();
9002        mEphemeralInstallerActivity.packageName = pkg.applicationInfo.packageName;
9003        mEphemeralInstallerActivity.processName = pkg.applicationInfo.packageName;
9004        mEphemeralInstallerActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
9005        mEphemeralInstallerActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
9006                ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
9007        mEphemeralInstallerActivity.theme = 0;
9008        mEphemeralInstallerActivity.exported = true;
9009        mEphemeralInstallerActivity.enabled = true;
9010        mEphemeralInstallerInfo.activityInfo = mEphemeralInstallerActivity;
9011        mEphemeralInstallerInfo.priority = 0;
9012        mEphemeralInstallerInfo.preferredOrder = 0;
9013        mEphemeralInstallerInfo.match = 0;
9014
9015        if (DEBUG_EPHEMERAL) {
9016            Slog.d(TAG, "Set ephemeral installer activity: " + mEphemeralInstallerComponent);
9017        }
9018    }
9019
9020    private static String calculateBundledApkRoot(final String codePathString) {
9021        final File codePath = new File(codePathString);
9022        final File codeRoot;
9023        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
9024            codeRoot = Environment.getRootDirectory();
9025        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
9026            codeRoot = Environment.getOemDirectory();
9027        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
9028            codeRoot = Environment.getVendorDirectory();
9029        } else {
9030            // Unrecognized code path; take its top real segment as the apk root:
9031            // e.g. /something/app/blah.apk => /something
9032            try {
9033                File f = codePath.getCanonicalFile();
9034                File parent = f.getParentFile();    // non-null because codePath is a file
9035                File tmp;
9036                while ((tmp = parent.getParentFile()) != null) {
9037                    f = parent;
9038                    parent = tmp;
9039                }
9040                codeRoot = f;
9041                Slog.w(TAG, "Unrecognized code path "
9042                        + codePath + " - using " + codeRoot);
9043            } catch (IOException e) {
9044                // Can't canonicalize the code path -- shenanigans?
9045                Slog.w(TAG, "Can't canonicalize code path " + codePath);
9046                return Environment.getRootDirectory().getPath();
9047            }
9048        }
9049        return codeRoot.getPath();
9050    }
9051
9052    /**
9053     * Derive and set the location of native libraries for the given package,
9054     * which varies depending on where and how the package was installed.
9055     */
9056    private void setNativeLibraryPaths(PackageParser.Package pkg) {
9057        final ApplicationInfo info = pkg.applicationInfo;
9058        final String codePath = pkg.codePath;
9059        final File codeFile = new File(codePath);
9060        final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp();
9061        final boolean asecApp = info.isForwardLocked() || info.isExternalAsec();
9062
9063        info.nativeLibraryRootDir = null;
9064        info.nativeLibraryRootRequiresIsa = false;
9065        info.nativeLibraryDir = null;
9066        info.secondaryNativeLibraryDir = null;
9067
9068        if (isApkFile(codeFile)) {
9069            // Monolithic install
9070            if (bundledApp) {
9071                // If "/system/lib64/apkname" exists, assume that is the per-package
9072                // native library directory to use; otherwise use "/system/lib/apkname".
9073                final String apkRoot = calculateBundledApkRoot(info.sourceDir);
9074                final boolean is64Bit = VMRuntime.is64BitInstructionSet(
9075                        getPrimaryInstructionSet(info));
9076
9077                // This is a bundled system app so choose the path based on the ABI.
9078                // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
9079                // is just the default path.
9080                final String apkName = deriveCodePathName(codePath);
9081                final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
9082                info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
9083                        apkName).getAbsolutePath();
9084
9085                if (info.secondaryCpuAbi != null) {
9086                    final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
9087                    info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
9088                            secondaryLibDir, apkName).getAbsolutePath();
9089                }
9090            } else if (asecApp) {
9091                info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
9092                        .getAbsolutePath();
9093            } else {
9094                final String apkName = deriveCodePathName(codePath);
9095                info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName)
9096                        .getAbsolutePath();
9097            }
9098
9099            info.nativeLibraryRootRequiresIsa = false;
9100            info.nativeLibraryDir = info.nativeLibraryRootDir;
9101        } else {
9102            // Cluster install
9103            info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
9104            info.nativeLibraryRootRequiresIsa = true;
9105
9106            info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
9107                    getPrimaryInstructionSet(info)).getAbsolutePath();
9108
9109            if (info.secondaryCpuAbi != null) {
9110                info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
9111                        VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
9112            }
9113        }
9114    }
9115
9116    /**
9117     * Calculate the abis and roots for a bundled app. These can uniquely
9118     * be determined from the contents of the system partition, i.e whether
9119     * it contains 64 or 32 bit shared libraries etc. We do not validate any
9120     * of this information, and instead assume that the system was built
9121     * sensibly.
9122     */
9123    private void setBundledAppAbisAndRoots(PackageParser.Package pkg,
9124                                           PackageSetting pkgSetting) {
9125        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
9126
9127        // If "/system/lib64/apkname" exists, assume that is the per-package
9128        // native library directory to use; otherwise use "/system/lib/apkname".
9129        final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
9130        setBundledAppAbi(pkg, apkRoot, apkName);
9131        // pkgSetting might be null during rescan following uninstall of updates
9132        // to a bundled app, so accommodate that possibility.  The settings in
9133        // that case will be established later from the parsed package.
9134        //
9135        // If the settings aren't null, sync them up with what we've just derived.
9136        // note that apkRoot isn't stored in the package settings.
9137        if (pkgSetting != null) {
9138            pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
9139            pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
9140        }
9141    }
9142
9143    /**
9144     * Deduces the ABI of a bundled app and sets the relevant fields on the
9145     * parsed pkg object.
9146     *
9147     * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
9148     *        under which system libraries are installed.
9149     * @param apkName the name of the installed package.
9150     */
9151    private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
9152        final File codeFile = new File(pkg.codePath);
9153
9154        final boolean has64BitLibs;
9155        final boolean has32BitLibs;
9156        if (isApkFile(codeFile)) {
9157            // Monolithic install
9158            has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
9159            has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
9160        } else {
9161            // Cluster install
9162            final File rootDir = new File(codeFile, LIB_DIR_NAME);
9163            if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
9164                    && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
9165                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
9166                has64BitLibs = (new File(rootDir, isa)).exists();
9167            } else {
9168                has64BitLibs = false;
9169            }
9170            if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
9171                    && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
9172                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
9173                has32BitLibs = (new File(rootDir, isa)).exists();
9174            } else {
9175                has32BitLibs = false;
9176            }
9177        }
9178
9179        if (has64BitLibs && !has32BitLibs) {
9180            // The package has 64 bit libs, but not 32 bit libs. Its primary
9181            // ABI should be 64 bit. We can safely assume here that the bundled
9182            // native libraries correspond to the most preferred ABI in the list.
9183
9184            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
9185            pkg.applicationInfo.secondaryCpuAbi = null;
9186        } else if (has32BitLibs && !has64BitLibs) {
9187            // The package has 32 bit libs but not 64 bit libs. Its primary
9188            // ABI should be 32 bit.
9189
9190            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
9191            pkg.applicationInfo.secondaryCpuAbi = null;
9192        } else if (has32BitLibs && has64BitLibs) {
9193            // The application has both 64 and 32 bit bundled libraries. We check
9194            // here that the app declares multiArch support, and warn if it doesn't.
9195            //
9196            // We will be lenient here and record both ABIs. The primary will be the
9197            // ABI that's higher on the list, i.e, a device that's configured to prefer
9198            // 64 bit apps will see a 64 bit primary ABI,
9199
9200            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
9201                Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch.");
9202            }
9203
9204            if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
9205                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
9206                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
9207            } else {
9208                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
9209                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
9210            }
9211        } else {
9212            pkg.applicationInfo.primaryCpuAbi = null;
9213            pkg.applicationInfo.secondaryCpuAbi = null;
9214        }
9215    }
9216
9217    private void killApplication(String pkgName, int appId, String reason) {
9218        // Request the ActivityManager to kill the process(only for existing packages)
9219        // so that we do not end up in a confused state while the user is still using the older
9220        // version of the application while the new one gets installed.
9221        final long token = Binder.clearCallingIdentity();
9222        try {
9223            IActivityManager am = ActivityManagerNative.getDefault();
9224            if (am != null) {
9225                try {
9226                    am.killApplicationWithAppId(pkgName, appId, reason);
9227                } catch (RemoteException e) {
9228                }
9229            }
9230        } finally {
9231            Binder.restoreCallingIdentity(token);
9232        }
9233    }
9234
9235    private void removePackageLI(PackageParser.Package pkg, boolean chatty) {
9236        // Remove the parent package setting
9237        PackageSetting ps = (PackageSetting) pkg.mExtras;
9238        if (ps != null) {
9239            removePackageLI(ps, chatty);
9240        }
9241        // Remove the child package setting
9242        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9243        for (int i = 0; i < childCount; i++) {
9244            PackageParser.Package childPkg = pkg.childPackages.get(i);
9245            ps = (PackageSetting) childPkg.mExtras;
9246            if (ps != null) {
9247                removePackageLI(ps, chatty);
9248            }
9249        }
9250    }
9251
9252    void removePackageLI(PackageSetting ps, boolean chatty) {
9253        if (DEBUG_INSTALL) {
9254            if (chatty)
9255                Log.d(TAG, "Removing package " + ps.name);
9256        }
9257
9258        // writer
9259        synchronized (mPackages) {
9260            mPackages.remove(ps.name);
9261            final PackageParser.Package pkg = ps.pkg;
9262            if (pkg != null) {
9263                cleanPackageDataStructuresLILPw(pkg, chatty);
9264            }
9265        }
9266    }
9267
9268    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
9269        if (DEBUG_INSTALL) {
9270            if (chatty)
9271                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
9272        }
9273
9274        // writer
9275        synchronized (mPackages) {
9276            // Remove the parent package
9277            mPackages.remove(pkg.applicationInfo.packageName);
9278            cleanPackageDataStructuresLILPw(pkg, chatty);
9279
9280            // Remove the child packages
9281            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9282            for (int i = 0; i < childCount; i++) {
9283                PackageParser.Package childPkg = pkg.childPackages.get(i);
9284                mPackages.remove(childPkg.applicationInfo.packageName);
9285                cleanPackageDataStructuresLILPw(childPkg, chatty);
9286            }
9287        }
9288    }
9289
9290    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
9291        int N = pkg.providers.size();
9292        StringBuilder r = null;
9293        int i;
9294        for (i=0; i<N; i++) {
9295            PackageParser.Provider p = pkg.providers.get(i);
9296            mProviders.removeProvider(p);
9297            if (p.info.authority == null) {
9298
9299                /* There was another ContentProvider with this authority when
9300                 * this app was installed so this authority is null,
9301                 * Ignore it as we don't have to unregister the provider.
9302                 */
9303                continue;
9304            }
9305            String names[] = p.info.authority.split(";");
9306            for (int j = 0; j < names.length; j++) {
9307                if (mProvidersByAuthority.get(names[j]) == p) {
9308                    mProvidersByAuthority.remove(names[j]);
9309                    if (DEBUG_REMOVE) {
9310                        if (chatty)
9311                            Log.d(TAG, "Unregistered content provider: " + names[j]
9312                                    + ", className = " + p.info.name + ", isSyncable = "
9313                                    + p.info.isSyncable);
9314                    }
9315                }
9316            }
9317            if (DEBUG_REMOVE && chatty) {
9318                if (r == null) {
9319                    r = new StringBuilder(256);
9320                } else {
9321                    r.append(' ');
9322                }
9323                r.append(p.info.name);
9324            }
9325        }
9326        if (r != null) {
9327            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
9328        }
9329
9330        N = pkg.services.size();
9331        r = null;
9332        for (i=0; i<N; i++) {
9333            PackageParser.Service s = pkg.services.get(i);
9334            mServices.removeService(s);
9335            if (chatty) {
9336                if (r == null) {
9337                    r = new StringBuilder(256);
9338                } else {
9339                    r.append(' ');
9340                }
9341                r.append(s.info.name);
9342            }
9343        }
9344        if (r != null) {
9345            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
9346        }
9347
9348        N = pkg.receivers.size();
9349        r = null;
9350        for (i=0; i<N; i++) {
9351            PackageParser.Activity a = pkg.receivers.get(i);
9352            mReceivers.removeActivity(a, "receiver");
9353            if (DEBUG_REMOVE && chatty) {
9354                if (r == null) {
9355                    r = new StringBuilder(256);
9356                } else {
9357                    r.append(' ');
9358                }
9359                r.append(a.info.name);
9360            }
9361        }
9362        if (r != null) {
9363            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
9364        }
9365
9366        N = pkg.activities.size();
9367        r = null;
9368        for (i=0; i<N; i++) {
9369            PackageParser.Activity a = pkg.activities.get(i);
9370            mActivities.removeActivity(a, "activity");
9371            if (DEBUG_REMOVE && chatty) {
9372                if (r == null) {
9373                    r = new StringBuilder(256);
9374                } else {
9375                    r.append(' ');
9376                }
9377                r.append(a.info.name);
9378            }
9379        }
9380        if (r != null) {
9381            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
9382        }
9383
9384        N = pkg.permissions.size();
9385        r = null;
9386        for (i=0; i<N; i++) {
9387            PackageParser.Permission p = pkg.permissions.get(i);
9388            BasePermission bp = mSettings.mPermissions.get(p.info.name);
9389            if (bp == null) {
9390                bp = mSettings.mPermissionTrees.get(p.info.name);
9391            }
9392            if (bp != null && bp.perm == p) {
9393                bp.perm = null;
9394                if (DEBUG_REMOVE && chatty) {
9395                    if (r == null) {
9396                        r = new StringBuilder(256);
9397                    } else {
9398                        r.append(' ');
9399                    }
9400                    r.append(p.info.name);
9401                }
9402            }
9403            if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
9404                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(p.info.name);
9405                if (appOpPkgs != null) {
9406                    appOpPkgs.remove(pkg.packageName);
9407                }
9408            }
9409        }
9410        if (r != null) {
9411            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
9412        }
9413
9414        N = pkg.requestedPermissions.size();
9415        r = null;
9416        for (i=0; i<N; i++) {
9417            String perm = pkg.requestedPermissions.get(i);
9418            BasePermission bp = mSettings.mPermissions.get(perm);
9419            if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
9420                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(perm);
9421                if (appOpPkgs != null) {
9422                    appOpPkgs.remove(pkg.packageName);
9423                    if (appOpPkgs.isEmpty()) {
9424                        mAppOpPermissionPackages.remove(perm);
9425                    }
9426                }
9427            }
9428        }
9429        if (r != null) {
9430            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
9431        }
9432
9433        N = pkg.instrumentation.size();
9434        r = null;
9435        for (i=0; i<N; i++) {
9436            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
9437            mInstrumentation.remove(a.getComponentName());
9438            if (DEBUG_REMOVE && chatty) {
9439                if (r == null) {
9440                    r = new StringBuilder(256);
9441                } else {
9442                    r.append(' ');
9443                }
9444                r.append(a.info.name);
9445            }
9446        }
9447        if (r != null) {
9448            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
9449        }
9450
9451        r = null;
9452        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
9453            // Only system apps can hold shared libraries.
9454            if (pkg.libraryNames != null) {
9455                for (i=0; i<pkg.libraryNames.size(); i++) {
9456                    String name = pkg.libraryNames.get(i);
9457                    SharedLibraryEntry cur = mSharedLibraries.get(name);
9458                    if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) {
9459                        mSharedLibraries.remove(name);
9460                        if (DEBUG_REMOVE && chatty) {
9461                            if (r == null) {
9462                                r = new StringBuilder(256);
9463                            } else {
9464                                r.append(' ');
9465                            }
9466                            r.append(name);
9467                        }
9468                    }
9469                }
9470            }
9471        }
9472        if (r != null) {
9473            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
9474        }
9475    }
9476
9477    private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
9478        for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
9479            if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
9480                return true;
9481            }
9482        }
9483        return false;
9484    }
9485
9486    static final int UPDATE_PERMISSIONS_ALL = 1<<0;
9487    static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
9488    static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
9489
9490    private void updatePermissionsLPw(PackageParser.Package pkg, int flags) {
9491        // Update the parent permissions
9492        updatePermissionsLPw(pkg.packageName, pkg, flags);
9493        // Update the child permissions
9494        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9495        for (int i = 0; i < childCount; i++) {
9496            PackageParser.Package childPkg = pkg.childPackages.get(i);
9497            updatePermissionsLPw(childPkg.packageName, childPkg, flags);
9498        }
9499    }
9500
9501    private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo,
9502            int flags) {
9503        final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null;
9504        updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags);
9505    }
9506
9507    private void updatePermissionsLPw(String changingPkg,
9508            PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) {
9509        // Make sure there are no dangling permission trees.
9510        Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator();
9511        while (it.hasNext()) {
9512            final BasePermission bp = it.next();
9513            if (bp.packageSetting == null) {
9514                // We may not yet have parsed the package, so just see if
9515                // we still know about its settings.
9516                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
9517            }
9518            if (bp.packageSetting == null) {
9519                Slog.w(TAG, "Removing dangling permission tree: " + bp.name
9520                        + " from package " + bp.sourcePackage);
9521                it.remove();
9522            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
9523                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
9524                    Slog.i(TAG, "Removing old permission tree: " + bp.name
9525                            + " from package " + bp.sourcePackage);
9526                    flags |= UPDATE_PERMISSIONS_ALL;
9527                    it.remove();
9528                }
9529            }
9530        }
9531
9532        // Make sure all dynamic permissions have been assigned to a package,
9533        // and make sure there are no dangling permissions.
9534        it = mSettings.mPermissions.values().iterator();
9535        while (it.hasNext()) {
9536            final BasePermission bp = it.next();
9537            if (bp.type == BasePermission.TYPE_DYNAMIC) {
9538                if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
9539                        + bp.name + " pkg=" + bp.sourcePackage
9540                        + " info=" + bp.pendingInfo);
9541                if (bp.packageSetting == null && bp.pendingInfo != null) {
9542                    final BasePermission tree = findPermissionTreeLP(bp.name);
9543                    if (tree != null && tree.perm != null) {
9544                        bp.packageSetting = tree.packageSetting;
9545                        bp.perm = new PackageParser.Permission(tree.perm.owner,
9546                                new PermissionInfo(bp.pendingInfo));
9547                        bp.perm.info.packageName = tree.perm.info.packageName;
9548                        bp.perm.info.name = bp.name;
9549                        bp.uid = tree.uid;
9550                    }
9551                }
9552            }
9553            if (bp.packageSetting == null) {
9554                // We may not yet have parsed the package, so just see if
9555                // we still know about its settings.
9556                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
9557            }
9558            if (bp.packageSetting == null) {
9559                Slog.w(TAG, "Removing dangling permission: " + bp.name
9560                        + " from package " + bp.sourcePackage);
9561                it.remove();
9562            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
9563                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
9564                    Slog.i(TAG, "Removing old permission: " + bp.name
9565                            + " from package " + bp.sourcePackage);
9566                    flags |= UPDATE_PERMISSIONS_ALL;
9567                    it.remove();
9568                }
9569            }
9570        }
9571
9572        // Now update the permissions for all packages, in particular
9573        // replace the granted permissions of the system packages.
9574        if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
9575            for (PackageParser.Package pkg : mPackages.values()) {
9576                if (pkg != pkgInfo) {
9577                    // Only replace for packages on requested volume
9578                    final String volumeUuid = getVolumeUuidForPackage(pkg);
9579                    final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0)
9580                            && Objects.equals(replaceVolumeUuid, volumeUuid);
9581                    grantPermissionsLPw(pkg, replace, changingPkg);
9582                }
9583            }
9584        }
9585
9586        if (pkgInfo != null) {
9587            // Only replace for packages on requested volume
9588            final String volumeUuid = getVolumeUuidForPackage(pkgInfo);
9589            final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0)
9590                    && Objects.equals(replaceVolumeUuid, volumeUuid);
9591            grantPermissionsLPw(pkgInfo, replace, changingPkg);
9592        }
9593    }
9594
9595    private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace,
9596            String packageOfInterest) {
9597        // IMPORTANT: There are two types of permissions: install and runtime.
9598        // Install time permissions are granted when the app is installed to
9599        // all device users and users added in the future. Runtime permissions
9600        // are granted at runtime explicitly to specific users. Normal and signature
9601        // protected permissions are install time permissions. Dangerous permissions
9602        // are install permissions if the app's target SDK is Lollipop MR1 or older,
9603        // otherwise they are runtime permissions. This function does not manage
9604        // runtime permissions except for the case an app targeting Lollipop MR1
9605        // being upgraded to target a newer SDK, in which case dangerous permissions
9606        // are transformed from install time to runtime ones.
9607
9608        final PackageSetting ps = (PackageSetting) pkg.mExtras;
9609        if (ps == null) {
9610            return;
9611        }
9612
9613        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions");
9614
9615        PermissionsState permissionsState = ps.getPermissionsState();
9616        PermissionsState origPermissions = permissionsState;
9617
9618        final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
9619
9620        boolean runtimePermissionsRevoked = false;
9621        int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY;
9622
9623        boolean changedInstallPermission = false;
9624
9625        if (replace) {
9626            ps.installPermissionsFixed = false;
9627            if (!ps.isSharedUser()) {
9628                origPermissions = new PermissionsState(permissionsState);
9629                permissionsState.reset();
9630            } else {
9631                // We need to know only about runtime permission changes since the
9632                // calling code always writes the install permissions state but
9633                // the runtime ones are written only if changed. The only cases of
9634                // changed runtime permissions here are promotion of an install to
9635                // runtime and revocation of a runtime from a shared user.
9636                changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw(
9637                        ps.sharedUser, UserManagerService.getInstance().getUserIds());
9638                if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) {
9639                    runtimePermissionsRevoked = true;
9640                }
9641            }
9642        }
9643
9644        permissionsState.setGlobalGids(mGlobalGids);
9645
9646        final int N = pkg.requestedPermissions.size();
9647        for (int i=0; i<N; i++) {
9648            final String name = pkg.requestedPermissions.get(i);
9649            final BasePermission bp = mSettings.mPermissions.get(name);
9650
9651            if (DEBUG_INSTALL) {
9652                Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
9653            }
9654
9655            if (bp == null || bp.packageSetting == null) {
9656                if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
9657                    Slog.w(TAG, "Unknown permission " + name
9658                            + " in package " + pkg.packageName);
9659                }
9660                continue;
9661            }
9662
9663            final String perm = bp.name;
9664            boolean allowedSig = false;
9665            int grant = GRANT_DENIED;
9666
9667            // Keep track of app op permissions.
9668            if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
9669                ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name);
9670                if (pkgs == null) {
9671                    pkgs = new ArraySet<>();
9672                    mAppOpPermissionPackages.put(bp.name, pkgs);
9673                }
9674                pkgs.add(pkg.packageName);
9675            }
9676
9677            final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE;
9678            final boolean appSupportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion
9679                    >= Build.VERSION_CODES.M;
9680            switch (level) {
9681                case PermissionInfo.PROTECTION_NORMAL: {
9682                    // For all apps normal permissions are install time ones.
9683                    grant = GRANT_INSTALL;
9684                } break;
9685
9686                case PermissionInfo.PROTECTION_DANGEROUS: {
9687                    // If a permission review is required for legacy apps we represent
9688                    // their permissions as always granted runtime ones since we need
9689                    // to keep the review required permission flag per user while an
9690                    // install permission's state is shared across all users.
9691                    if (!appSupportsRuntimePermissions && !Build.PERMISSIONS_REVIEW_REQUIRED) {
9692                        // For legacy apps dangerous permissions are install time ones.
9693                        grant = GRANT_INSTALL;
9694                    } else if (origPermissions.hasInstallPermission(bp.name)) {
9695                        // For legacy apps that became modern, install becomes runtime.
9696                        grant = GRANT_UPGRADE;
9697                    } else if (mPromoteSystemApps
9698                            && isSystemApp(ps)
9699                            && mExistingSystemPackages.contains(ps.name)) {
9700                        // For legacy system apps, install becomes runtime.
9701                        // We cannot check hasInstallPermission() for system apps since those
9702                        // permissions were granted implicitly and not persisted pre-M.
9703                        grant = GRANT_UPGRADE;
9704                    } else {
9705                        // For modern apps keep runtime permissions unchanged.
9706                        grant = GRANT_RUNTIME;
9707                    }
9708                } break;
9709
9710                case PermissionInfo.PROTECTION_SIGNATURE: {
9711                    // For all apps signature permissions are install time ones.
9712                    allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions);
9713                    if (allowedSig) {
9714                        grant = GRANT_INSTALL;
9715                    }
9716                } break;
9717            }
9718
9719            if (DEBUG_INSTALL) {
9720                Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
9721            }
9722
9723            if (grant != GRANT_DENIED) {
9724                if (!isSystemApp(ps) && ps.installPermissionsFixed) {
9725                    // If this is an existing, non-system package, then
9726                    // we can't add any new permissions to it.
9727                    if (!allowedSig && !origPermissions.hasInstallPermission(perm)) {
9728                        // Except...  if this is a permission that was added
9729                        // to the platform (note: need to only do this when
9730                        // updating the platform).
9731                        if (!isNewPlatformPermissionForPackage(perm, pkg)) {
9732                            grant = GRANT_DENIED;
9733                        }
9734                    }
9735                }
9736
9737                switch (grant) {
9738                    case GRANT_INSTALL: {
9739                        // Revoke this as runtime permission to handle the case of
9740                        // a runtime permission being downgraded to an install one. Also in permission review mode we keep dangerous permissions for legacy apps
9741                        for (int userId : UserManagerService.getInstance().getUserIds()) {
9742                            if (origPermissions.getRuntimePermissionState(
9743                                    bp.name, userId) != null) {
9744                                // Revoke the runtime permission and clear the flags.
9745                                origPermissions.revokeRuntimePermission(bp, userId);
9746                                origPermissions.updatePermissionFlags(bp, userId,
9747                                      PackageManager.MASK_PERMISSION_FLAGS, 0);
9748                                // If we revoked a permission permission, we have to write.
9749                                changedRuntimePermissionUserIds = ArrayUtils.appendInt(
9750                                        changedRuntimePermissionUserIds, userId);
9751                            }
9752                        }
9753                        // Grant an install permission.
9754                        if (permissionsState.grantInstallPermission(bp) !=
9755                                PermissionsState.PERMISSION_OPERATION_FAILURE) {
9756                            changedInstallPermission = true;
9757                        }
9758                    } break;
9759
9760                    case GRANT_RUNTIME: {
9761                        // Grant previously granted runtime permissions.
9762                        for (int userId : UserManagerService.getInstance().getUserIds()) {
9763                            PermissionState permissionState = origPermissions
9764                                    .getRuntimePermissionState(bp.name, userId);
9765                            int flags = permissionState != null
9766                                    ? permissionState.getFlags() : 0;
9767                            if (origPermissions.hasRuntimePermission(bp.name, userId)) {
9768                                if (permissionsState.grantRuntimePermission(bp, userId) ==
9769                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
9770                                    // If we cannot put the permission as it was, we have to write.
9771                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
9772                                            changedRuntimePermissionUserIds, userId);
9773                                }
9774                                // If the app supports runtime permissions no need for a review.
9775                                if (Build.PERMISSIONS_REVIEW_REQUIRED
9776                                        && appSupportsRuntimePermissions
9777                                        && (flags & PackageManager
9778                                                .FLAG_PERMISSION_REVIEW_REQUIRED) != 0) {
9779                                    flags &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
9780                                    // Since we changed the flags, we have to write.
9781                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
9782                                            changedRuntimePermissionUserIds, userId);
9783                                }
9784                            } else if (Build.PERMISSIONS_REVIEW_REQUIRED
9785                                    && !appSupportsRuntimePermissions) {
9786                                // For legacy apps that need a permission review, every new
9787                                // runtime permission is granted but it is pending a review.
9788                                if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
9789                                    permissionsState.grantRuntimePermission(bp, userId);
9790                                    flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
9791                                    // We changed the permission and flags, hence have to write.
9792                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
9793                                            changedRuntimePermissionUserIds, userId);
9794                                }
9795                            }
9796                            // Propagate the permission flags.
9797                            permissionsState.updatePermissionFlags(bp, userId, flags, flags);
9798                        }
9799                    } break;
9800
9801                    case GRANT_UPGRADE: {
9802                        // Grant runtime permissions for a previously held install permission.
9803                        PermissionState permissionState = origPermissions
9804                                .getInstallPermissionState(bp.name);
9805                        final int flags = permissionState != null ? permissionState.getFlags() : 0;
9806
9807                        if (origPermissions.revokeInstallPermission(bp)
9808                                != PermissionsState.PERMISSION_OPERATION_FAILURE) {
9809                            // We will be transferring the permission flags, so clear them.
9810                            origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL,
9811                                    PackageManager.MASK_PERMISSION_FLAGS, 0);
9812                            changedInstallPermission = true;
9813                        }
9814
9815                        // If the permission is not to be promoted to runtime we ignore it and
9816                        // also its other flags as they are not applicable to install permissions.
9817                        if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) {
9818                            for (int userId : currentUserIds) {
9819                                if (permissionsState.grantRuntimePermission(bp, userId) !=
9820                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
9821                                    // Transfer the permission flags.
9822                                    permissionsState.updatePermissionFlags(bp, userId,
9823                                            flags, flags);
9824                                    // If we granted the permission, we have to write.
9825                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
9826                                            changedRuntimePermissionUserIds, userId);
9827                                }
9828                            }
9829                        }
9830                    } break;
9831
9832                    default: {
9833                        if (packageOfInterest == null
9834                                || packageOfInterest.equals(pkg.packageName)) {
9835                            Slog.w(TAG, "Not granting permission " + perm
9836                                    + " to package " + pkg.packageName
9837                                    + " because it was previously installed without");
9838                        }
9839                    } break;
9840                }
9841            } else {
9842                if (permissionsState.revokeInstallPermission(bp) !=
9843                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
9844                    // Also drop the permission flags.
9845                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
9846                            PackageManager.MASK_PERMISSION_FLAGS, 0);
9847                    changedInstallPermission = true;
9848                    Slog.i(TAG, "Un-granting permission " + perm
9849                            + " from package " + pkg.packageName
9850                            + " (protectionLevel=" + bp.protectionLevel
9851                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
9852                            + ")");
9853                } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) {
9854                    // Don't print warning for app op permissions, since it is fine for them
9855                    // not to be granted, there is a UI for the user to decide.
9856                    if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
9857                        Slog.w(TAG, "Not granting permission " + perm
9858                                + " to package " + pkg.packageName
9859                                + " (protectionLevel=" + bp.protectionLevel
9860                                + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
9861                                + ")");
9862                    }
9863                }
9864            }
9865        }
9866
9867        if ((changedInstallPermission || replace) && !ps.installPermissionsFixed &&
9868                !isSystemApp(ps) || isUpdatedSystemApp(ps)){
9869            // This is the first that we have heard about this package, so the
9870            // permissions we have now selected are fixed until explicitly
9871            // changed.
9872            ps.installPermissionsFixed = true;
9873        }
9874
9875        // Persist the runtime permissions state for users with changes. If permissions
9876        // were revoked because no app in the shared user declares them we have to
9877        // write synchronously to avoid losing runtime permissions state.
9878        for (int userId : changedRuntimePermissionUserIds) {
9879            mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked);
9880        }
9881
9882        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9883    }
9884
9885    private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) {
9886        boolean allowed = false;
9887        final int NP = PackageParser.NEW_PERMISSIONS.length;
9888        for (int ip=0; ip<NP; ip++) {
9889            final PackageParser.NewPermissionInfo npi
9890                    = PackageParser.NEW_PERMISSIONS[ip];
9891            if (npi.name.equals(perm)
9892                    && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
9893                allowed = true;
9894                Log.i(TAG, "Auto-granting " + perm + " to old pkg "
9895                        + pkg.packageName);
9896                break;
9897            }
9898        }
9899        return allowed;
9900    }
9901
9902    private boolean grantSignaturePermission(String perm, PackageParser.Package pkg,
9903            BasePermission bp, PermissionsState origPermissions) {
9904        boolean allowed;
9905        allowed = (compareSignatures(
9906                bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
9907                        == PackageManager.SIGNATURE_MATCH)
9908                || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
9909                        == PackageManager.SIGNATURE_MATCH);
9910        if (!allowed && (bp.protectionLevel
9911                & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0) {
9912            if (isSystemApp(pkg)) {
9913                // For updated system applications, a system permission
9914                // is granted only if it had been defined by the original application.
9915                if (pkg.isUpdatedSystemApp()) {
9916                    final PackageSetting sysPs = mSettings
9917                            .getDisabledSystemPkgLPr(pkg.packageName);
9918                    if (sysPs != null && sysPs.getPermissionsState().hasInstallPermission(perm)) {
9919                        // If the original was granted this permission, we take
9920                        // that grant decision as read and propagate it to the
9921                        // update.
9922                        if (sysPs.isPrivileged()) {
9923                            allowed = true;
9924                        }
9925                    } else {
9926                        // The system apk may have been updated with an older
9927                        // version of the one on the data partition, but which
9928                        // granted a new system permission that it didn't have
9929                        // before.  In this case we do want to allow the app to
9930                        // now get the new permission if the ancestral apk is
9931                        // privileged to get it.
9932                        if (sysPs != null && sysPs.pkg != null && sysPs.isPrivileged()) {
9933                            for (int j = 0; j < sysPs.pkg.requestedPermissions.size(); j++) {
9934                                if (perm.equals(sysPs.pkg.requestedPermissions.get(j))) {
9935                                    allowed = true;
9936                                    break;
9937                                }
9938                            }
9939                        }
9940                        // Also if a privileged parent package on the system image or any of
9941                        // its children requested a privileged permission, the updated child
9942                        // packages can also get the permission.
9943                        if (pkg.parentPackage != null) {
9944                            final PackageSetting disabledSysParentPs = mSettings
9945                                    .getDisabledSystemPkgLPr(pkg.parentPackage.packageName);
9946                            if (disabledSysParentPs != null && disabledSysParentPs.pkg != null
9947                                    && disabledSysParentPs.isPrivileged()) {
9948                                if (isPackageRequestingPermission(disabledSysParentPs.pkg, perm)) {
9949                                    allowed = true;
9950                                } else if (disabledSysParentPs.pkg.childPackages != null) {
9951                                    final int count = disabledSysParentPs.pkg.childPackages.size();
9952                                    for (int i = 0; i < count; i++) {
9953                                        PackageParser.Package disabledSysChildPkg =
9954                                                disabledSysParentPs.pkg.childPackages.get(i);
9955                                        if (isPackageRequestingPermission(disabledSysChildPkg,
9956                                                perm)) {
9957                                            allowed = true;
9958                                            break;
9959                                        }
9960                                    }
9961                                }
9962                            }
9963                        }
9964                    }
9965                } else {
9966                    allowed = isPrivilegedApp(pkg);
9967                }
9968            }
9969        }
9970        if (!allowed) {
9971            if (!allowed && (bp.protectionLevel
9972                    & PermissionInfo.PROTECTION_FLAG_PRE23) != 0
9973                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
9974                // If this was a previously normal/dangerous permission that got moved
9975                // to a system permission as part of the runtime permission redesign, then
9976                // we still want to blindly grant it to old apps.
9977                allowed = true;
9978            }
9979            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0
9980                    && pkg.packageName.equals(mRequiredInstallerPackage)) {
9981                // If this permission is to be granted to the system installer and
9982                // this app is an installer, then it gets the permission.
9983                allowed = true;
9984            }
9985            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0
9986                    && pkg.packageName.equals(mRequiredVerifierPackage)) {
9987                // If this permission is to be granted to the system verifier and
9988                // this app is a verifier, then it gets the permission.
9989                allowed = true;
9990            }
9991            if (!allowed && (bp.protectionLevel
9992                    & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0
9993                    && isSystemApp(pkg)) {
9994                // Any pre-installed system app is allowed to get this permission.
9995                allowed = true;
9996            }
9997            if (!allowed && (bp.protectionLevel
9998                    & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) {
9999                // For development permissions, a development permission
10000                // is granted only if it was already granted.
10001                allowed = origPermissions.hasInstallPermission(perm);
10002            }
10003            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_SETUP) != 0
10004                    && pkg.packageName.equals(mSetupWizardPackage)) {
10005                // If this permission is to be granted to the system setup wizard and
10006                // this app is a setup wizard, then it gets the permission.
10007                allowed = true;
10008            }
10009        }
10010        return allowed;
10011    }
10012
10013    private boolean isPackageRequestingPermission(PackageParser.Package pkg, String permission) {
10014        final int permCount = pkg.requestedPermissions.size();
10015        for (int j = 0; j < permCount; j++) {
10016            String requestedPermission = pkg.requestedPermissions.get(j);
10017            if (permission.equals(requestedPermission)) {
10018                return true;
10019            }
10020        }
10021        return false;
10022    }
10023
10024    final class ActivityIntentResolver
10025            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
10026        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
10027                boolean defaultOnly, int userId) {
10028            if (!sUserManager.exists(userId)) return null;
10029            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
10030            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
10031        }
10032
10033        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
10034                int userId) {
10035            if (!sUserManager.exists(userId)) return null;
10036            mFlags = flags;
10037            return super.queryIntent(intent, resolvedType,
10038                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
10039        }
10040
10041        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
10042                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
10043            if (!sUserManager.exists(userId)) return null;
10044            if (packageActivities == null) {
10045                return null;
10046            }
10047            mFlags = flags;
10048            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
10049            final int N = packageActivities.size();
10050            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
10051                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
10052
10053            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
10054            for (int i = 0; i < N; ++i) {
10055                intentFilters = packageActivities.get(i).intents;
10056                if (intentFilters != null && intentFilters.size() > 0) {
10057                    PackageParser.ActivityIntentInfo[] array =
10058                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
10059                    intentFilters.toArray(array);
10060                    listCut.add(array);
10061                }
10062            }
10063            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
10064        }
10065
10066        /**
10067         * Finds a privileged activity that matches the specified activity names.
10068         */
10069        private PackageParser.Activity findMatchingActivity(
10070                List<PackageParser.Activity> activityList, ActivityInfo activityInfo) {
10071            for (PackageParser.Activity sysActivity : activityList) {
10072                if (sysActivity.info.name.equals(activityInfo.name)) {
10073                    return sysActivity;
10074                }
10075                if (sysActivity.info.name.equals(activityInfo.targetActivity)) {
10076                    return sysActivity;
10077                }
10078                if (sysActivity.info.targetActivity != null) {
10079                    if (sysActivity.info.targetActivity.equals(activityInfo.name)) {
10080                        return sysActivity;
10081                    }
10082                    if (sysActivity.info.targetActivity.equals(activityInfo.targetActivity)) {
10083                        return sysActivity;
10084                    }
10085                }
10086            }
10087            return null;
10088        }
10089
10090        public class IterGenerator<E> {
10091            public Iterator<E> generate(ActivityIntentInfo info) {
10092                return null;
10093            }
10094        }
10095
10096        public class ActionIterGenerator extends IterGenerator<String> {
10097            @Override
10098            public Iterator<String> generate(ActivityIntentInfo info) {
10099                return info.actionsIterator();
10100            }
10101        }
10102
10103        public class CategoriesIterGenerator extends IterGenerator<String> {
10104            @Override
10105            public Iterator<String> generate(ActivityIntentInfo info) {
10106                return info.categoriesIterator();
10107            }
10108        }
10109
10110        public class SchemesIterGenerator extends IterGenerator<String> {
10111            @Override
10112            public Iterator<String> generate(ActivityIntentInfo info) {
10113                return info.schemesIterator();
10114            }
10115        }
10116
10117        public class AuthoritiesIterGenerator extends IterGenerator<IntentFilter.AuthorityEntry> {
10118            @Override
10119            public Iterator<IntentFilter.AuthorityEntry> generate(ActivityIntentInfo info) {
10120                return info.authoritiesIterator();
10121            }
10122        }
10123
10124        /**
10125         * <em>WARNING</em> for performance reasons, the passed in intentList WILL BE
10126         * MODIFIED. Do not pass in a list that should not be changed.
10127         */
10128        private <T> void getIntentListSubset(List<ActivityIntentInfo> intentList,
10129                IterGenerator<T> generator, Iterator<T> searchIterator) {
10130            // loop through the set of actions; every one must be found in the intent filter
10131            while (searchIterator.hasNext()) {
10132                // we must have at least one filter in the list to consider a match
10133                if (intentList.size() == 0) {
10134                    break;
10135                }
10136
10137                final T searchAction = searchIterator.next();
10138
10139                // loop through the set of intent filters
10140                final Iterator<ActivityIntentInfo> intentIter = intentList.iterator();
10141                while (intentIter.hasNext()) {
10142                    final ActivityIntentInfo intentInfo = intentIter.next();
10143                    boolean selectionFound = false;
10144
10145                    // loop through the intent filter's selection criteria; at least one
10146                    // of them must match the searched criteria
10147                    final Iterator<T> intentSelectionIter = generator.generate(intentInfo);
10148                    while (intentSelectionIter != null && intentSelectionIter.hasNext()) {
10149                        final T intentSelection = intentSelectionIter.next();
10150                        if (intentSelection != null && intentSelection.equals(searchAction)) {
10151                            selectionFound = true;
10152                            break;
10153                        }
10154                    }
10155
10156                    // the selection criteria wasn't found in this filter's set; this filter
10157                    // is not a potential match
10158                    if (!selectionFound) {
10159                        intentIter.remove();
10160                    }
10161                }
10162            }
10163        }
10164
10165        private boolean isProtectedAction(ActivityIntentInfo filter) {
10166            final Iterator<String> actionsIter = filter.actionsIterator();
10167            while (actionsIter != null && actionsIter.hasNext()) {
10168                final String filterAction = actionsIter.next();
10169                if (PROTECTED_ACTIONS.contains(filterAction)) {
10170                    return true;
10171                }
10172            }
10173            return false;
10174        }
10175
10176        /**
10177         * Adjusts the priority of the given intent filter according to policy.
10178         * <p>
10179         * <ul>
10180         * <li>The priority for non privileged applications is capped to '0'</li>
10181         * <li>The priority for protected actions on privileged applications is capped to '0'</li>
10182         * <li>The priority for unbundled updates to privileged applications is capped to the
10183         *      priority defined on the system partition</li>
10184         * </ul>
10185         * <p>
10186         * <em>NOTE:</em> There is one exception. For security reasons, the setup wizard is
10187         * allowed to obtain any priority on any action.
10188         */
10189        private void adjustPriority(
10190                List<PackageParser.Activity> systemActivities, ActivityIntentInfo intent) {
10191            // nothing to do; priority is fine as-is
10192            if (intent.getPriority() <= 0) {
10193                return;
10194            }
10195
10196            final ActivityInfo activityInfo = intent.activity.info;
10197            final ApplicationInfo applicationInfo = activityInfo.applicationInfo;
10198
10199            final boolean privilegedApp =
10200                    ((applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0);
10201            if (!privilegedApp) {
10202                // non-privileged applications can never define a priority >0
10203                Slog.w(TAG, "Non-privileged app; cap priority to 0;"
10204                        + " package: " + applicationInfo.packageName
10205                        + " activity: " + intent.activity.className
10206                        + " origPrio: " + intent.getPriority());
10207                intent.setPriority(0);
10208                return;
10209            }
10210
10211            if (systemActivities == null) {
10212                // the system package is not disabled; we're parsing the system partition
10213                if (isProtectedAction(intent)) {
10214                    if (mDeferProtectedFilters) {
10215                        // We can't deal with these just yet. No component should ever obtain a
10216                        // >0 priority for a protected actions, with ONE exception -- the setup
10217                        // wizard. The setup wizard, however, cannot be known until we're able to
10218                        // query it for the category CATEGORY_SETUP_WIZARD. Which we can't do
10219                        // until all intent filters have been processed. Chicken, meet egg.
10220                        // Let the filter temporarily have a high priority and rectify the
10221                        // priorities after all system packages have been scanned.
10222                        mProtectedFilters.add(intent);
10223                        if (DEBUG_FILTERS) {
10224                            Slog.i(TAG, "Protected action; save for later;"
10225                                    + " package: " + applicationInfo.packageName
10226                                    + " activity: " + intent.activity.className
10227                                    + " origPrio: " + intent.getPriority());
10228                        }
10229                        return;
10230                    } else {
10231                        if (DEBUG_FILTERS && mSetupWizardPackage == null) {
10232                            Slog.i(TAG, "No setup wizard;"
10233                                + " All protected intents capped to priority 0");
10234                        }
10235                        if (intent.activity.info.packageName.equals(mSetupWizardPackage)) {
10236                            if (DEBUG_FILTERS) {
10237                                Slog.i(TAG, "Found setup wizard;"
10238                                    + " allow priority " + intent.getPriority() + ";"
10239                                    + " package: " + intent.activity.info.packageName
10240                                    + " activity: " + intent.activity.className
10241                                    + " priority: " + intent.getPriority());
10242                            }
10243                            // setup wizard gets whatever it wants
10244                            return;
10245                        }
10246                        Slog.w(TAG, "Protected action; cap priority to 0;"
10247                                + " package: " + intent.activity.info.packageName
10248                                + " activity: " + intent.activity.className
10249                                + " origPrio: " + intent.getPriority());
10250                        intent.setPriority(0);
10251                        return;
10252                    }
10253                }
10254                // privileged apps on the system image get whatever priority they request
10255                return;
10256            }
10257
10258            // privileged app unbundled update ... try to find the same activity
10259            final PackageParser.Activity foundActivity =
10260                    findMatchingActivity(systemActivities, activityInfo);
10261            if (foundActivity == null) {
10262                // this is a new activity; it cannot obtain >0 priority
10263                if (DEBUG_FILTERS) {
10264                    Slog.i(TAG, "New activity; cap priority to 0;"
10265                            + " package: " + applicationInfo.packageName
10266                            + " activity: " + intent.activity.className
10267                            + " origPrio: " + intent.getPriority());
10268                }
10269                intent.setPriority(0);
10270                return;
10271            }
10272
10273            // found activity, now check for filter equivalence
10274
10275            // a shallow copy is enough; we modify the list, not its contents
10276            final List<ActivityIntentInfo> intentListCopy =
10277                    new ArrayList<>(foundActivity.intents);
10278            final List<ActivityIntentInfo> foundFilters = findFilters(intent);
10279
10280            // find matching action subsets
10281            final Iterator<String> actionsIterator = intent.actionsIterator();
10282            if (actionsIterator != null) {
10283                getIntentListSubset(
10284                        intentListCopy, new ActionIterGenerator(), actionsIterator);
10285                if (intentListCopy.size() == 0) {
10286                    // no more intents to match; we're not equivalent
10287                    if (DEBUG_FILTERS) {
10288                        Slog.i(TAG, "Mismatched action; cap priority to 0;"
10289                                + " package: " + applicationInfo.packageName
10290                                + " activity: " + intent.activity.className
10291                                + " origPrio: " + intent.getPriority());
10292                    }
10293                    intent.setPriority(0);
10294                    return;
10295                }
10296            }
10297
10298            // find matching category subsets
10299            final Iterator<String> categoriesIterator = intent.categoriesIterator();
10300            if (categoriesIterator != null) {
10301                getIntentListSubset(intentListCopy, new CategoriesIterGenerator(),
10302                        categoriesIterator);
10303                if (intentListCopy.size() == 0) {
10304                    // no more intents to match; we're not equivalent
10305                    if (DEBUG_FILTERS) {
10306                        Slog.i(TAG, "Mismatched category; cap priority to 0;"
10307                                + " package: " + applicationInfo.packageName
10308                                + " activity: " + intent.activity.className
10309                                + " origPrio: " + intent.getPriority());
10310                    }
10311                    intent.setPriority(0);
10312                    return;
10313                }
10314            }
10315
10316            // find matching schemes subsets
10317            final Iterator<String> schemesIterator = intent.schemesIterator();
10318            if (schemesIterator != null) {
10319                getIntentListSubset(intentListCopy, new SchemesIterGenerator(),
10320                        schemesIterator);
10321                if (intentListCopy.size() == 0) {
10322                    // no more intents to match; we're not equivalent
10323                    if (DEBUG_FILTERS) {
10324                        Slog.i(TAG, "Mismatched scheme; cap priority to 0;"
10325                                + " package: " + applicationInfo.packageName
10326                                + " activity: " + intent.activity.className
10327                                + " origPrio: " + intent.getPriority());
10328                    }
10329                    intent.setPriority(0);
10330                    return;
10331                }
10332            }
10333
10334            // find matching authorities subsets
10335            final Iterator<IntentFilter.AuthorityEntry>
10336                    authoritiesIterator = intent.authoritiesIterator();
10337            if (authoritiesIterator != null) {
10338                getIntentListSubset(intentListCopy,
10339                        new AuthoritiesIterGenerator(),
10340                        authoritiesIterator);
10341                if (intentListCopy.size() == 0) {
10342                    // no more intents to match; we're not equivalent
10343                    if (DEBUG_FILTERS) {
10344                        Slog.i(TAG, "Mismatched authority; cap priority to 0;"
10345                                + " package: " + applicationInfo.packageName
10346                                + " activity: " + intent.activity.className
10347                                + " origPrio: " + intent.getPriority());
10348                    }
10349                    intent.setPriority(0);
10350                    return;
10351                }
10352            }
10353
10354            // we found matching filter(s); app gets the max priority of all intents
10355            int cappedPriority = 0;
10356            for (int i = intentListCopy.size() - 1; i >= 0; --i) {
10357                cappedPriority = Math.max(cappedPriority, intentListCopy.get(i).getPriority());
10358            }
10359            if (intent.getPriority() > cappedPriority) {
10360                if (DEBUG_FILTERS) {
10361                    Slog.i(TAG, "Found matching filter(s);"
10362                            + " cap priority to " + cappedPriority + ";"
10363                            + " package: " + applicationInfo.packageName
10364                            + " activity: " + intent.activity.className
10365                            + " origPrio: " + intent.getPriority());
10366                }
10367                intent.setPriority(cappedPriority);
10368                return;
10369            }
10370            // all this for nothing; the requested priority was <= what was on the system
10371        }
10372
10373        public final void addActivity(PackageParser.Activity a, String type) {
10374            mActivities.put(a.getComponentName(), a);
10375            if (DEBUG_SHOW_INFO)
10376                Log.v(
10377                TAG, "  " + type + " " +
10378                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
10379            if (DEBUG_SHOW_INFO)
10380                Log.v(TAG, "    Class=" + a.info.name);
10381            final int NI = a.intents.size();
10382            for (int j=0; j<NI; j++) {
10383                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
10384                if ("activity".equals(type)) {
10385                    final PackageSetting ps =
10386                            mSettings.getDisabledSystemPkgLPr(intent.activity.info.packageName);
10387                    final List<PackageParser.Activity> systemActivities =
10388                            ps != null && ps.pkg != null ? ps.pkg.activities : null;
10389                    adjustPriority(systemActivities, intent);
10390                }
10391                if (DEBUG_SHOW_INFO) {
10392                    Log.v(TAG, "    IntentFilter:");
10393                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
10394                }
10395                if (!intent.debugCheck()) {
10396                    Log.w(TAG, "==> For Activity " + a.info.name);
10397                }
10398                addFilter(intent);
10399            }
10400        }
10401
10402        public final void removeActivity(PackageParser.Activity a, String type) {
10403            mActivities.remove(a.getComponentName());
10404            if (DEBUG_SHOW_INFO) {
10405                Log.v(TAG, "  " + type + " "
10406                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
10407                                : a.info.name) + ":");
10408                Log.v(TAG, "    Class=" + a.info.name);
10409            }
10410            final int NI = a.intents.size();
10411            for (int j=0; j<NI; j++) {
10412                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
10413                if (DEBUG_SHOW_INFO) {
10414                    Log.v(TAG, "    IntentFilter:");
10415                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
10416                }
10417                removeFilter(intent);
10418            }
10419        }
10420
10421        @Override
10422        protected boolean allowFilterResult(
10423                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
10424            ActivityInfo filterAi = filter.activity.info;
10425            for (int i=dest.size()-1; i>=0; i--) {
10426                ActivityInfo destAi = dest.get(i).activityInfo;
10427                if (destAi.name == filterAi.name
10428                        && destAi.packageName == filterAi.packageName) {
10429                    return false;
10430                }
10431            }
10432            return true;
10433        }
10434
10435        @Override
10436        protected ActivityIntentInfo[] newArray(int size) {
10437            return new ActivityIntentInfo[size];
10438        }
10439
10440        @Override
10441        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
10442            if (!sUserManager.exists(userId)) return true;
10443            PackageParser.Package p = filter.activity.owner;
10444            if (p != null) {
10445                PackageSetting ps = (PackageSetting)p.mExtras;
10446                if (ps != null) {
10447                    // System apps are never considered stopped for purposes of
10448                    // filtering, because there may be no way for the user to
10449                    // actually re-launch them.
10450                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
10451                            && ps.getStopped(userId);
10452                }
10453            }
10454            return false;
10455        }
10456
10457        @Override
10458        protected boolean isPackageForFilter(String packageName,
10459                PackageParser.ActivityIntentInfo info) {
10460            return packageName.equals(info.activity.owner.packageName);
10461        }
10462
10463        @Override
10464        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
10465                int match, int userId) {
10466            if (!sUserManager.exists(userId)) return null;
10467            if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) {
10468                return null;
10469            }
10470            final PackageParser.Activity activity = info.activity;
10471            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
10472            if (ps == null) {
10473                return null;
10474            }
10475            ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags,
10476                    ps.readUserState(userId), userId);
10477            if (ai == null) {
10478                return null;
10479            }
10480            final ResolveInfo res = new ResolveInfo();
10481            res.activityInfo = ai;
10482            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
10483                res.filter = info;
10484            }
10485            if (info != null) {
10486                res.handleAllWebDataURI = info.handleAllWebDataURI();
10487            }
10488            res.priority = info.getPriority();
10489            res.preferredOrder = activity.owner.mPreferredOrder;
10490            //System.out.println("Result: " + res.activityInfo.className +
10491            //                   " = " + res.priority);
10492            res.match = match;
10493            res.isDefault = info.hasDefault;
10494            res.labelRes = info.labelRes;
10495            res.nonLocalizedLabel = info.nonLocalizedLabel;
10496            if (userNeedsBadging(userId)) {
10497                res.noResourceId = true;
10498            } else {
10499                res.icon = info.icon;
10500            }
10501            res.iconResourceId = info.icon;
10502            res.system = res.activityInfo.applicationInfo.isSystemApp();
10503            return res;
10504        }
10505
10506        @Override
10507        protected void sortResults(List<ResolveInfo> results) {
10508            Collections.sort(results, mResolvePrioritySorter);
10509        }
10510
10511        @Override
10512        protected void dumpFilter(PrintWriter out, String prefix,
10513                PackageParser.ActivityIntentInfo filter) {
10514            out.print(prefix); out.print(
10515                    Integer.toHexString(System.identityHashCode(filter.activity)));
10516                    out.print(' ');
10517                    filter.activity.printComponentShortName(out);
10518                    out.print(" filter ");
10519                    out.println(Integer.toHexString(System.identityHashCode(filter)));
10520        }
10521
10522        @Override
10523        protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) {
10524            return filter.activity;
10525        }
10526
10527        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
10528            PackageParser.Activity activity = (PackageParser.Activity)label;
10529            out.print(prefix); out.print(
10530                    Integer.toHexString(System.identityHashCode(activity)));
10531                    out.print(' ');
10532                    activity.printComponentShortName(out);
10533            if (count > 1) {
10534                out.print(" ("); out.print(count); out.print(" filters)");
10535            }
10536            out.println();
10537        }
10538
10539        // Keys are String (activity class name), values are Activity.
10540        private final ArrayMap<ComponentName, PackageParser.Activity> mActivities
10541                = new ArrayMap<ComponentName, PackageParser.Activity>();
10542        private int mFlags;
10543    }
10544
10545    private final class ServiceIntentResolver
10546            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
10547        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
10548                boolean defaultOnly, int userId) {
10549            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
10550            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
10551        }
10552
10553        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
10554                int userId) {
10555            if (!sUserManager.exists(userId)) return null;
10556            mFlags = flags;
10557            return super.queryIntent(intent, resolvedType,
10558                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
10559        }
10560
10561        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
10562                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
10563            if (!sUserManager.exists(userId)) return null;
10564            if (packageServices == null) {
10565                return null;
10566            }
10567            mFlags = flags;
10568            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
10569            final int N = packageServices.size();
10570            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
10571                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
10572
10573            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
10574            for (int i = 0; i < N; ++i) {
10575                intentFilters = packageServices.get(i).intents;
10576                if (intentFilters != null && intentFilters.size() > 0) {
10577                    PackageParser.ServiceIntentInfo[] array =
10578                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
10579                    intentFilters.toArray(array);
10580                    listCut.add(array);
10581                }
10582            }
10583            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
10584        }
10585
10586        public final void addService(PackageParser.Service s) {
10587            mServices.put(s.getComponentName(), s);
10588            if (DEBUG_SHOW_INFO) {
10589                Log.v(TAG, "  "
10590                        + (s.info.nonLocalizedLabel != null
10591                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
10592                Log.v(TAG, "    Class=" + s.info.name);
10593            }
10594            final int NI = s.intents.size();
10595            int j;
10596            for (j=0; j<NI; j++) {
10597                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
10598                if (DEBUG_SHOW_INFO) {
10599                    Log.v(TAG, "    IntentFilter:");
10600                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
10601                }
10602                if (!intent.debugCheck()) {
10603                    Log.w(TAG, "==> For Service " + s.info.name);
10604                }
10605                addFilter(intent);
10606            }
10607        }
10608
10609        public final void removeService(PackageParser.Service s) {
10610            mServices.remove(s.getComponentName());
10611            if (DEBUG_SHOW_INFO) {
10612                Log.v(TAG, "  " + (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                removeFilter(intent);
10625            }
10626        }
10627
10628        @Override
10629        protected boolean allowFilterResult(
10630                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
10631            ServiceInfo filterSi = filter.service.info;
10632            for (int i=dest.size()-1; i>=0; i--) {
10633                ServiceInfo destAi = dest.get(i).serviceInfo;
10634                if (destAi.name == filterSi.name
10635                        && destAi.packageName == filterSi.packageName) {
10636                    return false;
10637                }
10638            }
10639            return true;
10640        }
10641
10642        @Override
10643        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
10644            return new PackageParser.ServiceIntentInfo[size];
10645        }
10646
10647        @Override
10648        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
10649            if (!sUserManager.exists(userId)) return true;
10650            PackageParser.Package p = filter.service.owner;
10651            if (p != null) {
10652                PackageSetting ps = (PackageSetting)p.mExtras;
10653                if (ps != null) {
10654                    // System apps are never considered stopped for purposes of
10655                    // filtering, because there may be no way for the user to
10656                    // actually re-launch them.
10657                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
10658                            && ps.getStopped(userId);
10659                }
10660            }
10661            return false;
10662        }
10663
10664        @Override
10665        protected boolean isPackageForFilter(String packageName,
10666                PackageParser.ServiceIntentInfo info) {
10667            return packageName.equals(info.service.owner.packageName);
10668        }
10669
10670        @Override
10671        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
10672                int match, int userId) {
10673            if (!sUserManager.exists(userId)) return null;
10674            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
10675            if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) {
10676                return null;
10677            }
10678            final PackageParser.Service service = info.service;
10679            PackageSetting ps = (PackageSetting) service.owner.mExtras;
10680            if (ps == null) {
10681                return null;
10682            }
10683            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
10684                    ps.readUserState(userId), userId);
10685            if (si == null) {
10686                return null;
10687            }
10688            final ResolveInfo res = new ResolveInfo();
10689            res.serviceInfo = si;
10690            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
10691                res.filter = filter;
10692            }
10693            res.priority = info.getPriority();
10694            res.preferredOrder = service.owner.mPreferredOrder;
10695            res.match = match;
10696            res.isDefault = info.hasDefault;
10697            res.labelRes = info.labelRes;
10698            res.nonLocalizedLabel = info.nonLocalizedLabel;
10699            res.icon = info.icon;
10700            res.system = res.serviceInfo.applicationInfo.isSystemApp();
10701            return res;
10702        }
10703
10704        @Override
10705        protected void sortResults(List<ResolveInfo> results) {
10706            Collections.sort(results, mResolvePrioritySorter);
10707        }
10708
10709        @Override
10710        protected void dumpFilter(PrintWriter out, String prefix,
10711                PackageParser.ServiceIntentInfo filter) {
10712            out.print(prefix); out.print(
10713                    Integer.toHexString(System.identityHashCode(filter.service)));
10714                    out.print(' ');
10715                    filter.service.printComponentShortName(out);
10716                    out.print(" filter ");
10717                    out.println(Integer.toHexString(System.identityHashCode(filter)));
10718        }
10719
10720        @Override
10721        protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) {
10722            return filter.service;
10723        }
10724
10725        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
10726            PackageParser.Service service = (PackageParser.Service)label;
10727            out.print(prefix); out.print(
10728                    Integer.toHexString(System.identityHashCode(service)));
10729                    out.print(' ');
10730                    service.printComponentShortName(out);
10731            if (count > 1) {
10732                out.print(" ("); out.print(count); out.print(" filters)");
10733            }
10734            out.println();
10735        }
10736
10737//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
10738//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
10739//            final List<ResolveInfo> retList = Lists.newArrayList();
10740//            while (i.hasNext()) {
10741//                final ResolveInfo resolveInfo = (ResolveInfo) i;
10742//                if (isEnabledLP(resolveInfo.serviceInfo)) {
10743//                    retList.add(resolveInfo);
10744//                }
10745//            }
10746//            return retList;
10747//        }
10748
10749        // Keys are String (activity class name), values are Activity.
10750        private final ArrayMap<ComponentName, PackageParser.Service> mServices
10751                = new ArrayMap<ComponentName, PackageParser.Service>();
10752        private int mFlags;
10753    };
10754
10755    private final class ProviderIntentResolver
10756            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
10757        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
10758                boolean defaultOnly, int userId) {
10759            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
10760            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
10761        }
10762
10763        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
10764                int userId) {
10765            if (!sUserManager.exists(userId))
10766                return null;
10767            mFlags = flags;
10768            return super.queryIntent(intent, resolvedType,
10769                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
10770        }
10771
10772        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
10773                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
10774            if (!sUserManager.exists(userId))
10775                return null;
10776            if (packageProviders == null) {
10777                return null;
10778            }
10779            mFlags = flags;
10780            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
10781            final int N = packageProviders.size();
10782            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
10783                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
10784
10785            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
10786            for (int i = 0; i < N; ++i) {
10787                intentFilters = packageProviders.get(i).intents;
10788                if (intentFilters != null && intentFilters.size() > 0) {
10789                    PackageParser.ProviderIntentInfo[] array =
10790                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
10791                    intentFilters.toArray(array);
10792                    listCut.add(array);
10793                }
10794            }
10795            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
10796        }
10797
10798        public final void addProvider(PackageParser.Provider p) {
10799            if (mProviders.containsKey(p.getComponentName())) {
10800                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
10801                return;
10802            }
10803
10804            mProviders.put(p.getComponentName(), p);
10805            if (DEBUG_SHOW_INFO) {
10806                Log.v(TAG, "  "
10807                        + (p.info.nonLocalizedLabel != null
10808                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
10809                Log.v(TAG, "    Class=" + p.info.name);
10810            }
10811            final int NI = p.intents.size();
10812            int j;
10813            for (j = 0; j < NI; j++) {
10814                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
10815                if (DEBUG_SHOW_INFO) {
10816                    Log.v(TAG, "    IntentFilter:");
10817                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
10818                }
10819                if (!intent.debugCheck()) {
10820                    Log.w(TAG, "==> For Provider " + p.info.name);
10821                }
10822                addFilter(intent);
10823            }
10824        }
10825
10826        public final void removeProvider(PackageParser.Provider p) {
10827            mProviders.remove(p.getComponentName());
10828            if (DEBUG_SHOW_INFO) {
10829                Log.v(TAG, "  " + (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                removeFilter(intent);
10842            }
10843        }
10844
10845        @Override
10846        protected boolean allowFilterResult(
10847                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
10848            ProviderInfo filterPi = filter.provider.info;
10849            for (int i = dest.size() - 1; i >= 0; i--) {
10850                ProviderInfo destPi = dest.get(i).providerInfo;
10851                if (destPi.name == filterPi.name
10852                        && destPi.packageName == filterPi.packageName) {
10853                    return false;
10854                }
10855            }
10856            return true;
10857        }
10858
10859        @Override
10860        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
10861            return new PackageParser.ProviderIntentInfo[size];
10862        }
10863
10864        @Override
10865        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
10866            if (!sUserManager.exists(userId))
10867                return true;
10868            PackageParser.Package p = filter.provider.owner;
10869            if (p != null) {
10870                PackageSetting ps = (PackageSetting) p.mExtras;
10871                if (ps != null) {
10872                    // System apps are never considered stopped for purposes of
10873                    // filtering, because there may be no way for the user to
10874                    // actually re-launch them.
10875                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
10876                            && ps.getStopped(userId);
10877                }
10878            }
10879            return false;
10880        }
10881
10882        @Override
10883        protected boolean isPackageForFilter(String packageName,
10884                PackageParser.ProviderIntentInfo info) {
10885            return packageName.equals(info.provider.owner.packageName);
10886        }
10887
10888        @Override
10889        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
10890                int match, int userId) {
10891            if (!sUserManager.exists(userId))
10892                return null;
10893            final PackageParser.ProviderIntentInfo info = filter;
10894            if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) {
10895                return null;
10896            }
10897            final PackageParser.Provider provider = info.provider;
10898            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
10899            if (ps == null) {
10900                return null;
10901            }
10902            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
10903                    ps.readUserState(userId), userId);
10904            if (pi == null) {
10905                return null;
10906            }
10907            final ResolveInfo res = new ResolveInfo();
10908            res.providerInfo = pi;
10909            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
10910                res.filter = filter;
10911            }
10912            res.priority = info.getPriority();
10913            res.preferredOrder = provider.owner.mPreferredOrder;
10914            res.match = match;
10915            res.isDefault = info.hasDefault;
10916            res.labelRes = info.labelRes;
10917            res.nonLocalizedLabel = info.nonLocalizedLabel;
10918            res.icon = info.icon;
10919            res.system = res.providerInfo.applicationInfo.isSystemApp();
10920            return res;
10921        }
10922
10923        @Override
10924        protected void sortResults(List<ResolveInfo> results) {
10925            Collections.sort(results, mResolvePrioritySorter);
10926        }
10927
10928        @Override
10929        protected void dumpFilter(PrintWriter out, String prefix,
10930                PackageParser.ProviderIntentInfo filter) {
10931            out.print(prefix);
10932            out.print(
10933                    Integer.toHexString(System.identityHashCode(filter.provider)));
10934            out.print(' ');
10935            filter.provider.printComponentShortName(out);
10936            out.print(" filter ");
10937            out.println(Integer.toHexString(System.identityHashCode(filter)));
10938        }
10939
10940        @Override
10941        protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) {
10942            return filter.provider;
10943        }
10944
10945        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
10946            PackageParser.Provider provider = (PackageParser.Provider)label;
10947            out.print(prefix); out.print(
10948                    Integer.toHexString(System.identityHashCode(provider)));
10949                    out.print(' ');
10950                    provider.printComponentShortName(out);
10951            if (count > 1) {
10952                out.print(" ("); out.print(count); out.print(" filters)");
10953            }
10954            out.println();
10955        }
10956
10957        private final ArrayMap<ComponentName, PackageParser.Provider> mProviders
10958                = new ArrayMap<ComponentName, PackageParser.Provider>();
10959        private int mFlags;
10960    }
10961
10962    private static final class EphemeralIntentResolver
10963            extends IntentResolver<EphemeralResolveIntentInfo, EphemeralResolveInfo> {
10964        @Override
10965        protected EphemeralResolveIntentInfo[] newArray(int size) {
10966            return new EphemeralResolveIntentInfo[size];
10967        }
10968
10969        @Override
10970        protected boolean isPackageForFilter(String packageName, EphemeralResolveIntentInfo info) {
10971            return true;
10972        }
10973
10974        @Override
10975        protected EphemeralResolveInfo newResult(EphemeralResolveIntentInfo info, int match,
10976                int userId) {
10977            if (!sUserManager.exists(userId)) {
10978                return null;
10979            }
10980            return info.getEphemeralResolveInfo();
10981        }
10982    }
10983
10984    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
10985            new Comparator<ResolveInfo>() {
10986        public int compare(ResolveInfo r1, ResolveInfo r2) {
10987            int v1 = r1.priority;
10988            int v2 = r2.priority;
10989            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
10990            if (v1 != v2) {
10991                return (v1 > v2) ? -1 : 1;
10992            }
10993            v1 = r1.preferredOrder;
10994            v2 = r2.preferredOrder;
10995            if (v1 != v2) {
10996                return (v1 > v2) ? -1 : 1;
10997            }
10998            if (r1.isDefault != r2.isDefault) {
10999                return r1.isDefault ? -1 : 1;
11000            }
11001            v1 = r1.match;
11002            v2 = r2.match;
11003            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
11004            if (v1 != v2) {
11005                return (v1 > v2) ? -1 : 1;
11006            }
11007            if (r1.system != r2.system) {
11008                return r1.system ? -1 : 1;
11009            }
11010            if (r1.activityInfo != null) {
11011                return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName);
11012            }
11013            if (r1.serviceInfo != null) {
11014                return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName);
11015            }
11016            if (r1.providerInfo != null) {
11017                return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName);
11018            }
11019            return 0;
11020        }
11021    };
11022
11023    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
11024            new Comparator<ProviderInfo>() {
11025        public int compare(ProviderInfo p1, ProviderInfo p2) {
11026            final int v1 = p1.initOrder;
11027            final int v2 = p2.initOrder;
11028            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
11029        }
11030    };
11031
11032    final void sendPackageBroadcast(final String action, final String pkg, final Bundle extras,
11033            final int flags, final String targetPkg, final IIntentReceiver finishedReceiver,
11034            final int[] userIds) {
11035        mHandler.post(new Runnable() {
11036            @Override
11037            public void run() {
11038                try {
11039                    final IActivityManager am = ActivityManagerNative.getDefault();
11040                    if (am == null) return;
11041                    final int[] resolvedUserIds;
11042                    if (userIds == null) {
11043                        resolvedUserIds = am.getRunningUserIds();
11044                    } else {
11045                        resolvedUserIds = userIds;
11046                    }
11047                    for (int id : resolvedUserIds) {
11048                        final Intent intent = new Intent(action,
11049                                pkg != null ? Uri.fromParts("package", pkg, null) : null);
11050                        if (extras != null) {
11051                            intent.putExtras(extras);
11052                        }
11053                        if (targetPkg != null) {
11054                            intent.setPackage(targetPkg);
11055                        }
11056                        // Modify the UID when posting to other users
11057                        int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
11058                        if (uid > 0 && UserHandle.getUserId(uid) != id) {
11059                            uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
11060                            intent.putExtra(Intent.EXTRA_UID, uid);
11061                        }
11062                        intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
11063                        intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags);
11064                        if (DEBUG_BROADCASTS) {
11065                            RuntimeException here = new RuntimeException("here");
11066                            here.fillInStackTrace();
11067                            Slog.d(TAG, "Sending to user " + id + ": "
11068                                    + intent.toShortString(false, true, false, false)
11069                                    + " " + intent.getExtras(), here);
11070                        }
11071                        am.broadcastIntent(null, intent, null, finishedReceiver,
11072                                0, null, null, null, android.app.AppOpsManager.OP_NONE,
11073                                null, finishedReceiver != null, false, id);
11074                    }
11075                } catch (RemoteException ex) {
11076                }
11077            }
11078        });
11079    }
11080
11081    /**
11082     * Check if the external storage media is available. This is true if there
11083     * is a mounted external storage medium or if the external storage is
11084     * emulated.
11085     */
11086    private boolean isExternalMediaAvailable() {
11087        return mMediaMounted || Environment.isExternalStorageEmulated();
11088    }
11089
11090    @Override
11091    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
11092        // writer
11093        synchronized (mPackages) {
11094            if (!isExternalMediaAvailable()) {
11095                // If the external storage is no longer mounted at this point,
11096                // the caller may not have been able to delete all of this
11097                // packages files and can not delete any more.  Bail.
11098                return null;
11099            }
11100            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
11101            if (lastPackage != null) {
11102                pkgs.remove(lastPackage);
11103            }
11104            if (pkgs.size() > 0) {
11105                return pkgs.get(0);
11106            }
11107        }
11108        return null;
11109    }
11110
11111    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
11112        final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
11113                userId, andCode ? 1 : 0, packageName);
11114        if (mSystemReady) {
11115            msg.sendToTarget();
11116        } else {
11117            if (mPostSystemReadyMessages == null) {
11118                mPostSystemReadyMessages = new ArrayList<>();
11119            }
11120            mPostSystemReadyMessages.add(msg);
11121        }
11122    }
11123
11124    void startCleaningPackages() {
11125        // reader
11126        if (!isExternalMediaAvailable()) {
11127            return;
11128        }
11129        synchronized (mPackages) {
11130            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
11131                return;
11132            }
11133        }
11134        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
11135        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
11136        IActivityManager am = ActivityManagerNative.getDefault();
11137        if (am != null) {
11138            try {
11139                am.startService(null, intent, null, mContext.getOpPackageName(),
11140                        UserHandle.USER_SYSTEM);
11141            } catch (RemoteException e) {
11142            }
11143        }
11144    }
11145
11146    @Override
11147    public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer,
11148            int installFlags, String installerPackageName, int userId) {
11149        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
11150
11151        final int callingUid = Binder.getCallingUid();
11152        enforceCrossUserPermission(callingUid, userId,
11153                true /* requireFullPermission */, true /* checkShell */, "installPackageAsUser");
11154
11155        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
11156            try {
11157                if (observer != null) {
11158                    observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null);
11159                }
11160            } catch (RemoteException re) {
11161            }
11162            return;
11163        }
11164
11165        if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) {
11166            installFlags |= PackageManager.INSTALL_FROM_ADB;
11167
11168        } else {
11169            // Caller holds INSTALL_PACKAGES permission, so we're less strict
11170            // about installerPackageName.
11171
11172            installFlags &= ~PackageManager.INSTALL_FROM_ADB;
11173            installFlags &= ~PackageManager.INSTALL_ALL_USERS;
11174        }
11175
11176        UserHandle user;
11177        if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) {
11178            user = UserHandle.ALL;
11179        } else {
11180            user = new UserHandle(userId);
11181        }
11182
11183        // Only system components can circumvent runtime permissions when installing.
11184        if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0
11185                && mContext.checkCallingOrSelfPermission(Manifest.permission
11186                .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) {
11187            throw new SecurityException("You need the "
11188                    + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission "
11189                    + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag");
11190        }
11191
11192        final File originFile = new File(originPath);
11193        final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile);
11194
11195        final Message msg = mHandler.obtainMessage(INIT_COPY);
11196        final VerificationInfo verificationInfo = new VerificationInfo(
11197                null /*originatingUri*/, null /*referrer*/, -1 /*originatingUid*/, callingUid);
11198        final InstallParams params = new InstallParams(origin, null /*moveInfo*/, observer,
11199                installFlags, installerPackageName, null /*volumeUuid*/, verificationInfo, user,
11200                null /*packageAbiOverride*/, null /*grantedPermissions*/,
11201                null /*certificates*/);
11202        params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params));
11203        msg.obj = params;
11204
11205        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser",
11206                System.identityHashCode(msg.obj));
11207        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
11208                System.identityHashCode(msg.obj));
11209
11210        mHandler.sendMessage(msg);
11211    }
11212
11213    void installStage(String packageName, File stagedDir, String stagedCid,
11214            IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams,
11215            String installerPackageName, int installerUid, UserHandle user,
11216            Certificate[][] certificates) {
11217        if (DEBUG_EPHEMERAL) {
11218            if ((sessionParams.installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) {
11219                Slog.d(TAG, "Ephemeral install of " + packageName);
11220            }
11221        }
11222        final VerificationInfo verificationInfo = new VerificationInfo(
11223                sessionParams.originatingUri, sessionParams.referrerUri,
11224                sessionParams.originatingUid, installerUid);
11225
11226        final OriginInfo origin;
11227        if (stagedDir != null) {
11228            origin = OriginInfo.fromStagedFile(stagedDir);
11229        } else {
11230            origin = OriginInfo.fromStagedContainer(stagedCid);
11231        }
11232
11233        final Message msg = mHandler.obtainMessage(INIT_COPY);
11234        final InstallParams params = new InstallParams(origin, null, observer,
11235                sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid,
11236                verificationInfo, user, sessionParams.abiOverride,
11237                sessionParams.grantedRuntimePermissions, certificates);
11238        params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params));
11239        msg.obj = params;
11240
11241        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage",
11242                System.identityHashCode(msg.obj));
11243        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
11244                System.identityHashCode(msg.obj));
11245
11246        mHandler.sendMessage(msg);
11247    }
11248
11249    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting,
11250            int userId) {
11251        final boolean isSystem = isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
11252        sendPackageAddedForUser(packageName, isSystem, pkgSetting.appId, userId);
11253    }
11254
11255    private void sendPackageAddedForUser(String packageName, boolean isSystem,
11256            int appId, int userId) {
11257        Bundle extras = new Bundle(1);
11258        extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, appId));
11259
11260        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
11261                packageName, extras, 0, null, null, new int[] {userId});
11262        try {
11263            IActivityManager am = ActivityManagerNative.getDefault();
11264            if (isSystem && am.isUserRunning(userId, 0)) {
11265                // The just-installed/enabled app is bundled on the system, so presumed
11266                // to be able to run automatically without needing an explicit launch.
11267                // Send it a BOOT_COMPLETED if it would ordinarily have gotten one.
11268                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED)
11269                        .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES)
11270                        .setPackage(packageName);
11271                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null,
11272                        android.app.AppOpsManager.OP_NONE, null, false, false, userId);
11273            }
11274        } catch (RemoteException e) {
11275            // shouldn't happen
11276            Slog.w(TAG, "Unable to bootstrap installed package", e);
11277        }
11278    }
11279
11280    @Override
11281    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
11282            int userId) {
11283        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
11284        PackageSetting pkgSetting;
11285        final int uid = Binder.getCallingUid();
11286        enforceCrossUserPermission(uid, userId,
11287                true /* requireFullPermission */, true /* checkShell */,
11288                "setApplicationHiddenSetting for user " + userId);
11289
11290        if (hidden && isPackageDeviceAdmin(packageName, userId)) {
11291            Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
11292            return false;
11293        }
11294
11295        long callingId = Binder.clearCallingIdentity();
11296        try {
11297            boolean sendAdded = false;
11298            boolean sendRemoved = false;
11299            // writer
11300            synchronized (mPackages) {
11301                pkgSetting = mSettings.mPackages.get(packageName);
11302                if (pkgSetting == null) {
11303                    return false;
11304                }
11305                if (pkgSetting.getHidden(userId) != hidden) {
11306                    pkgSetting.setHidden(hidden, userId);
11307                    mSettings.writePackageRestrictionsLPr(userId);
11308                    if (hidden) {
11309                        sendRemoved = true;
11310                    } else {
11311                        sendAdded = true;
11312                    }
11313                }
11314            }
11315            if (sendAdded) {
11316                sendPackageAddedForUser(packageName, pkgSetting, userId);
11317                return true;
11318            }
11319            if (sendRemoved) {
11320                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
11321                        "hiding pkg");
11322                sendApplicationHiddenForUser(packageName, pkgSetting, userId);
11323                return true;
11324            }
11325        } finally {
11326            Binder.restoreCallingIdentity(callingId);
11327        }
11328        return false;
11329    }
11330
11331    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
11332            int userId) {
11333        final PackageRemovedInfo info = new PackageRemovedInfo();
11334        info.removedPackage = packageName;
11335        info.removedUsers = new int[] {userId};
11336        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
11337        info.sendPackageRemovedBroadcasts(true /*killApp*/);
11338    }
11339
11340    private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended) {
11341        if (pkgList.length > 0) {
11342            Bundle extras = new Bundle(1);
11343            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
11344
11345            sendPackageBroadcast(
11346                    suspended ? Intent.ACTION_PACKAGES_SUSPENDED
11347                            : Intent.ACTION_PACKAGES_UNSUSPENDED,
11348                    null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null,
11349                    new int[] {userId});
11350        }
11351    }
11352
11353    /**
11354     * Returns true if application is not found or there was an error. Otherwise it returns
11355     * the hidden state of the package for the given user.
11356     */
11357    @Override
11358    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
11359        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
11360        enforceCrossUserPermission(Binder.getCallingUid(), userId,
11361                true /* requireFullPermission */, false /* checkShell */,
11362                "getApplicationHidden for user " + userId);
11363        PackageSetting pkgSetting;
11364        long callingId = Binder.clearCallingIdentity();
11365        try {
11366            // writer
11367            synchronized (mPackages) {
11368                pkgSetting = mSettings.mPackages.get(packageName);
11369                if (pkgSetting == null) {
11370                    return true;
11371                }
11372                return pkgSetting.getHidden(userId);
11373            }
11374        } finally {
11375            Binder.restoreCallingIdentity(callingId);
11376        }
11377    }
11378
11379    /**
11380     * @hide
11381     */
11382    @Override
11383    public int installExistingPackageAsUser(String packageName, int userId) {
11384        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
11385                null);
11386        PackageSetting pkgSetting;
11387        final int uid = Binder.getCallingUid();
11388        enforceCrossUserPermission(uid, userId,
11389                true /* requireFullPermission */, true /* checkShell */,
11390                "installExistingPackage for user " + userId);
11391        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
11392            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
11393        }
11394
11395        long callingId = Binder.clearCallingIdentity();
11396        try {
11397            boolean installed = false;
11398
11399            // writer
11400            synchronized (mPackages) {
11401                pkgSetting = mSettings.mPackages.get(packageName);
11402                if (pkgSetting == null) {
11403                    return PackageManager.INSTALL_FAILED_INVALID_URI;
11404                }
11405                if (!pkgSetting.getInstalled(userId)) {
11406                    pkgSetting.setInstalled(true, userId);
11407                    pkgSetting.setHidden(false, userId);
11408                    mSettings.writePackageRestrictionsLPr(userId);
11409                    installed = true;
11410                }
11411            }
11412
11413            if (installed) {
11414                if (pkgSetting.pkg != null) {
11415                    synchronized (mInstallLock) {
11416                        // We don't need to freeze for a brand new install
11417                        prepareAppDataAfterInstallLIF(pkgSetting.pkg);
11418                    }
11419                }
11420                sendPackageAddedForUser(packageName, pkgSetting, userId);
11421            }
11422        } finally {
11423            Binder.restoreCallingIdentity(callingId);
11424        }
11425
11426        return PackageManager.INSTALL_SUCCEEDED;
11427    }
11428
11429    boolean isUserRestricted(int userId, String restrictionKey) {
11430        Bundle restrictions = sUserManager.getUserRestrictions(userId);
11431        if (restrictions.getBoolean(restrictionKey, false)) {
11432            Log.w(TAG, "User is restricted: " + restrictionKey);
11433            return true;
11434        }
11435        return false;
11436    }
11437
11438    @Override
11439    public String[] setPackagesSuspendedAsUser(String[] packageNames, boolean suspended,
11440            int userId) {
11441        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
11442        enforceCrossUserPermission(Binder.getCallingUid(), userId,
11443                true /* requireFullPermission */, true /* checkShell */,
11444                "setPackagesSuspended for user " + userId);
11445
11446        if (ArrayUtils.isEmpty(packageNames)) {
11447            return packageNames;
11448        }
11449
11450        // List of package names for whom the suspended state has changed.
11451        List<String> changedPackages = new ArrayList<>(packageNames.length);
11452        // List of package names for whom the suspended state is not set as requested in this
11453        // method.
11454        List<String> unactionedPackages = new ArrayList<>(packageNames.length);
11455        for (int i = 0; i < packageNames.length; i++) {
11456            String packageName = packageNames[i];
11457            long callingId = Binder.clearCallingIdentity();
11458            try {
11459                boolean changed = false;
11460                final int appId;
11461                synchronized (mPackages) {
11462                    final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
11463                    if (pkgSetting == null) {
11464                        Slog.w(TAG, "Could not find package setting for package \"" + packageName
11465                                + "\". Skipping suspending/un-suspending.");
11466                        unactionedPackages.add(packageName);
11467                        continue;
11468                    }
11469                    appId = pkgSetting.appId;
11470                    if (pkgSetting.getSuspended(userId) != suspended) {
11471                        if (!canSuspendPackageForUserLocked(packageName, userId)) {
11472                            unactionedPackages.add(packageName);
11473                            continue;
11474                        }
11475                        pkgSetting.setSuspended(suspended, userId);
11476                        mSettings.writePackageRestrictionsLPr(userId);
11477                        changed = true;
11478                        changedPackages.add(packageName);
11479                    }
11480                }
11481
11482                if (changed && suspended) {
11483                    killApplication(packageName, UserHandle.getUid(userId, appId),
11484                            "suspending package");
11485                }
11486            } finally {
11487                Binder.restoreCallingIdentity(callingId);
11488            }
11489        }
11490
11491        if (!changedPackages.isEmpty()) {
11492            sendPackagesSuspendedForUser(changedPackages.toArray(
11493                    new String[changedPackages.size()]), userId, suspended);
11494        }
11495
11496        return unactionedPackages.toArray(new String[unactionedPackages.size()]);
11497    }
11498
11499    @Override
11500    public boolean isPackageSuspendedForUser(String packageName, int userId) {
11501        enforceCrossUserPermission(Binder.getCallingUid(), userId,
11502                true /* requireFullPermission */, false /* checkShell */,
11503                "isPackageSuspendedForUser for user " + userId);
11504        synchronized (mPackages) {
11505            final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
11506            if (pkgSetting == null) {
11507                throw new IllegalArgumentException("Unknown target package: " + packageName);
11508            }
11509            return pkgSetting.getSuspended(userId);
11510        }
11511    }
11512
11513    /**
11514     * TODO: cache and disallow blocking the active dialer.
11515     *
11516     * @see also DefaultPermissionGrantPolicy#grantDefaultSystemHandlerPermissions
11517     */
11518    private boolean canSuspendPackageForUserLocked(String packageName, int userId) {
11519        if (isPackageDeviceAdmin(packageName, userId)) {
11520            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
11521                    + "\": has an active device admin");
11522            return false;
11523        }
11524
11525        String activeLauncherPackageName = getActiveLauncherPackageName(userId);
11526        if (packageName.equals(activeLauncherPackageName)) {
11527            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
11528                    + "\": contains the active launcher");
11529            return false;
11530        }
11531
11532        if (packageName.equals(mRequiredInstallerPackage)) {
11533            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
11534                    + "\": required for package installation");
11535            return false;
11536        }
11537
11538        if (packageName.equals(mRequiredVerifierPackage)) {
11539            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
11540                    + "\": required for package verification");
11541            return false;
11542        }
11543
11544        final PackageParser.Package pkg = mPackages.get(packageName);
11545        if (pkg != null && isPrivilegedApp(pkg)) {
11546            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
11547                    + "\": is a privileged app");
11548            return false;
11549        }
11550
11551        return true;
11552    }
11553
11554    private String getActiveLauncherPackageName(int userId) {
11555        Intent intent = new Intent(Intent.ACTION_MAIN);
11556        intent.addCategory(Intent.CATEGORY_HOME);
11557        ResolveInfo resolveInfo = resolveIntent(
11558                intent,
11559                intent.resolveTypeIfNeeded(mContext.getContentResolver()),
11560                PackageManager.MATCH_DEFAULT_ONLY,
11561                userId);
11562
11563        return resolveInfo == null ? null : resolveInfo.activityInfo.packageName;
11564    }
11565
11566    @Override
11567    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
11568        mContext.enforceCallingOrSelfPermission(
11569                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
11570                "Only package verification agents can verify applications");
11571
11572        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
11573        final PackageVerificationResponse response = new PackageVerificationResponse(
11574                verificationCode, Binder.getCallingUid());
11575        msg.arg1 = id;
11576        msg.obj = response;
11577        mHandler.sendMessage(msg);
11578    }
11579
11580    @Override
11581    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
11582            long millisecondsToDelay) {
11583        mContext.enforceCallingOrSelfPermission(
11584                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
11585                "Only package verification agents can extend verification timeouts");
11586
11587        final PackageVerificationState state = mPendingVerification.get(id);
11588        final PackageVerificationResponse response = new PackageVerificationResponse(
11589                verificationCodeAtTimeout, Binder.getCallingUid());
11590
11591        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
11592            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
11593        }
11594        if (millisecondsToDelay < 0) {
11595            millisecondsToDelay = 0;
11596        }
11597        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
11598                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
11599            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
11600        }
11601
11602        if ((state != null) && !state.timeoutExtended()) {
11603            state.extendTimeout();
11604
11605            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
11606            msg.arg1 = id;
11607            msg.obj = response;
11608            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
11609        }
11610    }
11611
11612    private void broadcastPackageVerified(int verificationId, Uri packageUri,
11613            int verificationCode, UserHandle user) {
11614        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
11615        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
11616        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
11617        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
11618        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
11619
11620        mContext.sendBroadcastAsUser(intent, user,
11621                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
11622    }
11623
11624    private ComponentName matchComponentForVerifier(String packageName,
11625            List<ResolveInfo> receivers) {
11626        ActivityInfo targetReceiver = null;
11627
11628        final int NR = receivers.size();
11629        for (int i = 0; i < NR; i++) {
11630            final ResolveInfo info = receivers.get(i);
11631            if (info.activityInfo == null) {
11632                continue;
11633            }
11634
11635            if (packageName.equals(info.activityInfo.packageName)) {
11636                targetReceiver = info.activityInfo;
11637                break;
11638            }
11639        }
11640
11641        if (targetReceiver == null) {
11642            return null;
11643        }
11644
11645        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
11646    }
11647
11648    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
11649            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
11650        if (pkgInfo.verifiers.length == 0) {
11651            return null;
11652        }
11653
11654        final int N = pkgInfo.verifiers.length;
11655        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
11656        for (int i = 0; i < N; i++) {
11657            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
11658
11659            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
11660                    receivers);
11661            if (comp == null) {
11662                continue;
11663            }
11664
11665            final int verifierUid = getUidForVerifier(verifierInfo);
11666            if (verifierUid == -1) {
11667                continue;
11668            }
11669
11670            if (DEBUG_VERIFY) {
11671                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
11672                        + " with the correct signature");
11673            }
11674            sufficientVerifiers.add(comp);
11675            verificationState.addSufficientVerifier(verifierUid);
11676        }
11677
11678        return sufficientVerifiers;
11679    }
11680
11681    private int getUidForVerifier(VerifierInfo verifierInfo) {
11682        synchronized (mPackages) {
11683            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
11684            if (pkg == null) {
11685                return -1;
11686            } else if (pkg.mSignatures.length != 1) {
11687                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
11688                        + " has more than one signature; ignoring");
11689                return -1;
11690            }
11691
11692            /*
11693             * If the public key of the package's signature does not match
11694             * our expected public key, then this is a different package and
11695             * we should skip.
11696             */
11697
11698            final byte[] expectedPublicKey;
11699            try {
11700                final Signature verifierSig = pkg.mSignatures[0];
11701                final PublicKey publicKey = verifierSig.getPublicKey();
11702                expectedPublicKey = publicKey.getEncoded();
11703            } catch (CertificateException e) {
11704                return -1;
11705            }
11706
11707            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
11708
11709            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
11710                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
11711                        + " does not have the expected public key; ignoring");
11712                return -1;
11713            }
11714
11715            return pkg.applicationInfo.uid;
11716        }
11717    }
11718
11719    @Override
11720    public void finishPackageInstall(int token) {
11721        enforceSystemOrRoot("Only the system is allowed to finish installs");
11722
11723        if (DEBUG_INSTALL) {
11724            Slog.v(TAG, "BM finishing package install for " + token);
11725        }
11726        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
11727
11728        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
11729        mHandler.sendMessage(msg);
11730    }
11731
11732    /**
11733     * Get the verification agent timeout.
11734     *
11735     * @return verification timeout in milliseconds
11736     */
11737    private long getVerificationTimeout() {
11738        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
11739                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
11740                DEFAULT_VERIFICATION_TIMEOUT);
11741    }
11742
11743    /**
11744     * Get the default verification agent response code.
11745     *
11746     * @return default verification response code
11747     */
11748    private int getDefaultVerificationResponse() {
11749        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
11750                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
11751                DEFAULT_VERIFICATION_RESPONSE);
11752    }
11753
11754    /**
11755     * Check whether or not package verification has been enabled.
11756     *
11757     * @return true if verification should be performed
11758     */
11759    private boolean isVerificationEnabled(int userId, int installFlags) {
11760        if (!DEFAULT_VERIFY_ENABLE) {
11761            return false;
11762        }
11763        // Ephemeral apps don't get the full verification treatment
11764        if ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) {
11765            if (DEBUG_EPHEMERAL) {
11766                Slog.d(TAG, "INSTALL_EPHEMERAL so skipping verification");
11767            }
11768            return false;
11769        }
11770
11771        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
11772
11773        // Check if installing from ADB
11774        if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
11775            // Do not run verification in a test harness environment
11776            if (ActivityManager.isRunningInTestHarness()) {
11777                return false;
11778            }
11779            if (ensureVerifyAppsEnabled) {
11780                return true;
11781            }
11782            // Check if the developer does not want package verification for ADB installs
11783            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
11784                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
11785                return false;
11786            }
11787        }
11788
11789        if (ensureVerifyAppsEnabled) {
11790            return true;
11791        }
11792
11793        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
11794                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
11795    }
11796
11797    @Override
11798    public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains)
11799            throws RemoteException {
11800        mContext.enforceCallingOrSelfPermission(
11801                Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
11802                "Only intentfilter verification agents can verify applications");
11803
11804        final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED);
11805        final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse(
11806                Binder.getCallingUid(), verificationCode, failedDomains);
11807        msg.arg1 = id;
11808        msg.obj = response;
11809        mHandler.sendMessage(msg);
11810    }
11811
11812    @Override
11813    public int getIntentVerificationStatus(String packageName, int userId) {
11814        synchronized (mPackages) {
11815            return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
11816        }
11817    }
11818
11819    @Override
11820    public boolean updateIntentVerificationStatus(String packageName, int status, int userId) {
11821        mContext.enforceCallingOrSelfPermission(
11822                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
11823
11824        boolean result = false;
11825        synchronized (mPackages) {
11826            result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId);
11827        }
11828        if (result) {
11829            scheduleWritePackageRestrictionsLocked(userId);
11830        }
11831        return result;
11832    }
11833
11834    @Override
11835    public @NonNull ParceledListSlice<IntentFilterVerificationInfo> getIntentFilterVerifications(
11836            String packageName) {
11837        synchronized (mPackages) {
11838            return new ParceledListSlice<>(mSettings.getIntentFilterVerificationsLPr(packageName));
11839        }
11840    }
11841
11842    @Override
11843    public @NonNull ParceledListSlice<IntentFilter> getAllIntentFilters(String packageName) {
11844        if (TextUtils.isEmpty(packageName)) {
11845            return ParceledListSlice.emptyList();
11846        }
11847        synchronized (mPackages) {
11848            PackageParser.Package pkg = mPackages.get(packageName);
11849            if (pkg == null || pkg.activities == null) {
11850                return ParceledListSlice.emptyList();
11851            }
11852            final int count = pkg.activities.size();
11853            ArrayList<IntentFilter> result = new ArrayList<>();
11854            for (int n=0; n<count; n++) {
11855                PackageParser.Activity activity = pkg.activities.get(n);
11856                if (activity.intents != null && activity.intents.size() > 0) {
11857                    result.addAll(activity.intents);
11858                }
11859            }
11860            return new ParceledListSlice<>(result);
11861        }
11862    }
11863
11864    @Override
11865    public boolean setDefaultBrowserPackageName(String packageName, int userId) {
11866        mContext.enforceCallingOrSelfPermission(
11867                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
11868
11869        synchronized (mPackages) {
11870            boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId);
11871            if (packageName != null) {
11872                result |= updateIntentVerificationStatus(packageName,
11873                        PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS,
11874                        userId);
11875                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr(
11876                        packageName, userId);
11877            }
11878            return result;
11879        }
11880    }
11881
11882    @Override
11883    public String getDefaultBrowserPackageName(int userId) {
11884        synchronized (mPackages) {
11885            return mSettings.getDefaultBrowserPackageNameLPw(userId);
11886        }
11887    }
11888
11889    /**
11890     * Get the "allow unknown sources" setting.
11891     *
11892     * @return the current "allow unknown sources" setting
11893     */
11894    private int getUnknownSourcesSettings() {
11895        return android.provider.Settings.Secure.getInt(mContext.getContentResolver(),
11896                android.provider.Settings.Secure.INSTALL_NON_MARKET_APPS,
11897                -1);
11898    }
11899
11900    @Override
11901    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
11902        final int uid = Binder.getCallingUid();
11903        // writer
11904        synchronized (mPackages) {
11905            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
11906            if (targetPackageSetting == null) {
11907                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
11908            }
11909
11910            PackageSetting installerPackageSetting;
11911            if (installerPackageName != null) {
11912                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
11913                if (installerPackageSetting == null) {
11914                    throw new IllegalArgumentException("Unknown installer package: "
11915                            + installerPackageName);
11916                }
11917            } else {
11918                installerPackageSetting = null;
11919            }
11920
11921            Signature[] callerSignature;
11922            Object obj = mSettings.getUserIdLPr(uid);
11923            if (obj != null) {
11924                if (obj instanceof SharedUserSetting) {
11925                    callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
11926                } else if (obj instanceof PackageSetting) {
11927                    callerSignature = ((PackageSetting)obj).signatures.mSignatures;
11928                } else {
11929                    throw new SecurityException("Bad object " + obj + " for uid " + uid);
11930                }
11931            } else {
11932                throw new SecurityException("Unknown calling UID: " + uid);
11933            }
11934
11935            // Verify: can't set installerPackageName to a package that is
11936            // not signed with the same cert as the caller.
11937            if (installerPackageSetting != null) {
11938                if (compareSignatures(callerSignature,
11939                        installerPackageSetting.signatures.mSignatures)
11940                        != PackageManager.SIGNATURE_MATCH) {
11941                    throw new SecurityException(
11942                            "Caller does not have same cert as new installer package "
11943                            + installerPackageName);
11944                }
11945            }
11946
11947            // Verify: if target already has an installer package, it must
11948            // be signed with the same cert as the caller.
11949            if (targetPackageSetting.installerPackageName != null) {
11950                PackageSetting setting = mSettings.mPackages.get(
11951                        targetPackageSetting.installerPackageName);
11952                // If the currently set package isn't valid, then it's always
11953                // okay to change it.
11954                if (setting != null) {
11955                    if (compareSignatures(callerSignature,
11956                            setting.signatures.mSignatures)
11957                            != PackageManager.SIGNATURE_MATCH) {
11958                        throw new SecurityException(
11959                                "Caller does not have same cert as old installer package "
11960                                + targetPackageSetting.installerPackageName);
11961                    }
11962                }
11963            }
11964
11965            // Okay!
11966            targetPackageSetting.installerPackageName = installerPackageName;
11967            if (installerPackageName != null) {
11968                mSettings.mInstallerPackages.add(installerPackageName);
11969            }
11970            scheduleWriteSettingsLocked();
11971        }
11972    }
11973
11974    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
11975        // Queue up an async operation since the package installation may take a little while.
11976        mHandler.post(new Runnable() {
11977            public void run() {
11978                mHandler.removeCallbacks(this);
11979                 // Result object to be returned
11980                PackageInstalledInfo res = new PackageInstalledInfo();
11981                res.setReturnCode(currentStatus);
11982                res.uid = -1;
11983                res.pkg = null;
11984                res.removedInfo = null;
11985                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
11986                    args.doPreInstall(res.returnCode);
11987                    synchronized (mInstallLock) {
11988                        installPackageTracedLI(args, res);
11989                    }
11990                    args.doPostInstall(res.returnCode, res.uid);
11991                }
11992
11993                // A restore should be performed at this point if (a) the install
11994                // succeeded, (b) the operation is not an update, and (c) the new
11995                // package has not opted out of backup participation.
11996                final boolean update = res.removedInfo != null
11997                        && res.removedInfo.removedPackage != null;
11998                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
11999                boolean doRestore = !update
12000                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
12001
12002                // Set up the post-install work request bookkeeping.  This will be used
12003                // and cleaned up by the post-install event handling regardless of whether
12004                // there's a restore pass performed.  Token values are >= 1.
12005                int token;
12006                if (mNextInstallToken < 0) mNextInstallToken = 1;
12007                token = mNextInstallToken++;
12008
12009                PostInstallData data = new PostInstallData(args, res);
12010                mRunningInstalls.put(token, data);
12011                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
12012
12013                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
12014                    // Pass responsibility to the Backup Manager.  It will perform a
12015                    // restore if appropriate, then pass responsibility back to the
12016                    // Package Manager to run the post-install observer callbacks
12017                    // and broadcasts.
12018                    IBackupManager bm = IBackupManager.Stub.asInterface(
12019                            ServiceManager.getService(Context.BACKUP_SERVICE));
12020                    if (bm != null) {
12021                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
12022                                + " to BM for possible restore");
12023                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
12024                        try {
12025                            // TODO: http://b/22388012
12026                            if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) {
12027                                bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
12028                            } else {
12029                                doRestore = false;
12030                            }
12031                        } catch (RemoteException e) {
12032                            // can't happen; the backup manager is local
12033                        } catch (Exception e) {
12034                            Slog.e(TAG, "Exception trying to enqueue restore", e);
12035                            doRestore = false;
12036                        }
12037                    } else {
12038                        Slog.e(TAG, "Backup Manager not found!");
12039                        doRestore = false;
12040                    }
12041                }
12042
12043                if (!doRestore) {
12044                    // No restore possible, or the Backup Manager was mysteriously not
12045                    // available -- just fire the post-install work request directly.
12046                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
12047
12048                    Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token);
12049
12050                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
12051                    mHandler.sendMessage(msg);
12052                }
12053            }
12054        });
12055    }
12056
12057    private abstract class HandlerParams {
12058        private static final int MAX_RETRIES = 4;
12059
12060        /**
12061         * Number of times startCopy() has been attempted and had a non-fatal
12062         * error.
12063         */
12064        private int mRetries = 0;
12065
12066        /** User handle for the user requesting the information or installation. */
12067        private final UserHandle mUser;
12068        String traceMethod;
12069        int traceCookie;
12070
12071        HandlerParams(UserHandle user) {
12072            mUser = user;
12073        }
12074
12075        UserHandle getUser() {
12076            return mUser;
12077        }
12078
12079        HandlerParams setTraceMethod(String traceMethod) {
12080            this.traceMethod = traceMethod;
12081            return this;
12082        }
12083
12084        HandlerParams setTraceCookie(int traceCookie) {
12085            this.traceCookie = traceCookie;
12086            return this;
12087        }
12088
12089        final boolean startCopy() {
12090            boolean res;
12091            try {
12092                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
12093
12094                if (++mRetries > MAX_RETRIES) {
12095                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
12096                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
12097                    handleServiceError();
12098                    return false;
12099                } else {
12100                    handleStartCopy();
12101                    res = true;
12102                }
12103            } catch (RemoteException e) {
12104                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
12105                mHandler.sendEmptyMessage(MCS_RECONNECT);
12106                res = false;
12107            }
12108            handleReturnCode();
12109            return res;
12110        }
12111
12112        final void serviceError() {
12113            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
12114            handleServiceError();
12115            handleReturnCode();
12116        }
12117
12118        abstract void handleStartCopy() throws RemoteException;
12119        abstract void handleServiceError();
12120        abstract void handleReturnCode();
12121    }
12122
12123    class MeasureParams extends HandlerParams {
12124        private final PackageStats mStats;
12125        private boolean mSuccess;
12126
12127        private final IPackageStatsObserver mObserver;
12128
12129        public MeasureParams(PackageStats stats, IPackageStatsObserver observer) {
12130            super(new UserHandle(stats.userHandle));
12131            mObserver = observer;
12132            mStats = stats;
12133        }
12134
12135        @Override
12136        public String toString() {
12137            return "MeasureParams{"
12138                + Integer.toHexString(System.identityHashCode(this))
12139                + " " + mStats.packageName + "}";
12140        }
12141
12142        @Override
12143        void handleStartCopy() throws RemoteException {
12144            synchronized (mInstallLock) {
12145                mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats);
12146            }
12147
12148            if (mSuccess) {
12149                final boolean mounted;
12150                if (Environment.isExternalStorageEmulated()) {
12151                    mounted = true;
12152                } else {
12153                    final String status = Environment.getExternalStorageState();
12154                    mounted = (Environment.MEDIA_MOUNTED.equals(status)
12155                            || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status));
12156                }
12157
12158                if (mounted) {
12159                    final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle);
12160
12161                    mStats.externalCacheSize = calculateDirectorySize(mContainerService,
12162                            userEnv.buildExternalStorageAppCacheDirs(mStats.packageName));
12163
12164                    mStats.externalDataSize = calculateDirectorySize(mContainerService,
12165                            userEnv.buildExternalStorageAppDataDirs(mStats.packageName));
12166
12167                    // Always subtract cache size, since it's a subdirectory
12168                    mStats.externalDataSize -= mStats.externalCacheSize;
12169
12170                    mStats.externalMediaSize = calculateDirectorySize(mContainerService,
12171                            userEnv.buildExternalStorageAppMediaDirs(mStats.packageName));
12172
12173                    mStats.externalObbSize = calculateDirectorySize(mContainerService,
12174                            userEnv.buildExternalStorageAppObbDirs(mStats.packageName));
12175                }
12176            }
12177        }
12178
12179        @Override
12180        void handleReturnCode() {
12181            if (mObserver != null) {
12182                try {
12183                    mObserver.onGetStatsCompleted(mStats, mSuccess);
12184                } catch (RemoteException e) {
12185                    Slog.i(TAG, "Observer no longer exists.");
12186                }
12187            }
12188        }
12189
12190        @Override
12191        void handleServiceError() {
12192            Slog.e(TAG, "Could not measure application " + mStats.packageName
12193                            + " external storage");
12194        }
12195    }
12196
12197    private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths)
12198            throws RemoteException {
12199        long result = 0;
12200        for (File path : paths) {
12201            result += mcs.calculateDirectorySize(path.getAbsolutePath());
12202        }
12203        return result;
12204    }
12205
12206    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
12207        for (File path : paths) {
12208            try {
12209                mcs.clearDirectory(path.getAbsolutePath());
12210            } catch (RemoteException e) {
12211            }
12212        }
12213    }
12214
12215    static class OriginInfo {
12216        /**
12217         * Location where install is coming from, before it has been
12218         * copied/renamed into place. This could be a single monolithic APK
12219         * file, or a cluster directory. This location may be untrusted.
12220         */
12221        final File file;
12222        final String cid;
12223
12224        /**
12225         * Flag indicating that {@link #file} or {@link #cid} has already been
12226         * staged, meaning downstream users don't need to defensively copy the
12227         * contents.
12228         */
12229        final boolean staged;
12230
12231        /**
12232         * Flag indicating that {@link #file} or {@link #cid} is an already
12233         * installed app that is being moved.
12234         */
12235        final boolean existing;
12236
12237        final String resolvedPath;
12238        final File resolvedFile;
12239
12240        static OriginInfo fromNothing() {
12241            return new OriginInfo(null, null, false, false);
12242        }
12243
12244        static OriginInfo fromUntrustedFile(File file) {
12245            return new OriginInfo(file, null, false, false);
12246        }
12247
12248        static OriginInfo fromExistingFile(File file) {
12249            return new OriginInfo(file, null, false, true);
12250        }
12251
12252        static OriginInfo fromStagedFile(File file) {
12253            return new OriginInfo(file, null, true, false);
12254        }
12255
12256        static OriginInfo fromStagedContainer(String cid) {
12257            return new OriginInfo(null, cid, true, false);
12258        }
12259
12260        private OriginInfo(File file, String cid, boolean staged, boolean existing) {
12261            this.file = file;
12262            this.cid = cid;
12263            this.staged = staged;
12264            this.existing = existing;
12265
12266            if (cid != null) {
12267                resolvedPath = PackageHelper.getSdDir(cid);
12268                resolvedFile = new File(resolvedPath);
12269            } else if (file != null) {
12270                resolvedPath = file.getAbsolutePath();
12271                resolvedFile = file;
12272            } else {
12273                resolvedPath = null;
12274                resolvedFile = null;
12275            }
12276        }
12277    }
12278
12279    static class MoveInfo {
12280        final int moveId;
12281        final String fromUuid;
12282        final String toUuid;
12283        final String packageName;
12284        final String dataAppName;
12285        final int appId;
12286        final String seinfo;
12287        final int targetSdkVersion;
12288
12289        public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName,
12290                String dataAppName, int appId, String seinfo, int targetSdkVersion) {
12291            this.moveId = moveId;
12292            this.fromUuid = fromUuid;
12293            this.toUuid = toUuid;
12294            this.packageName = packageName;
12295            this.dataAppName = dataAppName;
12296            this.appId = appId;
12297            this.seinfo = seinfo;
12298            this.targetSdkVersion = targetSdkVersion;
12299        }
12300    }
12301
12302    static class VerificationInfo {
12303        /** A constant used to indicate that a uid value is not present. */
12304        public static final int NO_UID = -1;
12305
12306        /** URI referencing where the package was downloaded from. */
12307        final Uri originatingUri;
12308
12309        /** HTTP referrer URI associated with the originatingURI. */
12310        final Uri referrer;
12311
12312        /** UID of the application that the install request originated from. */
12313        final int originatingUid;
12314
12315        /** UID of application requesting the install */
12316        final int installerUid;
12317
12318        VerificationInfo(Uri originatingUri, Uri referrer, int originatingUid, int installerUid) {
12319            this.originatingUri = originatingUri;
12320            this.referrer = referrer;
12321            this.originatingUid = originatingUid;
12322            this.installerUid = installerUid;
12323        }
12324    }
12325
12326    class InstallParams extends HandlerParams {
12327        final OriginInfo origin;
12328        final MoveInfo move;
12329        final IPackageInstallObserver2 observer;
12330        int installFlags;
12331        final String installerPackageName;
12332        final String volumeUuid;
12333        private InstallArgs mArgs;
12334        private int mRet;
12335        final String packageAbiOverride;
12336        final String[] grantedRuntimePermissions;
12337        final VerificationInfo verificationInfo;
12338        final Certificate[][] certificates;
12339
12340        InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
12341                int installFlags, String installerPackageName, String volumeUuid,
12342                VerificationInfo verificationInfo, UserHandle user, String packageAbiOverride,
12343                String[] grantedPermissions, Certificate[][] certificates) {
12344            super(user);
12345            this.origin = origin;
12346            this.move = move;
12347            this.observer = observer;
12348            this.installFlags = installFlags;
12349            this.installerPackageName = installerPackageName;
12350            this.volumeUuid = volumeUuid;
12351            this.verificationInfo = verificationInfo;
12352            this.packageAbiOverride = packageAbiOverride;
12353            this.grantedRuntimePermissions = grantedPermissions;
12354            this.certificates = certificates;
12355        }
12356
12357        @Override
12358        public String toString() {
12359            return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
12360                    + " file=" + origin.file + " cid=" + origin.cid + "}";
12361        }
12362
12363        private int installLocationPolicy(PackageInfoLite pkgLite) {
12364            String packageName = pkgLite.packageName;
12365            int installLocation = pkgLite.installLocation;
12366            boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
12367            // reader
12368            synchronized (mPackages) {
12369                // Currently installed package which the new package is attempting to replace or
12370                // null if no such package is installed.
12371                PackageParser.Package installedPkg = mPackages.get(packageName);
12372                // Package which currently owns the data which the new package will own if installed.
12373                // If an app is unstalled while keeping data (e.g., adb uninstall -k), installedPkg
12374                // will be null whereas dataOwnerPkg will contain information about the package
12375                // which was uninstalled while keeping its data.
12376                PackageParser.Package dataOwnerPkg = installedPkg;
12377                if (dataOwnerPkg  == null) {
12378                    PackageSetting ps = mSettings.mPackages.get(packageName);
12379                    if (ps != null) {
12380                        dataOwnerPkg = ps.pkg;
12381                    }
12382                }
12383
12384                if (dataOwnerPkg != null) {
12385                    // If installed, the package will get access to data left on the device by its
12386                    // predecessor. As a security measure, this is permited only if this is not a
12387                    // version downgrade or if the predecessor package is marked as debuggable and
12388                    // a downgrade is explicitly requested.
12389                    //
12390                    // On debuggable platform builds, downgrades are permitted even for
12391                    // non-debuggable packages to make testing easier. Debuggable platform builds do
12392                    // not offer security guarantees and thus it's OK to disable some security
12393                    // mechanisms to make debugging/testing easier on those builds. However, even on
12394                    // debuggable builds downgrades of packages are permitted only if requested via
12395                    // installFlags. This is because we aim to keep the behavior of debuggable
12396                    // platform builds as close as possible to the behavior of non-debuggable
12397                    // platform builds.
12398                    final boolean downgradeRequested =
12399                            (installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) != 0;
12400                    final boolean packageDebuggable =
12401                                (dataOwnerPkg.applicationInfo.flags
12402                                        & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
12403                    final boolean downgradePermitted =
12404                            (downgradeRequested) && ((Build.IS_DEBUGGABLE) || (packageDebuggable));
12405                    if (!downgradePermitted) {
12406                        try {
12407                            checkDowngrade(dataOwnerPkg, pkgLite);
12408                        } catch (PackageManagerException e) {
12409                            Slog.w(TAG, "Downgrade detected: " + e.getMessage());
12410                            return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
12411                        }
12412                    }
12413                }
12414
12415                if (installedPkg != null) {
12416                    if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
12417                        // Check for updated system application.
12418                        if ((installedPkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
12419                            if (onSd) {
12420                                Slog.w(TAG, "Cannot install update to system app on sdcard");
12421                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
12422                            }
12423                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
12424                        } else {
12425                            if (onSd) {
12426                                // Install flag overrides everything.
12427                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
12428                            }
12429                            // If current upgrade specifies particular preference
12430                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
12431                                // Application explicitly specified internal.
12432                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
12433                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
12434                                // App explictly prefers external. Let policy decide
12435                            } else {
12436                                // Prefer previous location
12437                                if (isExternal(installedPkg)) {
12438                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
12439                                }
12440                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
12441                            }
12442                        }
12443                    } else {
12444                        // Invalid install. Return error code
12445                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
12446                    }
12447                }
12448            }
12449            // All the special cases have been taken care of.
12450            // Return result based on recommended install location.
12451            if (onSd) {
12452                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
12453            }
12454            return pkgLite.recommendedInstallLocation;
12455        }
12456
12457        /*
12458         * Invoke remote method to get package information and install
12459         * location values. Override install location based on default
12460         * policy if needed and then create install arguments based
12461         * on the install location.
12462         */
12463        public void handleStartCopy() throws RemoteException {
12464            int ret = PackageManager.INSTALL_SUCCEEDED;
12465
12466            // If we're already staged, we've firmly committed to an install location
12467            if (origin.staged) {
12468                if (origin.file != null) {
12469                    installFlags |= PackageManager.INSTALL_INTERNAL;
12470                    installFlags &= ~PackageManager.INSTALL_EXTERNAL;
12471                } else if (origin.cid != null) {
12472                    installFlags |= PackageManager.INSTALL_EXTERNAL;
12473                    installFlags &= ~PackageManager.INSTALL_INTERNAL;
12474                } else {
12475                    throw new IllegalStateException("Invalid stage location");
12476                }
12477            }
12478
12479            final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
12480            final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
12481            final boolean ephemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0;
12482            PackageInfoLite pkgLite = null;
12483
12484            if (onInt && onSd) {
12485                // Check if both bits are set.
12486                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
12487                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
12488            } else if (onSd && ephemeral) {
12489                Slog.w(TAG,  "Conflicting flags specified for installing ephemeral on external");
12490                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
12491            } else {
12492                pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
12493                        packageAbiOverride);
12494
12495                if (DEBUG_EPHEMERAL && ephemeral) {
12496                    Slog.v(TAG, "pkgLite for install: " + pkgLite);
12497                }
12498
12499                /*
12500                 * If we have too little free space, try to free cache
12501                 * before giving up.
12502                 */
12503                if (!origin.staged && pkgLite.recommendedInstallLocation
12504                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
12505                    // TODO: focus freeing disk space on the target device
12506                    final StorageManager storage = StorageManager.from(mContext);
12507                    final long lowThreshold = storage.getStorageLowBytes(
12508                            Environment.getDataDirectory());
12509
12510                    final long sizeBytes = mContainerService.calculateInstalledSize(
12511                            origin.resolvedPath, isForwardLocked(), packageAbiOverride);
12512
12513                    try {
12514                        mInstaller.freeCache(null, sizeBytes + lowThreshold);
12515                        pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
12516                                installFlags, packageAbiOverride);
12517                    } catch (InstallerException e) {
12518                        Slog.w(TAG, "Failed to free cache", e);
12519                    }
12520
12521                    /*
12522                     * The cache free must have deleted the file we
12523                     * downloaded to install.
12524                     *
12525                     * TODO: fix the "freeCache" call to not delete
12526                     *       the file we care about.
12527                     */
12528                    if (pkgLite.recommendedInstallLocation
12529                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
12530                        pkgLite.recommendedInstallLocation
12531                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
12532                    }
12533                }
12534            }
12535
12536            if (ret == PackageManager.INSTALL_SUCCEEDED) {
12537                int loc = pkgLite.recommendedInstallLocation;
12538                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
12539                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
12540                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
12541                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
12542                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
12543                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
12544                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
12545                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
12546                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
12547                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
12548                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
12549                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
12550                } else {
12551                    // Override with defaults if needed.
12552                    loc = installLocationPolicy(pkgLite);
12553                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
12554                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
12555                    } else if (!onSd && !onInt) {
12556                        // Override install location with flags
12557                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
12558                            // Set the flag to install on external media.
12559                            installFlags |= PackageManager.INSTALL_EXTERNAL;
12560                            installFlags &= ~PackageManager.INSTALL_INTERNAL;
12561                        } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) {
12562                            if (DEBUG_EPHEMERAL) {
12563                                Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag");
12564                            }
12565                            installFlags |= PackageManager.INSTALL_EPHEMERAL;
12566                            installFlags &= ~(PackageManager.INSTALL_EXTERNAL
12567                                    |PackageManager.INSTALL_INTERNAL);
12568                        } else {
12569                            // Make sure the flag for installing on external
12570                            // media is unset
12571                            installFlags |= PackageManager.INSTALL_INTERNAL;
12572                            installFlags &= ~PackageManager.INSTALL_EXTERNAL;
12573                        }
12574                    }
12575                }
12576            }
12577
12578            final InstallArgs args = createInstallArgs(this);
12579            mArgs = args;
12580
12581            if (ret == PackageManager.INSTALL_SUCCEEDED) {
12582                // TODO: http://b/22976637
12583                // Apps installed for "all" users use the device owner to verify the app
12584                UserHandle verifierUser = getUser();
12585                if (verifierUser == UserHandle.ALL) {
12586                    verifierUser = UserHandle.SYSTEM;
12587                }
12588
12589                /*
12590                 * Determine if we have any installed package verifiers. If we
12591                 * do, then we'll defer to them to verify the packages.
12592                 */
12593                final int requiredUid = mRequiredVerifierPackage == null ? -1
12594                        : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
12595                                verifierUser.getIdentifier());
12596                if (!origin.existing && requiredUid != -1
12597                        && isVerificationEnabled(verifierUser.getIdentifier(), installFlags)) {
12598                    final Intent verification = new Intent(
12599                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
12600                    verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
12601                    verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
12602                            PACKAGE_MIME_TYPE);
12603                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
12604
12605                    // Query all live verifiers based on current user state
12606                    final List<ResolveInfo> receivers = queryIntentReceiversInternal(verification,
12607                            PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier());
12608
12609                    if (DEBUG_VERIFY) {
12610                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
12611                                + verification.toString() + " with " + pkgLite.verifiers.length
12612                                + " optional verifiers");
12613                    }
12614
12615                    final int verificationId = mPendingVerificationToken++;
12616
12617                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
12618
12619                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
12620                            installerPackageName);
12621
12622                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
12623                            installFlags);
12624
12625                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
12626                            pkgLite.packageName);
12627
12628                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
12629                            pkgLite.versionCode);
12630
12631                    if (verificationInfo != null) {
12632                        if (verificationInfo.originatingUri != null) {
12633                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
12634                                    verificationInfo.originatingUri);
12635                        }
12636                        if (verificationInfo.referrer != null) {
12637                            verification.putExtra(Intent.EXTRA_REFERRER,
12638                                    verificationInfo.referrer);
12639                        }
12640                        if (verificationInfo.originatingUid >= 0) {
12641                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
12642                                    verificationInfo.originatingUid);
12643                        }
12644                        if (verificationInfo.installerUid >= 0) {
12645                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
12646                                    verificationInfo.installerUid);
12647                        }
12648                    }
12649
12650                    final PackageVerificationState verificationState = new PackageVerificationState(
12651                            requiredUid, args);
12652
12653                    mPendingVerification.append(verificationId, verificationState);
12654
12655                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
12656                            receivers, verificationState);
12657
12658                    /*
12659                     * If any sufficient verifiers were listed in the package
12660                     * manifest, attempt to ask them.
12661                     */
12662                    if (sufficientVerifiers != null) {
12663                        final int N = sufficientVerifiers.size();
12664                        if (N == 0) {
12665                            Slog.i(TAG, "Additional verifiers required, but none installed.");
12666                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
12667                        } else {
12668                            for (int i = 0; i < N; i++) {
12669                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
12670
12671                                final Intent sufficientIntent = new Intent(verification);
12672                                sufficientIntent.setComponent(verifierComponent);
12673                                mContext.sendBroadcastAsUser(sufficientIntent, verifierUser);
12674                            }
12675                        }
12676                    }
12677
12678                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
12679                            mRequiredVerifierPackage, receivers);
12680                    if (ret == PackageManager.INSTALL_SUCCEEDED
12681                            && mRequiredVerifierPackage != null) {
12682                        Trace.asyncTraceBegin(
12683                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
12684                        /*
12685                         * Send the intent to the required verification agent,
12686                         * but only start the verification timeout after the
12687                         * target BroadcastReceivers have run.
12688                         */
12689                        verification.setComponent(requiredVerifierComponent);
12690                        mContext.sendOrderedBroadcastAsUser(verification, verifierUser,
12691                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
12692                                new BroadcastReceiver() {
12693                                    @Override
12694                                    public void onReceive(Context context, Intent intent) {
12695                                        final Message msg = mHandler
12696                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
12697                                        msg.arg1 = verificationId;
12698                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
12699                                    }
12700                                }, null, 0, null, null);
12701
12702                        /*
12703                         * We don't want the copy to proceed until verification
12704                         * succeeds, so null out this field.
12705                         */
12706                        mArgs = null;
12707                    }
12708                } else {
12709                    /*
12710                     * No package verification is enabled, so immediately start
12711                     * the remote call to initiate copy using temporary file.
12712                     */
12713                    ret = args.copyApk(mContainerService, true);
12714                }
12715            }
12716
12717            mRet = ret;
12718        }
12719
12720        @Override
12721        void handleReturnCode() {
12722            // If mArgs is null, then MCS couldn't be reached. When it
12723            // reconnects, it will try again to install. At that point, this
12724            // will succeed.
12725            if (mArgs != null) {
12726                processPendingInstall(mArgs, mRet);
12727            }
12728        }
12729
12730        @Override
12731        void handleServiceError() {
12732            mArgs = createInstallArgs(this);
12733            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
12734        }
12735
12736        public boolean isForwardLocked() {
12737            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
12738        }
12739    }
12740
12741    /**
12742     * Used during creation of InstallArgs
12743     *
12744     * @param installFlags package installation flags
12745     * @return true if should be installed on external storage
12746     */
12747    private static boolean installOnExternalAsec(int installFlags) {
12748        if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) {
12749            return false;
12750        }
12751        if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
12752            return true;
12753        }
12754        return false;
12755    }
12756
12757    /**
12758     * Used during creation of InstallArgs
12759     *
12760     * @param installFlags package installation flags
12761     * @return true if should be installed as forward locked
12762     */
12763    private static boolean installForwardLocked(int installFlags) {
12764        return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
12765    }
12766
12767    private InstallArgs createInstallArgs(InstallParams params) {
12768        if (params.move != null) {
12769            return new MoveInstallArgs(params);
12770        } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) {
12771            return new AsecInstallArgs(params);
12772        } else {
12773            return new FileInstallArgs(params);
12774        }
12775    }
12776
12777    /**
12778     * Create args that describe an existing installed package. Typically used
12779     * when cleaning up old installs, or used as a move source.
12780     */
12781    private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
12782            String resourcePath, String[] instructionSets) {
12783        final boolean isInAsec;
12784        if (installOnExternalAsec(installFlags)) {
12785            /* Apps on SD card are always in ASEC containers. */
12786            isInAsec = true;
12787        } else if (installForwardLocked(installFlags)
12788                && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) {
12789            /*
12790             * Forward-locked apps are only in ASEC containers if they're the
12791             * new style
12792             */
12793            isInAsec = true;
12794        } else {
12795            isInAsec = false;
12796        }
12797
12798        if (isInAsec) {
12799            return new AsecInstallArgs(codePath, instructionSets,
12800                    installOnExternalAsec(installFlags), installForwardLocked(installFlags));
12801        } else {
12802            return new FileInstallArgs(codePath, resourcePath, instructionSets);
12803        }
12804    }
12805
12806    static abstract class InstallArgs {
12807        /** @see InstallParams#origin */
12808        final OriginInfo origin;
12809        /** @see InstallParams#move */
12810        final MoveInfo move;
12811
12812        final IPackageInstallObserver2 observer;
12813        // Always refers to PackageManager flags only
12814        final int installFlags;
12815        final String installerPackageName;
12816        final String volumeUuid;
12817        final UserHandle user;
12818        final String abiOverride;
12819        final String[] installGrantPermissions;
12820        /** If non-null, drop an async trace when the install completes */
12821        final String traceMethod;
12822        final int traceCookie;
12823        final Certificate[][] certificates;
12824
12825        // The list of instruction sets supported by this app. This is currently
12826        // only used during the rmdex() phase to clean up resources. We can get rid of this
12827        // if we move dex files under the common app path.
12828        /* nullable */ String[] instructionSets;
12829
12830        InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
12831                int installFlags, String installerPackageName, String volumeUuid,
12832                UserHandle user, String[] instructionSets,
12833                String abiOverride, String[] installGrantPermissions,
12834                String traceMethod, int traceCookie, Certificate[][] certificates) {
12835            this.origin = origin;
12836            this.move = move;
12837            this.installFlags = installFlags;
12838            this.observer = observer;
12839            this.installerPackageName = installerPackageName;
12840            this.volumeUuid = volumeUuid;
12841            this.user = user;
12842            this.instructionSets = instructionSets;
12843            this.abiOverride = abiOverride;
12844            this.installGrantPermissions = installGrantPermissions;
12845            this.traceMethod = traceMethod;
12846            this.traceCookie = traceCookie;
12847            this.certificates = certificates;
12848        }
12849
12850        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
12851        abstract int doPreInstall(int status);
12852
12853        /**
12854         * Rename package into final resting place. All paths on the given
12855         * scanned package should be updated to reflect the rename.
12856         */
12857        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
12858        abstract int doPostInstall(int status, int uid);
12859
12860        /** @see PackageSettingBase#codePathString */
12861        abstract String getCodePath();
12862        /** @see PackageSettingBase#resourcePathString */
12863        abstract String getResourcePath();
12864
12865        // Need installer lock especially for dex file removal.
12866        abstract void cleanUpResourcesLI();
12867        abstract boolean doPostDeleteLI(boolean delete);
12868
12869        /**
12870         * Called before the source arguments are copied. This is used mostly
12871         * for MoveParams when it needs to read the source file to put it in the
12872         * destination.
12873         */
12874        int doPreCopy() {
12875            return PackageManager.INSTALL_SUCCEEDED;
12876        }
12877
12878        /**
12879         * Called after the source arguments are copied. This is used mostly for
12880         * MoveParams when it needs to read the source file to put it in the
12881         * destination.
12882         */
12883        int doPostCopy(int uid) {
12884            return PackageManager.INSTALL_SUCCEEDED;
12885        }
12886
12887        protected boolean isFwdLocked() {
12888            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
12889        }
12890
12891        protected boolean isExternalAsec() {
12892            return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
12893        }
12894
12895        protected boolean isEphemeral() {
12896            return (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0;
12897        }
12898
12899        UserHandle getUser() {
12900            return user;
12901        }
12902    }
12903
12904    private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) {
12905        if (!allCodePaths.isEmpty()) {
12906            if (instructionSets == null) {
12907                throw new IllegalStateException("instructionSet == null");
12908            }
12909            String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
12910            for (String codePath : allCodePaths) {
12911                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
12912                    try {
12913                        mInstaller.rmdex(codePath, dexCodeInstructionSet);
12914                    } catch (InstallerException ignored) {
12915                    }
12916                }
12917            }
12918        }
12919    }
12920
12921    /**
12922     * Logic to handle installation of non-ASEC applications, including copying
12923     * and renaming logic.
12924     */
12925    class FileInstallArgs extends InstallArgs {
12926        private File codeFile;
12927        private File resourceFile;
12928
12929        // Example topology:
12930        // /data/app/com.example/base.apk
12931        // /data/app/com.example/split_foo.apk
12932        // /data/app/com.example/lib/arm/libfoo.so
12933        // /data/app/com.example/lib/arm64/libfoo.so
12934        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
12935
12936        /** New install */
12937        FileInstallArgs(InstallParams params) {
12938            super(params.origin, params.move, params.observer, params.installFlags,
12939                    params.installerPackageName, params.volumeUuid,
12940                    params.getUser(), null /*instructionSets*/, params.packageAbiOverride,
12941                    params.grantedRuntimePermissions,
12942                    params.traceMethod, params.traceCookie, params.certificates);
12943            if (isFwdLocked()) {
12944                throw new IllegalArgumentException("Forward locking only supported in ASEC");
12945            }
12946        }
12947
12948        /** Existing install */
12949        FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) {
12950            super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets,
12951                    null, null, null, 0, null /*certificates*/);
12952            this.codeFile = (codePath != null) ? new File(codePath) : null;
12953            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
12954        }
12955
12956        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
12957            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk");
12958            try {
12959                return doCopyApk(imcs, temp);
12960            } finally {
12961                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12962            }
12963        }
12964
12965        private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
12966            if (origin.staged) {
12967                if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy");
12968                codeFile = origin.file;
12969                resourceFile = origin.file;
12970                return PackageManager.INSTALL_SUCCEEDED;
12971            }
12972
12973            try {
12974                final boolean isEphemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0;
12975                final File tempDir =
12976                        mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral);
12977                codeFile = tempDir;
12978                resourceFile = tempDir;
12979            } catch (IOException e) {
12980                Slog.w(TAG, "Failed to create copy file: " + e);
12981                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
12982            }
12983
12984            final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
12985                @Override
12986                public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
12987                    if (!FileUtils.isValidExtFilename(name)) {
12988                        throw new IllegalArgumentException("Invalid filename: " + name);
12989                    }
12990                    try {
12991                        final File file = new File(codeFile, name);
12992                        final FileDescriptor fd = Os.open(file.getAbsolutePath(),
12993                                O_RDWR | O_CREAT, 0644);
12994                        Os.chmod(file.getAbsolutePath(), 0644);
12995                        return new ParcelFileDescriptor(fd);
12996                    } catch (ErrnoException e) {
12997                        throw new RemoteException("Failed to open: " + e.getMessage());
12998                    }
12999                }
13000            };
13001
13002            int ret = PackageManager.INSTALL_SUCCEEDED;
13003            ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
13004            if (ret != PackageManager.INSTALL_SUCCEEDED) {
13005                Slog.e(TAG, "Failed to copy package");
13006                return ret;
13007            }
13008
13009            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
13010            NativeLibraryHelper.Handle handle = null;
13011            try {
13012                handle = NativeLibraryHelper.Handle.create(codeFile);
13013                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
13014                        abiOverride);
13015            } catch (IOException e) {
13016                Slog.e(TAG, "Copying native libraries failed", e);
13017                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
13018            } finally {
13019                IoUtils.closeQuietly(handle);
13020            }
13021
13022            return ret;
13023        }
13024
13025        int doPreInstall(int status) {
13026            if (status != PackageManager.INSTALL_SUCCEEDED) {
13027                cleanUp();
13028            }
13029            return status;
13030        }
13031
13032        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
13033            if (status != PackageManager.INSTALL_SUCCEEDED) {
13034                cleanUp();
13035                return false;
13036            }
13037
13038            final File targetDir = codeFile.getParentFile();
13039            final File beforeCodeFile = codeFile;
13040            final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName);
13041
13042            if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
13043            try {
13044                Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
13045            } catch (ErrnoException e) {
13046                Slog.w(TAG, "Failed to rename", e);
13047                return false;
13048            }
13049
13050            if (!SELinux.restoreconRecursive(afterCodeFile)) {
13051                Slog.w(TAG, "Failed to restorecon");
13052                return false;
13053            }
13054
13055            // Reflect the rename internally
13056            codeFile = afterCodeFile;
13057            resourceFile = afterCodeFile;
13058
13059            // Reflect the rename in scanned details
13060            pkg.setCodePath(afterCodeFile.getAbsolutePath());
13061            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
13062                    afterCodeFile, pkg.baseCodePath));
13063            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
13064                    afterCodeFile, pkg.splitCodePaths));
13065
13066            // Reflect the rename in app info
13067            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
13068            pkg.setApplicationInfoCodePath(pkg.codePath);
13069            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
13070            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
13071            pkg.setApplicationInfoResourcePath(pkg.codePath);
13072            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
13073            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
13074
13075            return true;
13076        }
13077
13078        int doPostInstall(int status, int uid) {
13079            if (status != PackageManager.INSTALL_SUCCEEDED) {
13080                cleanUp();
13081            }
13082            return status;
13083        }
13084
13085        @Override
13086        String getCodePath() {
13087            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
13088        }
13089
13090        @Override
13091        String getResourcePath() {
13092            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
13093        }
13094
13095        private boolean cleanUp() {
13096            if (codeFile == null || !codeFile.exists()) {
13097                return false;
13098            }
13099
13100            removeCodePathLI(codeFile);
13101
13102            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
13103                resourceFile.delete();
13104            }
13105
13106            return true;
13107        }
13108
13109        void cleanUpResourcesLI() {
13110            // Try enumerating all code paths before deleting
13111            List<String> allCodePaths = Collections.EMPTY_LIST;
13112            if (codeFile != null && codeFile.exists()) {
13113                try {
13114                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
13115                    allCodePaths = pkg.getAllCodePaths();
13116                } catch (PackageParserException e) {
13117                    // Ignored; we tried our best
13118                }
13119            }
13120
13121            cleanUp();
13122            removeDexFiles(allCodePaths, instructionSets);
13123        }
13124
13125        boolean doPostDeleteLI(boolean delete) {
13126            // XXX err, shouldn't we respect the delete flag?
13127            cleanUpResourcesLI();
13128            return true;
13129        }
13130    }
13131
13132    private boolean isAsecExternal(String cid) {
13133        final String asecPath = PackageHelper.getSdFilesystem(cid);
13134        return !asecPath.startsWith(mAsecInternalPath);
13135    }
13136
13137    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
13138            PackageManagerException {
13139        if (copyRet < 0) {
13140            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
13141                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
13142                throw new PackageManagerException(copyRet, message);
13143            }
13144        }
13145    }
13146
13147    /**
13148     * Extract the MountService "container ID" from the full code path of an
13149     * .apk.
13150     */
13151    static String cidFromCodePath(String fullCodePath) {
13152        int eidx = fullCodePath.lastIndexOf("/");
13153        String subStr1 = fullCodePath.substring(0, eidx);
13154        int sidx = subStr1.lastIndexOf("/");
13155        return subStr1.substring(sidx+1, eidx);
13156    }
13157
13158    /**
13159     * Logic to handle installation of ASEC applications, including copying and
13160     * renaming logic.
13161     */
13162    class AsecInstallArgs extends InstallArgs {
13163        static final String RES_FILE_NAME = "pkg.apk";
13164        static final String PUBLIC_RES_FILE_NAME = "res.zip";
13165
13166        String cid;
13167        String packagePath;
13168        String resourcePath;
13169
13170        /** New install */
13171        AsecInstallArgs(InstallParams params) {
13172            super(params.origin, params.move, params.observer, params.installFlags,
13173                    params.installerPackageName, params.volumeUuid,
13174                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
13175                    params.grantedRuntimePermissions,
13176                    params.traceMethod, params.traceCookie, params.certificates);
13177        }
13178
13179        /** Existing install */
13180        AsecInstallArgs(String fullCodePath, String[] instructionSets,
13181                        boolean isExternal, boolean isForwardLocked) {
13182            super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0)
13183              | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
13184                    instructionSets, null, null, null, 0, null /*certificates*/);
13185            // Hackily pretend we're still looking at a full code path
13186            if (!fullCodePath.endsWith(RES_FILE_NAME)) {
13187                fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath();
13188            }
13189
13190            // Extract cid from fullCodePath
13191            int eidx = fullCodePath.lastIndexOf("/");
13192            String subStr1 = fullCodePath.substring(0, eidx);
13193            int sidx = subStr1.lastIndexOf("/");
13194            cid = subStr1.substring(sidx+1, eidx);
13195            setMountPath(subStr1);
13196        }
13197
13198        AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) {
13199            super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0)
13200              | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
13201                    instructionSets, null, null, null, 0, null /*certificates*/);
13202            this.cid = cid;
13203            setMountPath(PackageHelper.getSdDir(cid));
13204        }
13205
13206        void createCopyFile() {
13207            cid = mInstallerService.allocateExternalStageCidLegacy();
13208        }
13209
13210        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
13211            if (origin.staged && origin.cid != null) {
13212                if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy");
13213                cid = origin.cid;
13214                setMountPath(PackageHelper.getSdDir(cid));
13215                return PackageManager.INSTALL_SUCCEEDED;
13216            }
13217
13218            if (temp) {
13219                createCopyFile();
13220            } else {
13221                /*
13222                 * Pre-emptively destroy the container since it's destroyed if
13223                 * copying fails due to it existing anyway.
13224                 */
13225                PackageHelper.destroySdDir(cid);
13226            }
13227
13228            final String newMountPath = imcs.copyPackageToContainer(
13229                    origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(),
13230                    isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */));
13231
13232            if (newMountPath != null) {
13233                setMountPath(newMountPath);
13234                return PackageManager.INSTALL_SUCCEEDED;
13235            } else {
13236                return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
13237            }
13238        }
13239
13240        @Override
13241        String getCodePath() {
13242            return packagePath;
13243        }
13244
13245        @Override
13246        String getResourcePath() {
13247            return resourcePath;
13248        }
13249
13250        int doPreInstall(int status) {
13251            if (status != PackageManager.INSTALL_SUCCEEDED) {
13252                // Destroy container
13253                PackageHelper.destroySdDir(cid);
13254            } else {
13255                boolean mounted = PackageHelper.isContainerMounted(cid);
13256                if (!mounted) {
13257                    String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(),
13258                            Process.SYSTEM_UID);
13259                    if (newMountPath != null) {
13260                        setMountPath(newMountPath);
13261                    } else {
13262                        return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
13263                    }
13264                }
13265            }
13266            return status;
13267        }
13268
13269        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
13270            String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME);
13271            String newMountPath = null;
13272            if (PackageHelper.isContainerMounted(cid)) {
13273                // Unmount the container
13274                if (!PackageHelper.unMountSdDir(cid)) {
13275                    Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
13276                    return false;
13277                }
13278            }
13279            if (!PackageHelper.renameSdDir(cid, newCacheId)) {
13280                Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
13281                        " which might be stale. Will try to clean up.");
13282                // Clean up the stale container and proceed to recreate.
13283                if (!PackageHelper.destroySdDir(newCacheId)) {
13284                    Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
13285                    return false;
13286                }
13287                // Successfully cleaned up stale container. Try to rename again.
13288                if (!PackageHelper.renameSdDir(cid, newCacheId)) {
13289                    Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
13290                            + " inspite of cleaning it up.");
13291                    return false;
13292                }
13293            }
13294            if (!PackageHelper.isContainerMounted(newCacheId)) {
13295                Slog.w(TAG, "Mounting container " + newCacheId);
13296                newMountPath = PackageHelper.mountSdDir(newCacheId,
13297                        getEncryptKey(), Process.SYSTEM_UID);
13298            } else {
13299                newMountPath = PackageHelper.getSdDir(newCacheId);
13300            }
13301            if (newMountPath == null) {
13302                Slog.w(TAG, "Failed to get cache path for  " + newCacheId);
13303                return false;
13304            }
13305            Log.i(TAG, "Succesfully renamed " + cid +
13306                    " to " + newCacheId +
13307                    " at new path: " + newMountPath);
13308            cid = newCacheId;
13309
13310            final File beforeCodeFile = new File(packagePath);
13311            setMountPath(newMountPath);
13312            final File afterCodeFile = new File(packagePath);
13313
13314            // Reflect the rename in scanned details
13315            pkg.setCodePath(afterCodeFile.getAbsolutePath());
13316            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
13317                    afterCodeFile, pkg.baseCodePath));
13318            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
13319                    afterCodeFile, pkg.splitCodePaths));
13320
13321            // Reflect the rename in app info
13322            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
13323            pkg.setApplicationInfoCodePath(pkg.codePath);
13324            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
13325            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
13326            pkg.setApplicationInfoResourcePath(pkg.codePath);
13327            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
13328            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
13329
13330            return true;
13331        }
13332
13333        private void setMountPath(String mountPath) {
13334            final File mountFile = new File(mountPath);
13335
13336            final File monolithicFile = new File(mountFile, RES_FILE_NAME);
13337            if (monolithicFile.exists()) {
13338                packagePath = monolithicFile.getAbsolutePath();
13339                if (isFwdLocked()) {
13340                    resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath();
13341                } else {
13342                    resourcePath = packagePath;
13343                }
13344            } else {
13345                packagePath = mountFile.getAbsolutePath();
13346                resourcePath = packagePath;
13347            }
13348        }
13349
13350        int doPostInstall(int status, int uid) {
13351            if (status != PackageManager.INSTALL_SUCCEEDED) {
13352                cleanUp();
13353            } else {
13354                final int groupOwner;
13355                final String protectedFile;
13356                if (isFwdLocked()) {
13357                    groupOwner = UserHandle.getSharedAppGid(uid);
13358                    protectedFile = RES_FILE_NAME;
13359                } else {
13360                    groupOwner = -1;
13361                    protectedFile = null;
13362                }
13363
13364                if (uid < Process.FIRST_APPLICATION_UID
13365                        || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) {
13366                    Slog.e(TAG, "Failed to finalize " + cid);
13367                    PackageHelper.destroySdDir(cid);
13368                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
13369                }
13370
13371                boolean mounted = PackageHelper.isContainerMounted(cid);
13372                if (!mounted) {
13373                    PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid());
13374                }
13375            }
13376            return status;
13377        }
13378
13379        private void cleanUp() {
13380            if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp");
13381
13382            // Destroy secure container
13383            PackageHelper.destroySdDir(cid);
13384        }
13385
13386        private List<String> getAllCodePaths() {
13387            final File codeFile = new File(getCodePath());
13388            if (codeFile != null && codeFile.exists()) {
13389                try {
13390                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
13391                    return pkg.getAllCodePaths();
13392                } catch (PackageParserException e) {
13393                    // Ignored; we tried our best
13394                }
13395            }
13396            return Collections.EMPTY_LIST;
13397        }
13398
13399        void cleanUpResourcesLI() {
13400            // Enumerate all code paths before deleting
13401            cleanUpResourcesLI(getAllCodePaths());
13402        }
13403
13404        private void cleanUpResourcesLI(List<String> allCodePaths) {
13405            cleanUp();
13406            removeDexFiles(allCodePaths, instructionSets);
13407        }
13408
13409        String getPackageName() {
13410            return getAsecPackageName(cid);
13411        }
13412
13413        boolean doPostDeleteLI(boolean delete) {
13414            if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete);
13415            final List<String> allCodePaths = getAllCodePaths();
13416            boolean mounted = PackageHelper.isContainerMounted(cid);
13417            if (mounted) {
13418                // Unmount first
13419                if (PackageHelper.unMountSdDir(cid)) {
13420                    mounted = false;
13421                }
13422            }
13423            if (!mounted && delete) {
13424                cleanUpResourcesLI(allCodePaths);
13425            }
13426            return !mounted;
13427        }
13428
13429        @Override
13430        int doPreCopy() {
13431            if (isFwdLocked()) {
13432                if (!PackageHelper.fixSdPermissions(cid, getPackageUid(DEFAULT_CONTAINER_PACKAGE,
13433                        MATCH_SYSTEM_ONLY, UserHandle.USER_SYSTEM), RES_FILE_NAME)) {
13434                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
13435                }
13436            }
13437
13438            return PackageManager.INSTALL_SUCCEEDED;
13439        }
13440
13441        @Override
13442        int doPostCopy(int uid) {
13443            if (isFwdLocked()) {
13444                if (uid < Process.FIRST_APPLICATION_UID
13445                        || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid),
13446                                RES_FILE_NAME)) {
13447                    Slog.e(TAG, "Failed to finalize " + cid);
13448                    PackageHelper.destroySdDir(cid);
13449                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
13450                }
13451            }
13452
13453            return PackageManager.INSTALL_SUCCEEDED;
13454        }
13455    }
13456
13457    /**
13458     * Logic to handle movement of existing installed applications.
13459     */
13460    class MoveInstallArgs extends InstallArgs {
13461        private File codeFile;
13462        private File resourceFile;
13463
13464        /** New install */
13465        MoveInstallArgs(InstallParams params) {
13466            super(params.origin, params.move, params.observer, params.installFlags,
13467                    params.installerPackageName, params.volumeUuid,
13468                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
13469                    params.grantedRuntimePermissions,
13470                    params.traceMethod, params.traceCookie, params.certificates);
13471        }
13472
13473        int copyApk(IMediaContainerService imcs, boolean temp) {
13474            if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from "
13475                    + move.fromUuid + " to " + move.toUuid);
13476            synchronized (mInstaller) {
13477                try {
13478                    mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName,
13479                            move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion);
13480                } catch (InstallerException e) {
13481                    Slog.w(TAG, "Failed to move app", e);
13482                    return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
13483                }
13484            }
13485
13486            codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName);
13487            resourceFile = codeFile;
13488            if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile);
13489
13490            return PackageManager.INSTALL_SUCCEEDED;
13491        }
13492
13493        int doPreInstall(int status) {
13494            if (status != PackageManager.INSTALL_SUCCEEDED) {
13495                cleanUp(move.toUuid);
13496            }
13497            return status;
13498        }
13499
13500        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
13501            if (status != PackageManager.INSTALL_SUCCEEDED) {
13502                cleanUp(move.toUuid);
13503                return false;
13504            }
13505
13506            // Reflect the move in app info
13507            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
13508            pkg.setApplicationInfoCodePath(pkg.codePath);
13509            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
13510            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
13511            pkg.setApplicationInfoResourcePath(pkg.codePath);
13512            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
13513            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
13514
13515            return true;
13516        }
13517
13518        int doPostInstall(int status, int uid) {
13519            if (status == PackageManager.INSTALL_SUCCEEDED) {
13520                cleanUp(move.fromUuid);
13521            } else {
13522                cleanUp(move.toUuid);
13523            }
13524            return status;
13525        }
13526
13527        @Override
13528        String getCodePath() {
13529            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
13530        }
13531
13532        @Override
13533        String getResourcePath() {
13534            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
13535        }
13536
13537        private boolean cleanUp(String volumeUuid) {
13538            final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid),
13539                    move.dataAppName);
13540            Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid);
13541            final int[] userIds = sUserManager.getUserIds();
13542            synchronized (mInstallLock) {
13543                // Clean up both app data and code
13544                // All package moves are frozen until finished
13545                for (int userId : userIds) {
13546                    try {
13547                        mInstaller.destroyAppData(volumeUuid, move.packageName, userId,
13548                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 0);
13549                    } catch (InstallerException e) {
13550                        Slog.w(TAG, String.valueOf(e));
13551                    }
13552                }
13553                removeCodePathLI(codeFile);
13554            }
13555            return true;
13556        }
13557
13558        void cleanUpResourcesLI() {
13559            throw new UnsupportedOperationException();
13560        }
13561
13562        boolean doPostDeleteLI(boolean delete) {
13563            throw new UnsupportedOperationException();
13564        }
13565    }
13566
13567    static String getAsecPackageName(String packageCid) {
13568        int idx = packageCid.lastIndexOf("-");
13569        if (idx == -1) {
13570            return packageCid;
13571        }
13572        return packageCid.substring(0, idx);
13573    }
13574
13575    // Utility method used to create code paths based on package name and available index.
13576    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
13577        String idxStr = "";
13578        int idx = 1;
13579        // Fall back to default value of idx=1 if prefix is not
13580        // part of oldCodePath
13581        if (oldCodePath != null) {
13582            String subStr = oldCodePath;
13583            // Drop the suffix right away
13584            if (suffix != null && subStr.endsWith(suffix)) {
13585                subStr = subStr.substring(0, subStr.length() - suffix.length());
13586            }
13587            // If oldCodePath already contains prefix find out the
13588            // ending index to either increment or decrement.
13589            int sidx = subStr.lastIndexOf(prefix);
13590            if (sidx != -1) {
13591                subStr = subStr.substring(sidx + prefix.length());
13592                if (subStr != null) {
13593                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
13594                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
13595                    }
13596                    try {
13597                        idx = Integer.parseInt(subStr);
13598                        if (idx <= 1) {
13599                            idx++;
13600                        } else {
13601                            idx--;
13602                        }
13603                    } catch(NumberFormatException e) {
13604                    }
13605                }
13606            }
13607        }
13608        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
13609        return prefix + idxStr;
13610    }
13611
13612    private File getNextCodePath(File targetDir, String packageName) {
13613        int suffix = 1;
13614        File result;
13615        do {
13616            result = new File(targetDir, packageName + "-" + suffix);
13617            suffix++;
13618        } while (result.exists());
13619        return result;
13620    }
13621
13622    // Utility method that returns the relative package path with respect
13623    // to the installation directory. Like say for /data/data/com.test-1.apk
13624    // string com.test-1 is returned.
13625    static String deriveCodePathName(String codePath) {
13626        if (codePath == null) {
13627            return null;
13628        }
13629        final File codeFile = new File(codePath);
13630        final String name = codeFile.getName();
13631        if (codeFile.isDirectory()) {
13632            return name;
13633        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
13634            final int lastDot = name.lastIndexOf('.');
13635            return name.substring(0, lastDot);
13636        } else {
13637            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
13638            return null;
13639        }
13640    }
13641
13642    static class PackageInstalledInfo {
13643        String name;
13644        int uid;
13645        // The set of users that originally had this package installed.
13646        int[] origUsers;
13647        // The set of users that now have this package installed.
13648        int[] newUsers;
13649        PackageParser.Package pkg;
13650        int returnCode;
13651        String returnMsg;
13652        PackageRemovedInfo removedInfo;
13653        ArrayMap<String, PackageInstalledInfo> addedChildPackages;
13654
13655        public void setError(int code, String msg) {
13656            setReturnCode(code);
13657            setReturnMessage(msg);
13658            Slog.w(TAG, msg);
13659        }
13660
13661        public void setError(String msg, PackageParserException e) {
13662            setReturnCode(e.error);
13663            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
13664            Slog.w(TAG, msg, e);
13665        }
13666
13667        public void setError(String msg, PackageManagerException e) {
13668            returnCode = e.error;
13669            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
13670            Slog.w(TAG, msg, e);
13671        }
13672
13673        public void setReturnCode(int returnCode) {
13674            this.returnCode = returnCode;
13675            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
13676            for (int i = 0; i < childCount; i++) {
13677                addedChildPackages.valueAt(i).returnCode = returnCode;
13678            }
13679        }
13680
13681        private void setReturnMessage(String returnMsg) {
13682            this.returnMsg = returnMsg;
13683            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
13684            for (int i = 0; i < childCount; i++) {
13685                addedChildPackages.valueAt(i).returnMsg = returnMsg;
13686            }
13687        }
13688
13689        // In some error cases we want to convey more info back to the observer
13690        String origPackage;
13691        String origPermission;
13692    }
13693
13694    /*
13695     * Install a non-existing package.
13696     */
13697    private void installNewPackageLIF(PackageParser.Package pkg, final int policyFlags,
13698            int scanFlags, UserHandle user, String installerPackageName, String volumeUuid,
13699            PackageInstalledInfo res) {
13700        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage");
13701
13702        // Remember this for later, in case we need to rollback this install
13703        String pkgName = pkg.packageName;
13704
13705        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
13706
13707        synchronized(mPackages) {
13708            if (mSettings.mRenamedPackages.containsKey(pkgName)) {
13709                // A package with the same name is already installed, though
13710                // it has been renamed to an older name.  The package we
13711                // are trying to install should be installed as an update to
13712                // the existing one, but that has not been requested, so bail.
13713                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
13714                        + " without first uninstalling package running as "
13715                        + mSettings.mRenamedPackages.get(pkgName));
13716                return;
13717            }
13718            if (mPackages.containsKey(pkgName)) {
13719                // Don't allow installation over an existing package with the same name.
13720                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
13721                        + " without first uninstalling.");
13722                return;
13723            }
13724        }
13725
13726        try {
13727            PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags,
13728                    System.currentTimeMillis(), user);
13729
13730            updateSettingsLI(newPackage, installerPackageName, null, res, user);
13731
13732            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
13733                prepareAppDataAfterInstallLIF(newPackage);
13734
13735            } else {
13736                // Remove package from internal structures, but keep around any
13737                // data that might have already existed
13738                deletePackageLIF(pkgName, UserHandle.ALL, false, null,
13739                        PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null);
13740            }
13741        } catch (PackageManagerException e) {
13742            res.setError("Package couldn't be installed in " + pkg.codePath, e);
13743        }
13744
13745        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
13746    }
13747
13748    private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) {
13749        // Can't rotate keys during boot or if sharedUser.
13750        if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null
13751                || !oldPs.keySetData.isUsingUpgradeKeySets()) {
13752            return false;
13753        }
13754        // app is using upgradeKeySets; make sure all are valid
13755        KeySetManagerService ksms = mSettings.mKeySetManagerService;
13756        long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets();
13757        for (int i = 0; i < upgradeKeySets.length; i++) {
13758            if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) {
13759                Slog.wtf(TAG, "Package "
13760                         + (oldPs.name != null ? oldPs.name : "<null>")
13761                         + " contains upgrade-key-set reference to unknown key-set: "
13762                         + upgradeKeySets[i]
13763                         + " reverting to signatures check.");
13764                return false;
13765            }
13766        }
13767        return true;
13768    }
13769
13770    private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) {
13771        // Upgrade keysets are being used.  Determine if new package has a superset of the
13772        // required keys.
13773        long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets();
13774        KeySetManagerService ksms = mSettings.mKeySetManagerService;
13775        for (int i = 0; i < upgradeKeySets.length; i++) {
13776            Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]);
13777            if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) {
13778                return true;
13779            }
13780        }
13781        return false;
13782    }
13783
13784    private void replacePackageLIF(PackageParser.Package pkg, final int policyFlags, int scanFlags,
13785            UserHandle user, String installerPackageName, PackageInstalledInfo res) {
13786        final boolean isEphemeral = (policyFlags & PackageParser.PARSE_IS_EPHEMERAL) != 0;
13787
13788        final PackageParser.Package oldPackage;
13789        final String pkgName = pkg.packageName;
13790        final int[] allUsers;
13791        final int[] installedUsers;
13792
13793        synchronized(mPackages) {
13794            oldPackage = mPackages.get(pkgName);
13795            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
13796
13797            // don't allow upgrade to target a release SDK from a pre-release SDK
13798            final boolean oldTargetsPreRelease = oldPackage.applicationInfo.targetSdkVersion
13799                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
13800            final boolean newTargetsPreRelease = pkg.applicationInfo.targetSdkVersion
13801                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
13802            if (oldTargetsPreRelease
13803                    && !newTargetsPreRelease
13804                    && ((policyFlags & PackageParser.PARSE_FORCE_SDK) == 0)) {
13805                Slog.w(TAG, "Can't install package targeting released sdk");
13806                res.setReturnCode(PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE);
13807                return;
13808            }
13809
13810            // don't allow an upgrade from full to ephemeral
13811            final boolean oldIsEphemeral = oldPackage.applicationInfo.isEphemeralApp();
13812            if (isEphemeral && !oldIsEphemeral) {
13813                // can't downgrade from full to ephemeral
13814                Slog.w(TAG, "Can't replace app with ephemeral: " + pkgName);
13815                res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID);
13816                return;
13817            }
13818
13819            // verify signatures are valid
13820            final PackageSetting ps = mSettings.mPackages.get(pkgName);
13821            if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
13822                if (!checkUpgradeKeySetLP(ps, pkg)) {
13823                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
13824                            "New package not signed by keys specified by upgrade-keysets: "
13825                                    + pkgName);
13826                    return;
13827                }
13828            } else {
13829                // default to original signature matching
13830                if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
13831                        != PackageManager.SIGNATURE_MATCH) {
13832                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
13833                            "New package has a different signature: " + pkgName);
13834                    return;
13835                }
13836            }
13837
13838            // Check for shared user id changes
13839            String invalidPackageName =
13840                    getParentOrChildPackageChangedSharedUser(oldPackage, pkg);
13841            if (invalidPackageName != null) {
13842                res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
13843                        "Package " + invalidPackageName + " tried to change user "
13844                                + oldPackage.mSharedUserId);
13845                return;
13846            }
13847
13848            // In case of rollback, remember per-user/profile install state
13849            allUsers = sUserManager.getUserIds();
13850            installedUsers = ps.queryInstalledUsers(allUsers, true);
13851        }
13852
13853        // Update what is removed
13854        res.removedInfo = new PackageRemovedInfo();
13855        res.removedInfo.uid = oldPackage.applicationInfo.uid;
13856        res.removedInfo.removedPackage = oldPackage.packageName;
13857        res.removedInfo.isUpdate = true;
13858        res.removedInfo.origUsers = installedUsers;
13859        final int childCount = (oldPackage.childPackages != null)
13860                ? oldPackage.childPackages.size() : 0;
13861        for (int i = 0; i < childCount; i++) {
13862            boolean childPackageUpdated = false;
13863            PackageParser.Package childPkg = oldPackage.childPackages.get(i);
13864            if (res.addedChildPackages != null) {
13865                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
13866                if (childRes != null) {
13867                    childRes.removedInfo.uid = childPkg.applicationInfo.uid;
13868                    childRes.removedInfo.removedPackage = childPkg.packageName;
13869                    childRes.removedInfo.isUpdate = true;
13870                    childPackageUpdated = true;
13871                }
13872            }
13873            if (!childPackageUpdated) {
13874                PackageRemovedInfo childRemovedRes = new PackageRemovedInfo();
13875                childRemovedRes.removedPackage = childPkg.packageName;
13876                childRemovedRes.isUpdate = false;
13877                childRemovedRes.dataRemoved = true;
13878                synchronized (mPackages) {
13879                    PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName);
13880                    if (childPs != null) {
13881                        childRemovedRes.origUsers = childPs.queryInstalledUsers(allUsers, true);
13882                    }
13883                }
13884                if (res.removedInfo.removedChildPackages == null) {
13885                    res.removedInfo.removedChildPackages = new ArrayMap<>();
13886                }
13887                res.removedInfo.removedChildPackages.put(childPkg.packageName, childRemovedRes);
13888            }
13889        }
13890
13891        boolean sysPkg = (isSystemApp(oldPackage));
13892        if (sysPkg) {
13893            // Set the system/privileged flags as needed
13894            final boolean privileged =
13895                    (oldPackage.applicationInfo.privateFlags
13896                            & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
13897            final int systemPolicyFlags = policyFlags
13898                    | PackageParser.PARSE_IS_SYSTEM
13899                    | (privileged ? PackageParser.PARSE_IS_PRIVILEGED : 0);
13900
13901            replaceSystemPackageLIF(oldPackage, pkg, systemPolicyFlags, scanFlags,
13902                    user, allUsers, installerPackageName, res);
13903        } else {
13904            replaceNonSystemPackageLIF(oldPackage, pkg, policyFlags, scanFlags,
13905                    user, allUsers, installerPackageName, res);
13906        }
13907    }
13908
13909    public List<String> getPreviousCodePaths(String packageName) {
13910        final PackageSetting ps = mSettings.mPackages.get(packageName);
13911        final List<String> result = new ArrayList<String>();
13912        if (ps != null && ps.oldCodePaths != null) {
13913            result.addAll(ps.oldCodePaths);
13914        }
13915        return result;
13916    }
13917
13918    private void replaceNonSystemPackageLIF(PackageParser.Package deletedPackage,
13919            PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user,
13920            int[] allUsers, String installerPackageName, PackageInstalledInfo res) {
13921        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
13922                + deletedPackage);
13923
13924        String pkgName = deletedPackage.packageName;
13925        boolean deletedPkg = true;
13926        boolean addedPkg = false;
13927        boolean updatedSettings = false;
13928        final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0;
13929        final int deleteFlags = PackageManager.DELETE_KEEP_DATA
13930                | (killApp ? 0 : PackageManager.DELETE_DONT_KILL_APP);
13931
13932        final long origUpdateTime = (pkg.mExtras != null)
13933                ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0;
13934
13935        // First delete the existing package while retaining the data directory
13936        if (!deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
13937                res.removedInfo, true, pkg)) {
13938            // If the existing package wasn't successfully deleted
13939            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
13940            deletedPkg = false;
13941        } else {
13942            // Successfully deleted the old package; proceed with replace.
13943
13944            // If deleted package lived in a container, give users a chance to
13945            // relinquish resources before killing.
13946            if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) {
13947                if (DEBUG_INSTALL) {
13948                    Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
13949                }
13950                final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
13951                final ArrayList<String> pkgList = new ArrayList<String>(1);
13952                pkgList.add(deletedPackage.applicationInfo.packageName);
13953                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
13954            }
13955
13956            clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
13957                    | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
13958            clearAppProfilesLIF(pkg);
13959
13960            try {
13961                final PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags,
13962                        scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
13963                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user);
13964
13965                // Update the in-memory copy of the previous code paths.
13966                PackageSetting ps = mSettings.mPackages.get(pkgName);
13967                if (!killApp) {
13968                    if (ps.oldCodePaths == null) {
13969                        ps.oldCodePaths = new ArraySet<>();
13970                    }
13971                    Collections.addAll(ps.oldCodePaths, deletedPackage.baseCodePath);
13972                    if (deletedPackage.splitCodePaths != null) {
13973                        Collections.addAll(ps.oldCodePaths, deletedPackage.splitCodePaths);
13974                    }
13975                } else {
13976                    ps.oldCodePaths = null;
13977                }
13978                if (ps.childPackageNames != null) {
13979                    for (int i = ps.childPackageNames.size() - 1; i >= 0; --i) {
13980                        final String childPkgName = ps.childPackageNames.get(i);
13981                        final PackageSetting childPs = mSettings.mPackages.get(childPkgName);
13982                        childPs.oldCodePaths = ps.oldCodePaths;
13983                    }
13984                }
13985                prepareAppDataAfterInstallLIF(newPackage);
13986                addedPkg = true;
13987            } catch (PackageManagerException e) {
13988                res.setError("Package couldn't be installed in " + pkg.codePath, e);
13989            }
13990        }
13991
13992        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
13993            if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
13994
13995            // Revert all internal state mutations and added folders for the failed install
13996            if (addedPkg) {
13997                deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
13998                        res.removedInfo, true, null);
13999            }
14000
14001            // Restore the old package
14002            if (deletedPkg) {
14003                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
14004                File restoreFile = new File(deletedPackage.codePath);
14005                // Parse old package
14006                boolean oldExternal = isExternal(deletedPackage);
14007                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
14008                        (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) |
14009                        (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
14010                int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
14011                try {
14012                    scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime,
14013                            null);
14014                } catch (PackageManagerException e) {
14015                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
14016                            + e.getMessage());
14017                    return;
14018                }
14019
14020                synchronized (mPackages) {
14021                    // Ensure the installer package name up to date
14022                    setInstallerPackageNameLPw(deletedPackage, installerPackageName);
14023
14024                    // Update permissions for restored package
14025                    updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
14026
14027                    mSettings.writeLPr();
14028                }
14029
14030                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
14031            }
14032        } else {
14033            synchronized (mPackages) {
14034                PackageSetting ps = mSettings.peekPackageLPr(pkg.packageName);
14035                if (ps != null) {
14036                    res.removedInfo.removedForAllUsers = mPackages.get(ps.name) == null;
14037                    if (res.removedInfo.removedChildPackages != null) {
14038                        final int childCount = res.removedInfo.removedChildPackages.size();
14039                        // Iterate in reverse as we may modify the collection
14040                        for (int i = childCount - 1; i >= 0; i--) {
14041                            String childPackageName = res.removedInfo.removedChildPackages.keyAt(i);
14042                            if (res.addedChildPackages.containsKey(childPackageName)) {
14043                                res.removedInfo.removedChildPackages.removeAt(i);
14044                            } else {
14045                                PackageRemovedInfo childInfo = res.removedInfo
14046                                        .removedChildPackages.valueAt(i);
14047                                childInfo.removedForAllUsers = mPackages.get(
14048                                        childInfo.removedPackage) == null;
14049                            }
14050                        }
14051                    }
14052                }
14053            }
14054        }
14055    }
14056
14057    private void replaceSystemPackageLIF(PackageParser.Package deletedPackage,
14058            PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user,
14059            int[] allUsers, String installerPackageName, PackageInstalledInfo res) {
14060        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
14061                + ", old=" + deletedPackage);
14062
14063        final boolean disabledSystem;
14064
14065        // Remove existing system package
14066        removePackageLI(deletedPackage, true);
14067
14068        disabledSystem = disableSystemPackageLPw(deletedPackage, pkg);
14069        if (!disabledSystem) {
14070            // We didn't need to disable the .apk as a current system package,
14071            // which means we are replacing another update that is already
14072            // installed.  We need to make sure to delete the older one's .apk.
14073            res.removedInfo.args = createInstallArgsForExisting(0,
14074                    deletedPackage.applicationInfo.getCodePath(),
14075                    deletedPackage.applicationInfo.getResourcePath(),
14076                    getAppDexInstructionSets(deletedPackage.applicationInfo));
14077        } else {
14078            res.removedInfo.args = null;
14079        }
14080
14081        // Successfully disabled the old package. Now proceed with re-installation
14082        clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
14083                | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
14084        clearAppProfilesLIF(pkg);
14085
14086        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
14087        pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP,
14088                ApplicationInfo.FLAG_UPDATED_SYSTEM_APP);
14089
14090        PackageParser.Package newPackage = null;
14091        try {
14092            // Add the package to the internal data structures
14093            newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags, 0, user);
14094
14095            // Set the update and install times
14096            PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras;
14097            setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime,
14098                    System.currentTimeMillis());
14099
14100            // Update the package dynamic state if succeeded
14101            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
14102                // Now that the install succeeded make sure we remove data
14103                // directories for any child package the update removed.
14104                final int deletedChildCount = (deletedPackage.childPackages != null)
14105                        ? deletedPackage.childPackages.size() : 0;
14106                final int newChildCount = (newPackage.childPackages != null)
14107                        ? newPackage.childPackages.size() : 0;
14108                for (int i = 0; i < deletedChildCount; i++) {
14109                    PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i);
14110                    boolean childPackageDeleted = true;
14111                    for (int j = 0; j < newChildCount; j++) {
14112                        PackageParser.Package newChildPkg = newPackage.childPackages.get(j);
14113                        if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) {
14114                            childPackageDeleted = false;
14115                            break;
14116                        }
14117                    }
14118                    if (childPackageDeleted) {
14119                        PackageSetting ps = mSettings.getDisabledSystemPkgLPr(
14120                                deletedChildPkg.packageName);
14121                        if (ps != null && res.removedInfo.removedChildPackages != null) {
14122                            PackageRemovedInfo removedChildRes = res.removedInfo
14123                                    .removedChildPackages.get(deletedChildPkg.packageName);
14124                            removePackageDataLIF(ps, allUsers, removedChildRes, 0, false);
14125                            removedChildRes.removedForAllUsers = mPackages.get(ps.name) == null;
14126                        }
14127                    }
14128                }
14129
14130                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user);
14131                prepareAppDataAfterInstallLIF(newPackage);
14132            }
14133        } catch (PackageManagerException e) {
14134            res.setReturnCode(INSTALL_FAILED_INTERNAL_ERROR);
14135            res.setError("Package couldn't be installed in " + pkg.codePath, e);
14136        }
14137
14138        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
14139            // Re installation failed. Restore old information
14140            // Remove new pkg information
14141            if (newPackage != null) {
14142                removeInstalledPackageLI(newPackage, true);
14143            }
14144            // Add back the old system package
14145            try {
14146                scanPackageTracedLI(deletedPackage, policyFlags, SCAN_UPDATE_SIGNATURE, 0, user);
14147            } catch (PackageManagerException e) {
14148                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
14149            }
14150
14151            synchronized (mPackages) {
14152                if (disabledSystem) {
14153                    enableSystemPackageLPw(deletedPackage);
14154                }
14155
14156                // Ensure the installer package name up to date
14157                setInstallerPackageNameLPw(deletedPackage, installerPackageName);
14158
14159                // Update permissions for restored package
14160                updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
14161
14162                mSettings.writeLPr();
14163            }
14164
14165            Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName
14166                    + " after failed upgrade");
14167        }
14168    }
14169
14170    /**
14171     * Checks whether the parent or any of the child packages have a change shared
14172     * user. For a package to be a valid update the shred users of the parent and
14173     * the children should match. We may later support changing child shared users.
14174     * @param oldPkg The updated package.
14175     * @param newPkg The update package.
14176     * @return The shared user that change between the versions.
14177     */
14178    private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg,
14179            PackageParser.Package newPkg) {
14180        // Check parent shared user
14181        if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) {
14182            return newPkg.packageName;
14183        }
14184        // Check child shared users
14185        final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
14186        final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0;
14187        for (int i = 0; i < newChildCount; i++) {
14188            PackageParser.Package newChildPkg = newPkg.childPackages.get(i);
14189            // If this child was present, did it have the same shared user?
14190            for (int j = 0; j < oldChildCount; j++) {
14191                PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j);
14192                if (newChildPkg.packageName.equals(oldChildPkg.packageName)
14193                        && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) {
14194                    return newChildPkg.packageName;
14195                }
14196            }
14197        }
14198        return null;
14199    }
14200
14201    private void removeNativeBinariesLI(PackageSetting ps) {
14202        // Remove the lib path for the parent package
14203        if (ps != null) {
14204            NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString);
14205            // Remove the lib path for the child packages
14206            final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
14207            for (int i = 0; i < childCount; i++) {
14208                PackageSetting childPs = null;
14209                synchronized (mPackages) {
14210                    childPs = mSettings.peekPackageLPr(ps.childPackageNames.get(i));
14211                }
14212                if (childPs != null) {
14213                    NativeLibraryHelper.removeNativeBinariesLI(childPs
14214                            .legacyNativeLibraryPathString);
14215                }
14216            }
14217        }
14218    }
14219
14220    private void enableSystemPackageLPw(PackageParser.Package pkg) {
14221        // Enable the parent package
14222        mSettings.enableSystemPackageLPw(pkg.packageName);
14223        // Enable the child packages
14224        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
14225        for (int i = 0; i < childCount; i++) {
14226            PackageParser.Package childPkg = pkg.childPackages.get(i);
14227            mSettings.enableSystemPackageLPw(childPkg.packageName);
14228        }
14229    }
14230
14231    private boolean disableSystemPackageLPw(PackageParser.Package oldPkg,
14232            PackageParser.Package newPkg) {
14233        // Disable the parent package (parent always replaced)
14234        boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true);
14235        // Disable the child packages
14236        final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
14237        for (int i = 0; i < childCount; i++) {
14238            PackageParser.Package childPkg = oldPkg.childPackages.get(i);
14239            final boolean replace = newPkg.hasChildPackage(childPkg.packageName);
14240            disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace);
14241        }
14242        return disabled;
14243    }
14244
14245    private void setInstallerPackageNameLPw(PackageParser.Package pkg,
14246            String installerPackageName) {
14247        // Enable the parent package
14248        mSettings.setInstallerPackageName(pkg.packageName, installerPackageName);
14249        // Enable the child packages
14250        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
14251        for (int i = 0; i < childCount; i++) {
14252            PackageParser.Package childPkg = pkg.childPackages.get(i);
14253            mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName);
14254        }
14255    }
14256
14257    private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) {
14258        // Collect all used permissions in the UID
14259        ArraySet<String> usedPermissions = new ArraySet<>();
14260        final int packageCount = su.packages.size();
14261        for (int i = 0; i < packageCount; i++) {
14262            PackageSetting ps = su.packages.valueAt(i);
14263            if (ps.pkg == null) {
14264                continue;
14265            }
14266            final int requestedPermCount = ps.pkg.requestedPermissions.size();
14267            for (int j = 0; j < requestedPermCount; j++) {
14268                String permission = ps.pkg.requestedPermissions.get(j);
14269                BasePermission bp = mSettings.mPermissions.get(permission);
14270                if (bp != null) {
14271                    usedPermissions.add(permission);
14272                }
14273            }
14274        }
14275
14276        PermissionsState permissionsState = su.getPermissionsState();
14277        // Prune install permissions
14278        List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates();
14279        final int installPermCount = installPermStates.size();
14280        for (int i = installPermCount - 1; i >= 0;  i--) {
14281            PermissionState permissionState = installPermStates.get(i);
14282            if (!usedPermissions.contains(permissionState.getName())) {
14283                BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
14284                if (bp != null) {
14285                    permissionsState.revokeInstallPermission(bp);
14286                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
14287                            PackageManager.MASK_PERMISSION_FLAGS, 0);
14288                }
14289            }
14290        }
14291
14292        int[] runtimePermissionChangedUserIds = EmptyArray.INT;
14293
14294        // Prune runtime permissions
14295        for (int userId : allUserIds) {
14296            List<PermissionState> runtimePermStates = permissionsState
14297                    .getRuntimePermissionStates(userId);
14298            final int runtimePermCount = runtimePermStates.size();
14299            for (int i = runtimePermCount - 1; i >= 0; i--) {
14300                PermissionState permissionState = runtimePermStates.get(i);
14301                if (!usedPermissions.contains(permissionState.getName())) {
14302                    BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
14303                    if (bp != null) {
14304                        permissionsState.revokeRuntimePermission(bp, userId);
14305                        permissionsState.updatePermissionFlags(bp, userId,
14306                                PackageManager.MASK_PERMISSION_FLAGS, 0);
14307                        runtimePermissionChangedUserIds = ArrayUtils.appendInt(
14308                                runtimePermissionChangedUserIds, userId);
14309                    }
14310                }
14311            }
14312        }
14313
14314        return runtimePermissionChangedUserIds;
14315    }
14316
14317    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
14318            int[] allUsers, PackageInstalledInfo res, UserHandle user) {
14319        // Update the parent package setting
14320        updateSettingsInternalLI(newPackage, installerPackageName, allUsers, res.origUsers,
14321                res, user);
14322        // Update the child packages setting
14323        final int childCount = (newPackage.childPackages != null)
14324                ? newPackage.childPackages.size() : 0;
14325        for (int i = 0; i < childCount; i++) {
14326            PackageParser.Package childPackage = newPackage.childPackages.get(i);
14327            PackageInstalledInfo childRes = res.addedChildPackages.get(childPackage.packageName);
14328            updateSettingsInternalLI(childPackage, installerPackageName, allUsers,
14329                    childRes.origUsers, childRes, user);
14330        }
14331    }
14332
14333    private void updateSettingsInternalLI(PackageParser.Package newPackage,
14334            String installerPackageName, int[] allUsers, int[] installedForUsers,
14335            PackageInstalledInfo res, UserHandle user) {
14336        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
14337
14338        String pkgName = newPackage.packageName;
14339        synchronized (mPackages) {
14340            //write settings. the installStatus will be incomplete at this stage.
14341            //note that the new package setting would have already been
14342            //added to mPackages. It hasn't been persisted yet.
14343            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
14344            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
14345            mSettings.writeLPr();
14346            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
14347        }
14348
14349        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath);
14350        synchronized (mPackages) {
14351            updatePermissionsLPw(newPackage.packageName, newPackage,
14352                    UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
14353                            ? UPDATE_PERMISSIONS_ALL : 0));
14354            // For system-bundled packages, we assume that installing an upgraded version
14355            // of the package implies that the user actually wants to run that new code,
14356            // so we enable the package.
14357            PackageSetting ps = mSettings.mPackages.get(pkgName);
14358            final int userId = user.getIdentifier();
14359            if (ps != null) {
14360                if (isSystemApp(newPackage)) {
14361                    if (DEBUG_INSTALL) {
14362                        Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
14363                    }
14364                    // Enable system package for requested users
14365                    if (res.origUsers != null) {
14366                        for (int origUserId : res.origUsers) {
14367                            if (userId == UserHandle.USER_ALL || userId == origUserId) {
14368                                ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
14369                                        origUserId, installerPackageName);
14370                            }
14371                        }
14372                    }
14373                    // Also convey the prior install/uninstall state
14374                    if (allUsers != null && installedForUsers != null) {
14375                        for (int currentUserId : allUsers) {
14376                            final boolean installed = ArrayUtils.contains(
14377                                    installedForUsers, currentUserId);
14378                            if (DEBUG_INSTALL) {
14379                                Slog.d(TAG, "    user " + currentUserId + " => " + installed);
14380                            }
14381                            ps.setInstalled(installed, currentUserId);
14382                        }
14383                        // these install state changes will be persisted in the
14384                        // upcoming call to mSettings.writeLPr().
14385                    }
14386                }
14387                // It's implied that when a user requests installation, they want the app to be
14388                // installed and enabled.
14389                if (userId != UserHandle.USER_ALL) {
14390                    ps.setInstalled(true, userId);
14391                    ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName);
14392                }
14393            }
14394            res.name = pkgName;
14395            res.uid = newPackage.applicationInfo.uid;
14396            res.pkg = newPackage;
14397            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
14398            mSettings.setInstallerPackageName(pkgName, installerPackageName);
14399            res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
14400            //to update install status
14401            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
14402            mSettings.writeLPr();
14403            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
14404        }
14405
14406        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
14407    }
14408
14409    private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) {
14410        try {
14411            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage");
14412            installPackageLI(args, res);
14413        } finally {
14414            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
14415        }
14416    }
14417
14418    private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
14419        final int installFlags = args.installFlags;
14420        final String installerPackageName = args.installerPackageName;
14421        final String volumeUuid = args.volumeUuid;
14422        final File tmpPackageFile = new File(args.getCodePath());
14423        final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
14424        final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0)
14425                || (args.volumeUuid != null));
14426        final boolean ephemeral = ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0);
14427        final boolean forceSdk = ((installFlags & PackageManager.INSTALL_FORCE_SDK) != 0);
14428        boolean replace = false;
14429        int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE;
14430        if (args.move != null) {
14431            // moving a complete application; perform an initial scan on the new install location
14432            scanFlags |= SCAN_INITIAL;
14433        }
14434        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
14435            scanFlags |= SCAN_DONT_KILL_APP;
14436        }
14437
14438        // Result object to be returned
14439        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
14440
14441        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
14442
14443        // Sanity check
14444        if (ephemeral && (forwardLocked || onExternal)) {
14445            Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked
14446                    + " external=" + onExternal);
14447            res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID);
14448            return;
14449        }
14450
14451        // Retrieve PackageSettings and parse package
14452        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
14453                | PackageParser.PARSE_ENFORCE_CODE
14454                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
14455                | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0)
14456                | (ephemeral ? PackageParser.PARSE_IS_EPHEMERAL : 0)
14457                | (forceSdk ? PackageParser.PARSE_FORCE_SDK : 0);
14458        PackageParser pp = new PackageParser();
14459        pp.setSeparateProcesses(mSeparateProcesses);
14460        pp.setDisplayMetrics(mMetrics);
14461
14462        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
14463        final PackageParser.Package pkg;
14464        try {
14465            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
14466        } catch (PackageParserException e) {
14467            res.setError("Failed parse during installPackageLI", e);
14468            return;
14469        } finally {
14470            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
14471        }
14472
14473        // If we are installing a clustered package add results for the children
14474        if (pkg.childPackages != null) {
14475            synchronized (mPackages) {
14476                final int childCount = pkg.childPackages.size();
14477                for (int i = 0; i < childCount; i++) {
14478                    PackageParser.Package childPkg = pkg.childPackages.get(i);
14479                    PackageInstalledInfo childRes = new PackageInstalledInfo();
14480                    childRes.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
14481                    childRes.pkg = childPkg;
14482                    childRes.name = childPkg.packageName;
14483                    PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName);
14484                    if (childPs != null) {
14485                        childRes.origUsers = childPs.queryInstalledUsers(
14486                                sUserManager.getUserIds(), true);
14487                    }
14488                    if ((mPackages.containsKey(childPkg.packageName))) {
14489                        childRes.removedInfo = new PackageRemovedInfo();
14490                        childRes.removedInfo.removedPackage = childPkg.packageName;
14491                    }
14492                    if (res.addedChildPackages == null) {
14493                        res.addedChildPackages = new ArrayMap<>();
14494                    }
14495                    res.addedChildPackages.put(childPkg.packageName, childRes);
14496                }
14497            }
14498        }
14499
14500        // If package doesn't declare API override, mark that we have an install
14501        // time CPU ABI override.
14502        if (TextUtils.isEmpty(pkg.cpuAbiOverride)) {
14503            pkg.cpuAbiOverride = args.abiOverride;
14504        }
14505
14506        String pkgName = res.name = pkg.packageName;
14507        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
14508            if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
14509                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
14510                return;
14511            }
14512        }
14513
14514        try {
14515            // either use what we've been given or parse directly from the APK
14516            if (args.certificates != null) {
14517                try {
14518                    PackageParser.populateCertificates(pkg, args.certificates);
14519                } catch (PackageParserException e) {
14520                    // there was something wrong with the certificates we were given;
14521                    // try to pull them from the APK
14522                    PackageParser.collectCertificates(pkg, parseFlags);
14523                }
14524            } else {
14525                PackageParser.collectCertificates(pkg, parseFlags);
14526            }
14527        } catch (PackageParserException e) {
14528            res.setError("Failed collect during installPackageLI", e);
14529            return;
14530        }
14531
14532        // Get rid of all references to package scan path via parser.
14533        pp = null;
14534        String oldCodePath = null;
14535        boolean systemApp = false;
14536        synchronized (mPackages) {
14537            // Check if installing already existing package
14538            if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
14539                String oldName = mSettings.mRenamedPackages.get(pkgName);
14540                if (pkg.mOriginalPackages != null
14541                        && pkg.mOriginalPackages.contains(oldName)
14542                        && mPackages.containsKey(oldName)) {
14543                    // This package is derived from an original package,
14544                    // and this device has been updating from that original
14545                    // name.  We must continue using the original name, so
14546                    // rename the new package here.
14547                    pkg.setPackageName(oldName);
14548                    pkgName = pkg.packageName;
14549                    replace = true;
14550                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
14551                            + oldName + " pkgName=" + pkgName);
14552                } else if (mPackages.containsKey(pkgName)) {
14553                    // This package, under its official name, already exists
14554                    // on the device; we should replace it.
14555                    replace = true;
14556                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
14557                }
14558
14559                // Child packages are installed through the parent package
14560                if (pkg.parentPackage != null) {
14561                    res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
14562                            "Package " + pkg.packageName + " is child of package "
14563                                    + pkg.parentPackage.parentPackage + ". Child packages "
14564                                    + "can be updated only through the parent package.");
14565                    return;
14566                }
14567
14568                if (replace) {
14569                    // Prevent apps opting out from runtime permissions
14570                    PackageParser.Package oldPackage = mPackages.get(pkgName);
14571                    final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion;
14572                    final int newTargetSdk = pkg.applicationInfo.targetSdkVersion;
14573                    if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1
14574                            && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) {
14575                        res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE,
14576                                "Package " + pkg.packageName + " new target SDK " + newTargetSdk
14577                                        + " doesn't support runtime permissions but the old"
14578                                        + " target SDK " + oldTargetSdk + " does.");
14579                        return;
14580                    }
14581
14582                    // Prevent installing of child packages
14583                    if (oldPackage.parentPackage != null) {
14584                        res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
14585                                "Package " + pkg.packageName + " is child of package "
14586                                        + oldPackage.parentPackage + ". Child packages "
14587                                        + "can be updated only through the parent package.");
14588                        return;
14589                    }
14590                }
14591            }
14592
14593            PackageSetting ps = mSettings.mPackages.get(pkgName);
14594            if (ps != null) {
14595                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
14596
14597                // Quick sanity check that we're signed correctly if updating;
14598                // we'll check this again later when scanning, but we want to
14599                // bail early here before tripping over redefined permissions.
14600                if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
14601                    if (!checkUpgradeKeySetLP(ps, pkg)) {
14602                        res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
14603                                + pkg.packageName + " upgrade keys do not match the "
14604                                + "previously installed version");
14605                        return;
14606                    }
14607                } else {
14608                    try {
14609                        verifySignaturesLP(ps, pkg);
14610                    } catch (PackageManagerException e) {
14611                        res.setError(e.error, e.getMessage());
14612                        return;
14613                    }
14614                }
14615
14616                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
14617                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
14618                    systemApp = (ps.pkg.applicationInfo.flags &
14619                            ApplicationInfo.FLAG_SYSTEM) != 0;
14620                }
14621                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
14622            }
14623
14624            // Check whether the newly-scanned package wants to define an already-defined perm
14625            int N = pkg.permissions.size();
14626            for (int i = N-1; i >= 0; i--) {
14627                PackageParser.Permission perm = pkg.permissions.get(i);
14628                BasePermission bp = mSettings.mPermissions.get(perm.info.name);
14629                if (bp != null) {
14630                    // If the defining package is signed with our cert, it's okay.  This
14631                    // also includes the "updating the same package" case, of course.
14632                    // "updating same package" could also involve key-rotation.
14633                    final boolean sigsOk;
14634                    if (bp.sourcePackage.equals(pkg.packageName)
14635                            && (bp.packageSetting instanceof PackageSetting)
14636                            && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting,
14637                                    scanFlags))) {
14638                        sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg);
14639                    } else {
14640                        sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures,
14641                                pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
14642                    }
14643                    if (!sigsOk) {
14644                        // If the owning package is the system itself, we log but allow
14645                        // install to proceed; we fail the install on all other permission
14646                        // redefinitions.
14647                        if (!bp.sourcePackage.equals("android")) {
14648                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
14649                                    + pkg.packageName + " attempting to redeclare permission "
14650                                    + perm.info.name + " already owned by " + bp.sourcePackage);
14651                            res.origPermission = perm.info.name;
14652                            res.origPackage = bp.sourcePackage;
14653                            return;
14654                        } else {
14655                            Slog.w(TAG, "Package " + pkg.packageName
14656                                    + " attempting to redeclare system permission "
14657                                    + perm.info.name + "; ignoring new declaration");
14658                            pkg.permissions.remove(i);
14659                        }
14660                    }
14661                }
14662            }
14663        }
14664
14665        if (systemApp) {
14666            if (onExternal) {
14667                // Abort update; system app can't be replaced with app on sdcard
14668                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
14669                        "Cannot install updates to system apps on sdcard");
14670                return;
14671            } else if (ephemeral) {
14672                // Abort update; system app can't be replaced with an ephemeral app
14673                res.setError(INSTALL_FAILED_EPHEMERAL_INVALID,
14674                        "Cannot update a system app with an ephemeral app");
14675                return;
14676            }
14677        }
14678
14679        if (args.move != null) {
14680            // We did an in-place move, so dex is ready to roll
14681            scanFlags |= SCAN_NO_DEX;
14682            scanFlags |= SCAN_MOVE;
14683
14684            synchronized (mPackages) {
14685                final PackageSetting ps = mSettings.mPackages.get(pkgName);
14686                if (ps == null) {
14687                    res.setError(INSTALL_FAILED_INTERNAL_ERROR,
14688                            "Missing settings for moved package " + pkgName);
14689                }
14690
14691                // We moved the entire application as-is, so bring over the
14692                // previously derived ABI information.
14693                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
14694                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
14695            }
14696
14697        } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) {
14698            // Enable SCAN_NO_DEX flag to skip dexopt at a later stage
14699            scanFlags |= SCAN_NO_DEX;
14700
14701            try {
14702                String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ?
14703                    args.abiOverride : pkg.cpuAbiOverride);
14704                derivePackageAbi(pkg, new File(pkg.codePath), abiOverride,
14705                        true /* extract libs */);
14706            } catch (PackageManagerException pme) {
14707                Slog.e(TAG, "Error deriving application ABI", pme);
14708                res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI");
14709                return;
14710            }
14711
14712            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
14713            // Do not run PackageDexOptimizer through the local performDexOpt
14714            // method because `pkg` is not in `mPackages` yet.
14715            int result = mPackageDexOptimizer.performDexOpt(pkg, null /* instructionSets */,
14716                    false /* checkProfiles */, getCompilerFilterForReason(REASON_INSTALL));
14717            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
14718            if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
14719                String msg = "Extracting package failed for " + pkgName;
14720                res.setError(INSTALL_FAILED_DEXOPT, msg);
14721                return;
14722            }
14723
14724            // Notify BackgroundDexOptService that the package has been changed.
14725            // If this is an update of a package which used to fail to compile,
14726            // BDOS will remove it from its blacklist.
14727            BackgroundDexOptService.notifyPackageChanged(pkg.packageName);
14728        }
14729
14730        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
14731            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
14732            return;
14733        }
14734
14735        startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg);
14736
14737        try (PackageFreezer freezer = freezePackageForInstall(pkgName, installFlags,
14738                "installPackageLI")) {
14739            if (replace) {
14740                replacePackageLIF(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user,
14741                        installerPackageName, res);
14742            } else {
14743                installNewPackageLIF(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
14744                        args.user, installerPackageName, volumeUuid, res);
14745            }
14746        }
14747        synchronized (mPackages) {
14748            final PackageSetting ps = mSettings.mPackages.get(pkgName);
14749            if (ps != null) {
14750                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
14751            }
14752
14753            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
14754            for (int i = 0; i < childCount; i++) {
14755                PackageParser.Package childPkg = pkg.childPackages.get(i);
14756                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
14757                PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName);
14758                if (childPs != null) {
14759                    childRes.newUsers = childPs.queryInstalledUsers(
14760                            sUserManager.getUserIds(), true);
14761                }
14762            }
14763        }
14764    }
14765
14766    private void startIntentFilterVerifications(int userId, boolean replacing,
14767            PackageParser.Package pkg) {
14768        if (mIntentFilterVerifierComponent == null) {
14769            Slog.w(TAG, "No IntentFilter verification will not be done as "
14770                    + "there is no IntentFilterVerifier available!");
14771            return;
14772        }
14773
14774        final int verifierUid = getPackageUid(
14775                mIntentFilterVerifierComponent.getPackageName(),
14776                MATCH_DEBUG_TRIAGED_MISSING,
14777                (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId);
14778
14779        Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
14780        msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid);
14781        mHandler.sendMessage(msg);
14782
14783        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
14784        for (int i = 0; i < childCount; i++) {
14785            PackageParser.Package childPkg = pkg.childPackages.get(i);
14786            msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
14787            msg.obj = new IFVerificationParams(childPkg, replacing, userId, verifierUid);
14788            mHandler.sendMessage(msg);
14789        }
14790    }
14791
14792    private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing,
14793            PackageParser.Package pkg) {
14794        int size = pkg.activities.size();
14795        if (size == 0) {
14796            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
14797                    "No activity, so no need to verify any IntentFilter!");
14798            return;
14799        }
14800
14801        final boolean hasDomainURLs = hasDomainURLs(pkg);
14802        if (!hasDomainURLs) {
14803            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
14804                    "No domain URLs, so no need to verify any IntentFilter!");
14805            return;
14806        }
14807
14808        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId
14809                + " if any IntentFilter from the " + size
14810                + " Activities needs verification ...");
14811
14812        int count = 0;
14813        final String packageName = pkg.packageName;
14814
14815        synchronized (mPackages) {
14816            // If this is a new install and we see that we've already run verification for this
14817            // package, we have nothing to do: it means the state was restored from backup.
14818            if (!replacing) {
14819                IntentFilterVerificationInfo ivi =
14820                        mSettings.getIntentFilterVerificationLPr(packageName);
14821                if (ivi != null) {
14822                    if (DEBUG_DOMAIN_VERIFICATION) {
14823                        Slog.i(TAG, "Package " + packageName+ " already verified: status="
14824                                + ivi.getStatusString());
14825                    }
14826                    return;
14827                }
14828            }
14829
14830            // If any filters need to be verified, then all need to be.
14831            boolean needToVerify = false;
14832            for (PackageParser.Activity a : pkg.activities) {
14833                for (ActivityIntentInfo filter : a.intents) {
14834                    if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) {
14835                        if (DEBUG_DOMAIN_VERIFICATION) {
14836                            Slog.d(TAG, "Intent filter needs verification, so processing all filters");
14837                        }
14838                        needToVerify = true;
14839                        break;
14840                    }
14841                }
14842            }
14843
14844            if (needToVerify) {
14845                final int verificationId = mIntentFilterVerificationToken++;
14846                for (PackageParser.Activity a : pkg.activities) {
14847                    for (ActivityIntentInfo filter : a.intents) {
14848                        if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) {
14849                            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
14850                                    "Verification needed for IntentFilter:" + filter.toString());
14851                            mIntentFilterVerifier.addOneIntentFilterVerification(
14852                                    verifierUid, userId, verificationId, filter, packageName);
14853                            count++;
14854                        }
14855                    }
14856                }
14857            }
14858        }
14859
14860        if (count > 0) {
14861            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count
14862                    + " IntentFilter verification" + (count > 1 ? "s" : "")
14863                    +  " for userId:" + userId);
14864            mIntentFilterVerifier.startVerifications(userId);
14865        } else {
14866            if (DEBUG_DOMAIN_VERIFICATION) {
14867                Slog.d(TAG, "No filters or not all autoVerify for " + packageName);
14868            }
14869        }
14870    }
14871
14872    private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) {
14873        final ComponentName cn  = filter.activity.getComponentName();
14874        final String packageName = cn.getPackageName();
14875
14876        IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr(
14877                packageName);
14878        if (ivi == null) {
14879            return true;
14880        }
14881        int status = ivi.getStatus();
14882        switch (status) {
14883            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
14884            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
14885                return true;
14886
14887            default:
14888                // Nothing to do
14889                return false;
14890        }
14891    }
14892
14893    private static boolean isMultiArch(ApplicationInfo info) {
14894        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
14895    }
14896
14897    private static boolean isExternal(PackageParser.Package pkg) {
14898        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
14899    }
14900
14901    private static boolean isExternal(PackageSetting ps) {
14902        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
14903    }
14904
14905    private static boolean isEphemeral(PackageParser.Package pkg) {
14906        return pkg.applicationInfo.isEphemeralApp();
14907    }
14908
14909    private static boolean isEphemeral(PackageSetting ps) {
14910        return ps.pkg != null && isEphemeral(ps.pkg);
14911    }
14912
14913    private static boolean isSystemApp(PackageParser.Package pkg) {
14914        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
14915    }
14916
14917    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
14918        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
14919    }
14920
14921    private static boolean hasDomainURLs(PackageParser.Package pkg) {
14922        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0;
14923    }
14924
14925    private static boolean isSystemApp(PackageSetting ps) {
14926        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
14927    }
14928
14929    private static boolean isUpdatedSystemApp(PackageSetting ps) {
14930        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
14931    }
14932
14933    private int packageFlagsToInstallFlags(PackageSetting ps) {
14934        int installFlags = 0;
14935        if (isEphemeral(ps)) {
14936            installFlags |= PackageManager.INSTALL_EPHEMERAL;
14937        }
14938        if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) {
14939            // This existing package was an external ASEC install when we have
14940            // the external flag without a UUID
14941            installFlags |= PackageManager.INSTALL_EXTERNAL;
14942        }
14943        if (ps.isForwardLocked()) {
14944            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
14945        }
14946        return installFlags;
14947    }
14948
14949    private String getVolumeUuidForPackage(PackageParser.Package pkg) {
14950        if (isExternal(pkg)) {
14951            if (TextUtils.isEmpty(pkg.volumeUuid)) {
14952                return StorageManager.UUID_PRIMARY_PHYSICAL;
14953            } else {
14954                return pkg.volumeUuid;
14955            }
14956        } else {
14957            return StorageManager.UUID_PRIVATE_INTERNAL;
14958        }
14959    }
14960
14961    private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) {
14962        if (isExternal(pkg)) {
14963            if (TextUtils.isEmpty(pkg.volumeUuid)) {
14964                return mSettings.getExternalVersion();
14965            } else {
14966                return mSettings.findOrCreateVersion(pkg.volumeUuid);
14967            }
14968        } else {
14969            return mSettings.getInternalVersion();
14970        }
14971    }
14972
14973    private void deleteTempPackageFiles() {
14974        final FilenameFilter filter = new FilenameFilter() {
14975            public boolean accept(File dir, String name) {
14976                return name.startsWith("vmdl") && name.endsWith(".tmp");
14977            }
14978        };
14979        for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) {
14980            file.delete();
14981        }
14982    }
14983
14984    @Override
14985    public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId,
14986            int flags) {
14987        deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId,
14988                flags);
14989    }
14990
14991    @Override
14992    public void deletePackage(final String packageName,
14993            final IPackageDeleteObserver2 observer, final int userId, final int deleteFlags) {
14994        mContext.enforceCallingOrSelfPermission(
14995                android.Manifest.permission.DELETE_PACKAGES, null);
14996        Preconditions.checkNotNull(packageName);
14997        Preconditions.checkNotNull(observer);
14998        final int uid = Binder.getCallingUid();
14999        final boolean deleteAllUsers = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0;
15000        final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId };
15001        if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) {
15002            mContext.enforceCallingOrSelfPermission(
15003                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
15004                    "deletePackage for user " + userId);
15005        }
15006
15007        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
15008            try {
15009                observer.onPackageDeleted(packageName,
15010                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
15011            } catch (RemoteException re) {
15012            }
15013            return;
15014        }
15015
15016        if (!deleteAllUsers && getBlockUninstallForUser(packageName, userId)) {
15017            try {
15018                observer.onPackageDeleted(packageName,
15019                        PackageManager.DELETE_FAILED_OWNER_BLOCKED, null);
15020            } catch (RemoteException re) {
15021            }
15022            return;
15023        }
15024
15025        if (DEBUG_REMOVE) {
15026            Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId
15027                    + " deleteAllUsers: " + deleteAllUsers );
15028        }
15029        // Queue up an async operation since the package deletion may take a little while.
15030        mHandler.post(new Runnable() {
15031            public void run() {
15032                mHandler.removeCallbacks(this);
15033                int returnCode;
15034                if (!deleteAllUsers) {
15035                    returnCode = deletePackageX(packageName, userId, deleteFlags);
15036                } else {
15037                    int[] blockUninstallUserIds = getBlockUninstallForUsers(packageName, users);
15038                    // If nobody is blocking uninstall, proceed with delete for all users
15039                    if (ArrayUtils.isEmpty(blockUninstallUserIds)) {
15040                        returnCode = deletePackageX(packageName, userId, deleteFlags);
15041                    } else {
15042                        // Otherwise uninstall individually for users with blockUninstalls=false
15043                        final int userFlags = deleteFlags & ~PackageManager.DELETE_ALL_USERS;
15044                        for (int userId : users) {
15045                            if (!ArrayUtils.contains(blockUninstallUserIds, userId)) {
15046                                returnCode = deletePackageX(packageName, userId, userFlags);
15047                                if (returnCode != PackageManager.DELETE_SUCCEEDED) {
15048                                    Slog.w(TAG, "Package delete failed for user " + userId
15049                                            + ", returnCode " + returnCode);
15050                                }
15051                            }
15052                        }
15053                        // The app has only been marked uninstalled for certain users.
15054                        // We still need to report that delete was blocked
15055                        returnCode = PackageManager.DELETE_FAILED_OWNER_BLOCKED;
15056                    }
15057                }
15058                try {
15059                    observer.onPackageDeleted(packageName, returnCode, null);
15060                } catch (RemoteException e) {
15061                    Log.i(TAG, "Observer no longer exists.");
15062                } //end catch
15063            } //end run
15064        });
15065    }
15066
15067    private int[] getBlockUninstallForUsers(String packageName, int[] userIds) {
15068        int[] result = EMPTY_INT_ARRAY;
15069        for (int userId : userIds) {
15070            if (getBlockUninstallForUser(packageName, userId)) {
15071                result = ArrayUtils.appendInt(result, userId);
15072            }
15073        }
15074        return result;
15075    }
15076
15077    @Override
15078    public boolean isPackageDeviceAdminOnAnyUser(String packageName) {
15079        return isPackageDeviceAdmin(packageName, UserHandle.USER_ALL);
15080    }
15081
15082    private boolean isPackageDeviceAdmin(String packageName, int userId) {
15083        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
15084                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
15085        try {
15086            if (dpm != null) {
15087                final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent(
15088                        /* callingUserOnly =*/ false);
15089                final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null
15090                        : deviceOwnerComponentName.getPackageName();
15091                // Does the package contains the device owner?
15092                // TODO Do we have to do it even if userId != UserHandle.USER_ALL?  Otherwise,
15093                // this check is probably not needed, since DO should be registered as a device
15094                // admin on some user too. (Original bug for this: b/17657954)
15095                if (packageName.equals(deviceOwnerPackageName)) {
15096                    return true;
15097                }
15098                // Does it contain a device admin for any user?
15099                int[] users;
15100                if (userId == UserHandle.USER_ALL) {
15101                    users = sUserManager.getUserIds();
15102                } else {
15103                    users = new int[]{userId};
15104                }
15105                for (int i = 0; i < users.length; ++i) {
15106                    if (dpm.packageHasActiveAdmins(packageName, users[i])) {
15107                        return true;
15108                    }
15109                }
15110            }
15111        } catch (RemoteException e) {
15112        }
15113        return false;
15114    }
15115
15116    private boolean shouldKeepUninstalledPackageLPr(String packageName) {
15117        return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName);
15118    }
15119
15120    /**
15121     *  This method is an internal method that could be get invoked either
15122     *  to delete an installed package or to clean up a failed installation.
15123     *  After deleting an installed package, a broadcast is sent to notify any
15124     *  listeners that the package has been removed. For cleaning up a failed
15125     *  installation, the broadcast is not necessary since the package's
15126     *  installation wouldn't have sent the initial broadcast either
15127     *  The key steps in deleting a package are
15128     *  deleting the package information in internal structures like mPackages,
15129     *  deleting the packages base directories through installd
15130     *  updating mSettings to reflect current status
15131     *  persisting settings for later use
15132     *  sending a broadcast if necessary
15133     */
15134    private int deletePackageX(String packageName, int userId, int deleteFlags) {
15135        final PackageRemovedInfo info = new PackageRemovedInfo();
15136        final boolean res;
15137
15138        final UserHandle removeForUser = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0
15139                ? UserHandle.ALL : new UserHandle(userId);
15140
15141        if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) {
15142            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
15143            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
15144        }
15145
15146        PackageSetting uninstalledPs = null;
15147
15148        // for the uninstall-updates case and restricted profiles, remember the per-
15149        // user handle installed state
15150        int[] allUsers;
15151        synchronized (mPackages) {
15152            uninstalledPs = mSettings.mPackages.get(packageName);
15153            if (uninstalledPs == null) {
15154                Slog.w(TAG, "Not removing non-existent package " + packageName);
15155                return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
15156            }
15157            allUsers = sUserManager.getUserIds();
15158            info.origUsers = uninstalledPs.queryInstalledUsers(allUsers, true);
15159        }
15160
15161        synchronized (mInstallLock) {
15162            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
15163            try (PackageFreezer freezer = freezePackageForDelete(packageName, deleteFlags,
15164                    "deletePackageX")) {
15165                res = deletePackageLIF(packageName, removeForUser, true, allUsers,
15166                        deleteFlags | REMOVE_CHATTY, info, true, null);
15167            }
15168            synchronized (mPackages) {
15169                if (res) {
15170                    mEphemeralApplicationRegistry.onPackageUninstalledLPw(uninstalledPs.pkg);
15171                }
15172            }
15173        }
15174
15175        if (res) {
15176            final boolean killApp = (deleteFlags & PackageManager.DELETE_DONT_KILL_APP) == 0;
15177            info.sendPackageRemovedBroadcasts(killApp);
15178            info.sendSystemPackageUpdatedBroadcasts();
15179            info.sendSystemPackageAppearedBroadcasts();
15180        }
15181        // Force a gc here.
15182        Runtime.getRuntime().gc();
15183        // Delete the resources here after sending the broadcast to let
15184        // other processes clean up before deleting resources.
15185        if (info.args != null) {
15186            synchronized (mInstallLock) {
15187                info.args.doPostDeleteLI(true);
15188            }
15189        }
15190
15191        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
15192    }
15193
15194    class PackageRemovedInfo {
15195        String removedPackage;
15196        int uid = -1;
15197        int removedAppId = -1;
15198        int[] origUsers;
15199        int[] removedUsers = null;
15200        boolean isRemovedPackageSystemUpdate = false;
15201        boolean isUpdate;
15202        boolean dataRemoved;
15203        boolean removedForAllUsers;
15204        // Clean up resources deleted packages.
15205        InstallArgs args = null;
15206        ArrayMap<String, PackageRemovedInfo> removedChildPackages;
15207        ArrayMap<String, PackageInstalledInfo> appearedChildPackages;
15208
15209        void sendPackageRemovedBroadcasts(boolean killApp) {
15210            sendPackageRemovedBroadcastInternal(killApp);
15211            final int childCount = removedChildPackages != null ? removedChildPackages.size() : 0;
15212            for (int i = 0; i < childCount; i++) {
15213                PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
15214                childInfo.sendPackageRemovedBroadcastInternal(killApp);
15215            }
15216        }
15217
15218        void sendSystemPackageUpdatedBroadcasts() {
15219            if (isRemovedPackageSystemUpdate) {
15220                sendSystemPackageUpdatedBroadcastsInternal();
15221                final int childCount = (removedChildPackages != null)
15222                        ? removedChildPackages.size() : 0;
15223                for (int i = 0; i < childCount; i++) {
15224                    PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
15225                    if (childInfo.isRemovedPackageSystemUpdate) {
15226                        childInfo.sendSystemPackageUpdatedBroadcastsInternal();
15227                    }
15228                }
15229            }
15230        }
15231
15232        void sendSystemPackageAppearedBroadcasts() {
15233            final int packageCount = (appearedChildPackages != null)
15234                    ? appearedChildPackages.size() : 0;
15235            for (int i = 0; i < packageCount; i++) {
15236                PackageInstalledInfo installedInfo = appearedChildPackages.valueAt(i);
15237                for (int userId : installedInfo.newUsers) {
15238                    sendPackageAddedForUser(installedInfo.name, true,
15239                            UserHandle.getAppId(installedInfo.uid), userId);
15240                }
15241            }
15242        }
15243
15244        private void sendSystemPackageUpdatedBroadcastsInternal() {
15245            Bundle extras = new Bundle(2);
15246            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
15247            extras.putBoolean(Intent.EXTRA_REPLACING, true);
15248            sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, removedPackage,
15249                    extras, 0, null, null, null);
15250            sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, removedPackage,
15251                    extras, 0, null, null, null);
15252            sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null,
15253                    null, 0, removedPackage, null, null);
15254        }
15255
15256        private void sendPackageRemovedBroadcastInternal(boolean killApp) {
15257            Bundle extras = new Bundle(2);
15258            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0  ? removedAppId : uid);
15259            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, dataRemoved);
15260            extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, !killApp);
15261            if (isUpdate || isRemovedPackageSystemUpdate) {
15262                extras.putBoolean(Intent.EXTRA_REPLACING, true);
15263            }
15264            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
15265            if (removedPackage != null) {
15266                sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
15267                        extras, 0, null, null, removedUsers);
15268                if (dataRemoved && !isRemovedPackageSystemUpdate) {
15269                    sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED,
15270                            removedPackage, extras, 0, null, null, removedUsers);
15271                }
15272            }
15273            if (removedAppId >= 0) {
15274                sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, 0, null, null,
15275                        removedUsers);
15276            }
15277        }
15278    }
15279
15280    /*
15281     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
15282     * flag is not set, the data directory is removed as well.
15283     * make sure this flag is set for partially installed apps. If not its meaningless to
15284     * delete a partially installed application.
15285     */
15286    private void removePackageDataLIF(PackageSetting ps, int[] allUserHandles,
15287            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
15288        String packageName = ps.name;
15289        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
15290        // Retrieve object to delete permissions for shared user later on
15291        final PackageParser.Package deletedPkg;
15292        final PackageSetting deletedPs;
15293        // reader
15294        synchronized (mPackages) {
15295            deletedPkg = mPackages.get(packageName);
15296            deletedPs = mSettings.mPackages.get(packageName);
15297            if (outInfo != null) {
15298                outInfo.removedPackage = packageName;
15299                outInfo.removedUsers = deletedPs != null
15300                        ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true)
15301                        : null;
15302            }
15303        }
15304
15305        removePackageLI(ps, (flags & REMOVE_CHATTY) != 0);
15306
15307        if ((flags & PackageManager.DELETE_KEEP_DATA) == 0) {
15308            destroyAppDataLIF(deletedPkg, UserHandle.USER_ALL,
15309                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
15310            destroyAppProfilesLIF(deletedPkg);
15311            if (outInfo != null) {
15312                outInfo.dataRemoved = true;
15313            }
15314            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
15315        }
15316
15317        // writer
15318        synchronized (mPackages) {
15319            if (deletedPs != null) {
15320                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
15321                    clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL);
15322                    clearDefaultBrowserIfNeeded(packageName);
15323                    if (outInfo != null) {
15324                        mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
15325                        outInfo.removedAppId = mSettings.removePackageLPw(packageName);
15326                    }
15327                    updatePermissionsLPw(deletedPs.name, null, 0);
15328                    if (deletedPs.sharedUser != null) {
15329                        // Remove permissions associated with package. Since runtime
15330                        // permissions are per user we have to kill the removed package
15331                        // or packages running under the shared user of the removed
15332                        // package if revoking the permissions requested only by the removed
15333                        // package is successful and this causes a change in gids.
15334                        for (int userId : UserManagerService.getInstance().getUserIds()) {
15335                            final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs,
15336                                    userId);
15337                            if (userIdToKill == UserHandle.USER_ALL
15338                                    || userIdToKill >= UserHandle.USER_SYSTEM) {
15339                                // If gids changed for this user, kill all affected packages.
15340                                mHandler.post(new Runnable() {
15341                                    @Override
15342                                    public void run() {
15343                                        // This has to happen with no lock held.
15344                                        killApplication(deletedPs.name, deletedPs.appId,
15345                                                KILL_APP_REASON_GIDS_CHANGED);
15346                                    }
15347                                });
15348                                break;
15349                            }
15350                        }
15351                    }
15352                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
15353                }
15354                // make sure to preserve per-user disabled state if this removal was just
15355                // a downgrade of a system app to the factory package
15356                if (allUserHandles != null && outInfo != null && outInfo.origUsers != null) {
15357                    if (DEBUG_REMOVE) {
15358                        Slog.d(TAG, "Propagating install state across downgrade");
15359                    }
15360                    for (int userId : allUserHandles) {
15361                        final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
15362                        if (DEBUG_REMOVE) {
15363                            Slog.d(TAG, "    user " + userId + " => " + installed);
15364                        }
15365                        ps.setInstalled(installed, userId);
15366                    }
15367                }
15368            }
15369            // can downgrade to reader
15370            if (writeSettings) {
15371                // Save settings now
15372                mSettings.writeLPr();
15373            }
15374        }
15375        if (outInfo != null) {
15376            // A user ID was deleted here. Go through all users and remove it
15377            // from KeyStore.
15378            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId);
15379        }
15380    }
15381
15382    static boolean locationIsPrivileged(File path) {
15383        try {
15384            final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
15385                    .getCanonicalPath();
15386            return path.getCanonicalPath().startsWith(privilegedAppDir);
15387        } catch (IOException e) {
15388            Slog.e(TAG, "Unable to access code path " + path);
15389        }
15390        return false;
15391    }
15392
15393    /*
15394     * Tries to delete system package.
15395     */
15396    private boolean deleteSystemPackageLIF(PackageParser.Package deletedPkg,
15397            PackageSetting deletedPs, int[] allUserHandles, int flags, PackageRemovedInfo outInfo,
15398            boolean writeSettings) {
15399        if (deletedPs.parentPackageName != null) {
15400            Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName);
15401            return false;
15402        }
15403
15404        final boolean applyUserRestrictions
15405                = (allUserHandles != null) && (outInfo.origUsers != null);
15406        final PackageSetting disabledPs;
15407        // Confirm if the system package has been updated
15408        // An updated system app can be deleted. This will also have to restore
15409        // the system pkg from system partition
15410        // reader
15411        synchronized (mPackages) {
15412            disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPs.name);
15413        }
15414
15415        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName
15416                + " disabledPs=" + disabledPs);
15417
15418        if (disabledPs == null) {
15419            Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName);
15420            return false;
15421        } else if (DEBUG_REMOVE) {
15422            Slog.d(TAG, "Deleting system pkg from data partition");
15423        }
15424
15425        if (DEBUG_REMOVE) {
15426            if (applyUserRestrictions) {
15427                Slog.d(TAG, "Remembering install states:");
15428                for (int userId : allUserHandles) {
15429                    final boolean finstalled = ArrayUtils.contains(outInfo.origUsers, userId);
15430                    Slog.d(TAG, "   u=" + userId + " inst=" + finstalled);
15431                }
15432            }
15433        }
15434
15435        // Delete the updated package
15436        outInfo.isRemovedPackageSystemUpdate = true;
15437        if (outInfo.removedChildPackages != null) {
15438            final int childCount = (deletedPs.childPackageNames != null)
15439                    ? deletedPs.childPackageNames.size() : 0;
15440            for (int i = 0; i < childCount; i++) {
15441                String childPackageName = deletedPs.childPackageNames.get(i);
15442                if (disabledPs.childPackageNames != null && disabledPs.childPackageNames
15443                        .contains(childPackageName)) {
15444                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
15445                            childPackageName);
15446                    if (childInfo != null) {
15447                        childInfo.isRemovedPackageSystemUpdate = true;
15448                    }
15449                }
15450            }
15451        }
15452
15453        if (disabledPs.versionCode < deletedPs.versionCode) {
15454            // Delete data for downgrades
15455            flags &= ~PackageManager.DELETE_KEEP_DATA;
15456        } else {
15457            // Preserve data by setting flag
15458            flags |= PackageManager.DELETE_KEEP_DATA;
15459        }
15460
15461        boolean ret = deleteInstalledPackageLIF(deletedPs, true, flags, allUserHandles,
15462                outInfo, writeSettings, disabledPs.pkg);
15463        if (!ret) {
15464            return false;
15465        }
15466
15467        // writer
15468        synchronized (mPackages) {
15469            // Reinstate the old system package
15470            enableSystemPackageLPw(disabledPs.pkg);
15471            // Remove any native libraries from the upgraded package.
15472            removeNativeBinariesLI(deletedPs);
15473        }
15474
15475        // Install the system package
15476        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
15477        int parseFlags = mDefParseFlags
15478                | PackageParser.PARSE_MUST_BE_APK
15479                | PackageParser.PARSE_IS_SYSTEM
15480                | PackageParser.PARSE_IS_SYSTEM_DIR;
15481        if (locationIsPrivileged(disabledPs.codePath)) {
15482            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
15483        }
15484
15485        final PackageParser.Package newPkg;
15486        try {
15487            newPkg = scanPackageTracedLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null);
15488        } catch (PackageManagerException e) {
15489            Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": "
15490                    + e.getMessage());
15491            return false;
15492        }
15493
15494        prepareAppDataAfterInstallLIF(newPkg);
15495
15496        // writer
15497        synchronized (mPackages) {
15498            PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
15499
15500            // Propagate the permissions state as we do not want to drop on the floor
15501            // runtime permissions. The update permissions method below will take
15502            // care of removing obsolete permissions and grant install permissions.
15503            ps.getPermissionsState().copyFrom(deletedPs.getPermissionsState());
15504            updatePermissionsLPw(newPkg.packageName, newPkg,
15505                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
15506
15507            if (applyUserRestrictions) {
15508                if (DEBUG_REMOVE) {
15509                    Slog.d(TAG, "Propagating install state across reinstall");
15510                }
15511                for (int userId : allUserHandles) {
15512                    final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
15513                    if (DEBUG_REMOVE) {
15514                        Slog.d(TAG, "    user " + userId + " => " + installed);
15515                    }
15516                    ps.setInstalled(installed, userId);
15517
15518                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
15519                }
15520                // Regardless of writeSettings we need to ensure that this restriction
15521                // state propagation is persisted
15522                mSettings.writeAllUsersPackageRestrictionsLPr();
15523            }
15524            // can downgrade to reader here
15525            if (writeSettings) {
15526                mSettings.writeLPr();
15527            }
15528        }
15529        return true;
15530    }
15531
15532    private boolean deleteInstalledPackageLIF(PackageSetting ps,
15533            boolean deleteCodeAndResources, int flags, int[] allUserHandles,
15534            PackageRemovedInfo outInfo, boolean writeSettings,
15535            PackageParser.Package replacingPackage) {
15536        synchronized (mPackages) {
15537            if (outInfo != null) {
15538                outInfo.uid = ps.appId;
15539            }
15540
15541            if (outInfo != null && outInfo.removedChildPackages != null) {
15542                final int childCount = (ps.childPackageNames != null)
15543                        ? ps.childPackageNames.size() : 0;
15544                for (int i = 0; i < childCount; i++) {
15545                    String childPackageName = ps.childPackageNames.get(i);
15546                    PackageSetting childPs = mSettings.mPackages.get(childPackageName);
15547                    if (childPs == null) {
15548                        return false;
15549                    }
15550                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
15551                            childPackageName);
15552                    if (childInfo != null) {
15553                        childInfo.uid = childPs.appId;
15554                    }
15555                }
15556            }
15557        }
15558
15559        // Delete package data from internal structures and also remove data if flag is set
15560        removePackageDataLIF(ps, allUserHandles, outInfo, flags, writeSettings);
15561
15562        // Delete the child packages data
15563        final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
15564        for (int i = 0; i < childCount; i++) {
15565            PackageSetting childPs;
15566            synchronized (mPackages) {
15567                childPs = mSettings.peekPackageLPr(ps.childPackageNames.get(i));
15568            }
15569            if (childPs != null) {
15570                PackageRemovedInfo childOutInfo = (outInfo != null
15571                        && outInfo.removedChildPackages != null)
15572                        ? outInfo.removedChildPackages.get(childPs.name) : null;
15573                final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0
15574                        && (replacingPackage != null
15575                        && !replacingPackage.hasChildPackage(childPs.name))
15576                        ? flags & ~DELETE_KEEP_DATA : flags;
15577                removePackageDataLIF(childPs, allUserHandles, childOutInfo,
15578                        deleteFlags, writeSettings);
15579            }
15580        }
15581
15582        // Delete application code and resources only for parent packages
15583        if (ps.parentPackageName == null) {
15584            if (deleteCodeAndResources && (outInfo != null)) {
15585                outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
15586                        ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
15587                if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
15588            }
15589        }
15590
15591        return true;
15592    }
15593
15594    @Override
15595    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
15596            int userId) {
15597        mContext.enforceCallingOrSelfPermission(
15598                android.Manifest.permission.DELETE_PACKAGES, null);
15599        synchronized (mPackages) {
15600            PackageSetting ps = mSettings.mPackages.get(packageName);
15601            if (ps == null) {
15602                Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName);
15603                return false;
15604            }
15605            if (!ps.getInstalled(userId)) {
15606                // Can't block uninstall for an app that is not installed or enabled.
15607                Log.i(TAG, "Package not installed in set block uninstall " + packageName);
15608                return false;
15609            }
15610            ps.setBlockUninstall(blockUninstall, userId);
15611            mSettings.writePackageRestrictionsLPr(userId);
15612        }
15613        return true;
15614    }
15615
15616    @Override
15617    public boolean getBlockUninstallForUser(String packageName, int userId) {
15618        synchronized (mPackages) {
15619            PackageSetting ps = mSettings.mPackages.get(packageName);
15620            if (ps == null) {
15621                Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName);
15622                return false;
15623            }
15624            return ps.getBlockUninstall(userId);
15625        }
15626    }
15627
15628    @Override
15629    public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) {
15630        int callingUid = Binder.getCallingUid();
15631        if (callingUid != Process.SYSTEM_UID && callingUid != Process.ROOT_UID) {
15632            throw new SecurityException(
15633                    "setRequiredForSystemUser can only be run by the system or root");
15634        }
15635        synchronized (mPackages) {
15636            PackageSetting ps = mSettings.mPackages.get(packageName);
15637            if (ps == null) {
15638                Log.w(TAG, "Package doesn't exist: " + packageName);
15639                return false;
15640            }
15641            if (systemUserApp) {
15642                ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
15643            } else {
15644                ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
15645            }
15646            mSettings.writeLPr();
15647        }
15648        return true;
15649    }
15650
15651    /*
15652     * This method handles package deletion in general
15653     */
15654    private boolean deletePackageLIF(String packageName, UserHandle user,
15655            boolean deleteCodeAndResources, int[] allUserHandles, int flags,
15656            PackageRemovedInfo outInfo, boolean writeSettings,
15657            PackageParser.Package replacingPackage) {
15658        if (packageName == null) {
15659            Slog.w(TAG, "Attempt to delete null packageName.");
15660            return false;
15661        }
15662
15663        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
15664
15665        PackageSetting ps;
15666
15667        synchronized (mPackages) {
15668            ps = mSettings.mPackages.get(packageName);
15669            if (ps == null) {
15670                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
15671                return false;
15672            }
15673
15674            if (ps.parentPackageName != null && (!isSystemApp(ps)
15675                    || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) {
15676                if (DEBUG_REMOVE) {
15677                    Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:"
15678                            + ((user == null) ? UserHandle.USER_ALL : user));
15679                }
15680                final int removedUserId = (user != null) ? user.getIdentifier()
15681                        : UserHandle.USER_ALL;
15682                if (!clearPackageStateForUserLIF(ps, removedUserId, outInfo)) {
15683                    return false;
15684                }
15685                markPackageUninstalledForUserLPw(ps, user);
15686                scheduleWritePackageRestrictionsLocked(user);
15687                return true;
15688            }
15689        }
15690
15691        if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
15692                && user.getIdentifier() != UserHandle.USER_ALL)) {
15693            // The caller is asking that the package only be deleted for a single
15694            // user.  To do this, we just mark its uninstalled state and delete
15695            // its data. If this is a system app, we only allow this to happen if
15696            // they have set the special DELETE_SYSTEM_APP which requests different
15697            // semantics than normal for uninstalling system apps.
15698            markPackageUninstalledForUserLPw(ps, user);
15699
15700            if (!isSystemApp(ps)) {
15701                // Do not uninstall the APK if an app should be cached
15702                boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName);
15703                if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) {
15704                    // Other user still have this package installed, so all
15705                    // we need to do is clear this user's data and save that
15706                    // it is uninstalled.
15707                    if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
15708                    if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
15709                        return false;
15710                    }
15711                    scheduleWritePackageRestrictionsLocked(user);
15712                    return true;
15713                } else {
15714                    // We need to set it back to 'installed' so the uninstall
15715                    // broadcasts will be sent correctly.
15716                    if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
15717                    ps.setInstalled(true, user.getIdentifier());
15718                }
15719            } else {
15720                // This is a system app, so we assume that the
15721                // other users still have this package installed, so all
15722                // we need to do is clear this user's data and save that
15723                // it is uninstalled.
15724                if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
15725                if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
15726                    return false;
15727                }
15728                scheduleWritePackageRestrictionsLocked(user);
15729                return true;
15730            }
15731        }
15732
15733        // If we are deleting a composite package for all users, keep track
15734        // of result for each child.
15735        if (ps.childPackageNames != null && outInfo != null) {
15736            synchronized (mPackages) {
15737                final int childCount = ps.childPackageNames.size();
15738                outInfo.removedChildPackages = new ArrayMap<>(childCount);
15739                for (int i = 0; i < childCount; i++) {
15740                    String childPackageName = ps.childPackageNames.get(i);
15741                    PackageRemovedInfo childInfo = new PackageRemovedInfo();
15742                    childInfo.removedPackage = childPackageName;
15743                    outInfo.removedChildPackages.put(childPackageName, childInfo);
15744                    PackageSetting childPs = mSettings.peekPackageLPr(childPackageName);
15745                    if (childPs != null) {
15746                        childInfo.origUsers = childPs.queryInstalledUsers(allUserHandles, true);
15747                    }
15748                }
15749            }
15750        }
15751
15752        boolean ret = false;
15753        if (isSystemApp(ps)) {
15754            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name);
15755            // When an updated system application is deleted we delete the existing resources
15756            // as well and fall back to existing code in system partition
15757            ret = deleteSystemPackageLIF(ps.pkg, ps, allUserHandles, flags, outInfo, writeSettings);
15758        } else {
15759            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name);
15760            ret = deleteInstalledPackageLIF(ps, deleteCodeAndResources, flags, allUserHandles,
15761                    outInfo, writeSettings, replacingPackage);
15762        }
15763
15764        // Take a note whether we deleted the package for all users
15765        if (outInfo != null) {
15766            outInfo.removedForAllUsers = mPackages.get(ps.name) == null;
15767            if (outInfo.removedChildPackages != null) {
15768                synchronized (mPackages) {
15769                    final int childCount = outInfo.removedChildPackages.size();
15770                    for (int i = 0; i < childCount; i++) {
15771                        PackageRemovedInfo childInfo = outInfo.removedChildPackages.valueAt(i);
15772                        if (childInfo != null) {
15773                            childInfo.removedForAllUsers = mPackages.get(
15774                                    childInfo.removedPackage) == null;
15775                        }
15776                    }
15777                }
15778            }
15779            // If we uninstalled an update to a system app there may be some
15780            // child packages that appeared as they are declared in the system
15781            // app but were not declared in the update.
15782            if (isSystemApp(ps)) {
15783                synchronized (mPackages) {
15784                    PackageSetting updatedPs = mSettings.peekPackageLPr(ps.name);
15785                    final int childCount = (updatedPs.childPackageNames != null)
15786                            ? updatedPs.childPackageNames.size() : 0;
15787                    for (int i = 0; i < childCount; i++) {
15788                        String childPackageName = updatedPs.childPackageNames.get(i);
15789                        if (outInfo.removedChildPackages == null
15790                                || outInfo.removedChildPackages.indexOfKey(childPackageName) < 0) {
15791                            PackageSetting childPs = mSettings.peekPackageLPr(childPackageName);
15792                            if (childPs == null) {
15793                                continue;
15794                            }
15795                            PackageInstalledInfo installRes = new PackageInstalledInfo();
15796                            installRes.name = childPackageName;
15797                            installRes.newUsers = childPs.queryInstalledUsers(allUserHandles, true);
15798                            installRes.pkg = mPackages.get(childPackageName);
15799                            installRes.uid = childPs.pkg.applicationInfo.uid;
15800                            if (outInfo.appearedChildPackages == null) {
15801                                outInfo.appearedChildPackages = new ArrayMap<>();
15802                            }
15803                            outInfo.appearedChildPackages.put(childPackageName, installRes);
15804                        }
15805                    }
15806                }
15807            }
15808        }
15809
15810        return ret;
15811    }
15812
15813    private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) {
15814        final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL)
15815                ? sUserManager.getUserIds() : new int[] {user.getIdentifier()};
15816        for (int nextUserId : userIds) {
15817            if (DEBUG_REMOVE) {
15818                Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId);
15819            }
15820            ps.setUserState(nextUserId, 0, COMPONENT_ENABLED_STATE_DEFAULT,
15821                    false /*installed*/, true /*stopped*/, true /*notLaunched*/,
15822                    false /*hidden*/, false /*suspended*/, null, null, null,
15823                    false /*blockUninstall*/,
15824                    ps.readUserState(nextUserId).domainVerificationStatus, 0);
15825        }
15826    }
15827
15828    private boolean clearPackageStateForUserLIF(PackageSetting ps, int userId,
15829            PackageRemovedInfo outInfo) {
15830        final PackageParser.Package pkg;
15831        synchronized (mPackages) {
15832            pkg = mPackages.get(ps.name);
15833        }
15834
15835        final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds()
15836                : new int[] {userId};
15837        for (int nextUserId : userIds) {
15838            if (DEBUG_REMOVE) {
15839                Slog.d(TAG, "Updating package:" + ps.name + " install state for user:"
15840                        + nextUserId);
15841            }
15842
15843            destroyAppDataLIF(pkg, userId,
15844                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
15845            removeKeystoreDataIfNeeded(nextUserId, ps.appId);
15846            schedulePackageCleaning(ps.name, nextUserId, false);
15847            synchronized (mPackages) {
15848                if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) {
15849                    scheduleWritePackageRestrictionsLocked(nextUserId);
15850                }
15851                resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId);
15852            }
15853        }
15854
15855        if (outInfo != null) {
15856            outInfo.removedPackage = ps.name;
15857            outInfo.removedAppId = ps.appId;
15858            outInfo.removedUsers = userIds;
15859        }
15860
15861        return true;
15862    }
15863
15864    private final class ClearStorageConnection implements ServiceConnection {
15865        IMediaContainerService mContainerService;
15866
15867        @Override
15868        public void onServiceConnected(ComponentName name, IBinder service) {
15869            synchronized (this) {
15870                mContainerService = IMediaContainerService.Stub.asInterface(service);
15871                notifyAll();
15872            }
15873        }
15874
15875        @Override
15876        public void onServiceDisconnected(ComponentName name) {
15877        }
15878    }
15879
15880    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
15881        if (DEFAULT_CONTAINER_PACKAGE.equals(packageName)) return;
15882
15883        final boolean mounted;
15884        if (Environment.isExternalStorageEmulated()) {
15885            mounted = true;
15886        } else {
15887            final String status = Environment.getExternalStorageState();
15888
15889            mounted = status.equals(Environment.MEDIA_MOUNTED)
15890                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
15891        }
15892
15893        if (!mounted) {
15894            return;
15895        }
15896
15897        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
15898        int[] users;
15899        if (userId == UserHandle.USER_ALL) {
15900            users = sUserManager.getUserIds();
15901        } else {
15902            users = new int[] { userId };
15903        }
15904        final ClearStorageConnection conn = new ClearStorageConnection();
15905        if (mContext.bindServiceAsUser(
15906                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
15907            try {
15908                for (int curUser : users) {
15909                    long timeout = SystemClock.uptimeMillis() + 5000;
15910                    synchronized (conn) {
15911                        long now = SystemClock.uptimeMillis();
15912                        while (conn.mContainerService == null && now < timeout) {
15913                            try {
15914                                conn.wait(timeout - now);
15915                            } catch (InterruptedException e) {
15916                            }
15917                        }
15918                    }
15919                    if (conn.mContainerService == null) {
15920                        return;
15921                    }
15922
15923                    final UserEnvironment userEnv = new UserEnvironment(curUser);
15924                    clearDirectory(conn.mContainerService,
15925                            userEnv.buildExternalStorageAppCacheDirs(packageName));
15926                    if (allData) {
15927                        clearDirectory(conn.mContainerService,
15928                                userEnv.buildExternalStorageAppDataDirs(packageName));
15929                        clearDirectory(conn.mContainerService,
15930                                userEnv.buildExternalStorageAppMediaDirs(packageName));
15931                    }
15932                }
15933            } finally {
15934                mContext.unbindService(conn);
15935            }
15936        }
15937    }
15938
15939    @Override
15940    public void clearApplicationProfileData(String packageName) {
15941        enforceSystemOrRoot("Only the system can clear all profile data");
15942
15943        final PackageParser.Package pkg;
15944        synchronized (mPackages) {
15945            pkg = mPackages.get(packageName);
15946        }
15947
15948        try (PackageFreezer freezer = freezePackage(packageName, "clearApplicationProfileData")) {
15949            synchronized (mInstallLock) {
15950                clearAppProfilesLIF(pkg);
15951            }
15952        }
15953    }
15954
15955    @Override
15956    public void clearApplicationUserData(final String packageName,
15957            final IPackageDataObserver observer, final int userId) {
15958        mContext.enforceCallingOrSelfPermission(
15959                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
15960
15961        enforceCrossUserPermission(Binder.getCallingUid(), userId,
15962                true /* requireFullPermission */, false /* checkShell */, "clear application data");
15963
15964        final DevicePolicyManagerInternal dpmi = LocalServices
15965                .getService(DevicePolicyManagerInternal.class);
15966        if (dpmi != null && dpmi.hasDeviceOwnerOrProfileOwner(packageName, userId)) {
15967            throw new SecurityException("Cannot clear data for a device owner or a profile owner");
15968        }
15969        // Queue up an async operation since the package deletion may take a little while.
15970        mHandler.post(new Runnable() {
15971            public void run() {
15972                mHandler.removeCallbacks(this);
15973                final boolean succeeded;
15974                try (PackageFreezer freezer = freezePackage(packageName,
15975                        "clearApplicationUserData")) {
15976                    synchronized (mInstallLock) {
15977                        succeeded = clearApplicationUserDataLIF(packageName, userId);
15978                    }
15979                    clearExternalStorageDataSync(packageName, userId, true);
15980                }
15981                if (succeeded) {
15982                    // invoke DeviceStorageMonitor's update method to clear any notifications
15983                    DeviceStorageMonitorInternal dsm = LocalServices
15984                            .getService(DeviceStorageMonitorInternal.class);
15985                    if (dsm != null) {
15986                        dsm.checkMemory();
15987                    }
15988                }
15989                if(observer != null) {
15990                    try {
15991                        observer.onRemoveCompleted(packageName, succeeded);
15992                    } catch (RemoteException e) {
15993                        Log.i(TAG, "Observer no longer exists.");
15994                    }
15995                } //end if observer
15996            } //end run
15997        });
15998    }
15999
16000    private boolean clearApplicationUserDataLIF(String packageName, int userId) {
16001        if (packageName == null) {
16002            Slog.w(TAG, "Attempt to delete null packageName.");
16003            return false;
16004        }
16005
16006        // Try finding details about the requested package
16007        PackageParser.Package pkg;
16008        synchronized (mPackages) {
16009            pkg = mPackages.get(packageName);
16010            if (pkg == null) {
16011                final PackageSetting ps = mSettings.mPackages.get(packageName);
16012                if (ps != null) {
16013                    pkg = ps.pkg;
16014                }
16015            }
16016
16017            if (pkg == null) {
16018                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
16019                return false;
16020            }
16021
16022            PackageSetting ps = (PackageSetting) pkg.mExtras;
16023            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
16024        }
16025
16026        clearAppDataLIF(pkg, userId,
16027                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
16028
16029        final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
16030        removeKeystoreDataIfNeeded(userId, appId);
16031
16032        final UserManager um = mContext.getSystemService(UserManager.class);
16033        final int flags;
16034        if (um.isUserUnlocked(userId)) {
16035            flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
16036        } else if (um.isUserRunning(userId)) {
16037            flags = StorageManager.FLAG_STORAGE_DE;
16038        } else {
16039            flags = 0;
16040        }
16041        prepareAppDataContentsLIF(pkg, userId, flags);
16042
16043        return true;
16044    }
16045
16046    /**
16047     * Reverts user permission state changes (permissions and flags) in
16048     * all packages for a given user.
16049     *
16050     * @param userId The device user for which to do a reset.
16051     */
16052    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) {
16053        final int packageCount = mPackages.size();
16054        for (int i = 0; i < packageCount; i++) {
16055            PackageParser.Package pkg = mPackages.valueAt(i);
16056            PackageSetting ps = (PackageSetting) pkg.mExtras;
16057            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
16058        }
16059    }
16060
16061    /**
16062     * Reverts user permission state changes (permissions and flags).
16063     *
16064     * @param ps The package for which to reset.
16065     * @param userId The device user for which to do a reset.
16066     */
16067    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(
16068            final PackageSetting ps, final int userId) {
16069        if (ps.pkg == null) {
16070            return;
16071        }
16072
16073        // These are flags that can change base on user actions.
16074        final int userSettableMask = FLAG_PERMISSION_USER_SET
16075                | FLAG_PERMISSION_USER_FIXED
16076                | FLAG_PERMISSION_REVOKE_ON_UPGRADE
16077                | FLAG_PERMISSION_REVIEW_REQUIRED;
16078
16079        final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED
16080                | FLAG_PERMISSION_POLICY_FIXED;
16081
16082        boolean writeInstallPermissions = false;
16083        boolean writeRuntimePermissions = false;
16084
16085        final int permissionCount = ps.pkg.requestedPermissions.size();
16086        for (int i = 0; i < permissionCount; i++) {
16087            String permission = ps.pkg.requestedPermissions.get(i);
16088
16089            BasePermission bp = mSettings.mPermissions.get(permission);
16090            if (bp == null) {
16091                continue;
16092            }
16093
16094            // If shared user we just reset the state to which only this app contributed.
16095            if (ps.sharedUser != null) {
16096                boolean used = false;
16097                final int packageCount = ps.sharedUser.packages.size();
16098                for (int j = 0; j < packageCount; j++) {
16099                    PackageSetting pkg = ps.sharedUser.packages.valueAt(j);
16100                    if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName)
16101                            && pkg.pkg.requestedPermissions.contains(permission)) {
16102                        used = true;
16103                        break;
16104                    }
16105                }
16106                if (used) {
16107                    continue;
16108                }
16109            }
16110
16111            PermissionsState permissionsState = ps.getPermissionsState();
16112
16113            final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId);
16114
16115            // Always clear the user settable flags.
16116            final boolean hasInstallState = permissionsState.getInstallPermissionState(
16117                    bp.name) != null;
16118            // If permission review is enabled and this is a legacy app, mark the
16119            // permission as requiring a review as this is the initial state.
16120            int flags = 0;
16121            if (Build.PERMISSIONS_REVIEW_REQUIRED
16122                    && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
16123                flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
16124            }
16125            if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) {
16126                if (hasInstallState) {
16127                    writeInstallPermissions = true;
16128                } else {
16129                    writeRuntimePermissions = true;
16130                }
16131            }
16132
16133            // Below is only runtime permission handling.
16134            if (!bp.isRuntime()) {
16135                continue;
16136            }
16137
16138            // Never clobber system or policy.
16139            if ((oldFlags & policyOrSystemFlags) != 0) {
16140                continue;
16141            }
16142
16143            // If this permission was granted by default, make sure it is.
16144            if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) {
16145                if (permissionsState.grantRuntimePermission(bp, userId)
16146                        != PERMISSION_OPERATION_FAILURE) {
16147                    writeRuntimePermissions = true;
16148                }
16149            // If permission review is enabled the permissions for a legacy apps
16150            // are represented as constantly granted runtime ones, so don't revoke.
16151            } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
16152                // Otherwise, reset the permission.
16153                final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId);
16154                switch (revokeResult) {
16155                    case PERMISSION_OPERATION_SUCCESS:
16156                    case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
16157                        writeRuntimePermissions = true;
16158                        final int appId = ps.appId;
16159                        mHandler.post(new Runnable() {
16160                            @Override
16161                            public void run() {
16162                                killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
16163                            }
16164                        });
16165                    } break;
16166                }
16167            }
16168        }
16169
16170        // Synchronously write as we are taking permissions away.
16171        if (writeRuntimePermissions) {
16172            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
16173        }
16174
16175        // Synchronously write as we are taking permissions away.
16176        if (writeInstallPermissions) {
16177            mSettings.writeLPr();
16178        }
16179    }
16180
16181    /**
16182     * Remove entries from the keystore daemon. Will only remove it if the
16183     * {@code appId} is valid.
16184     */
16185    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
16186        if (appId < 0) {
16187            return;
16188        }
16189
16190        final KeyStore keyStore = KeyStore.getInstance();
16191        if (keyStore != null) {
16192            if (userId == UserHandle.USER_ALL) {
16193                for (final int individual : sUserManager.getUserIds()) {
16194                    keyStore.clearUid(UserHandle.getUid(individual, appId));
16195                }
16196            } else {
16197                keyStore.clearUid(UserHandle.getUid(userId, appId));
16198            }
16199        } else {
16200            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
16201        }
16202    }
16203
16204    @Override
16205    public void deleteApplicationCacheFiles(final String packageName,
16206            final IPackageDataObserver observer) {
16207        final int userId = UserHandle.getCallingUserId();
16208        deleteApplicationCacheFilesAsUser(packageName, userId, observer);
16209    }
16210
16211    @Override
16212    public void deleteApplicationCacheFilesAsUser(final String packageName, final int userId,
16213            final IPackageDataObserver observer) {
16214        mContext.enforceCallingOrSelfPermission(
16215                android.Manifest.permission.DELETE_CACHE_FILES, null);
16216        enforceCrossUserPermission(Binder.getCallingUid(), userId,
16217                /* requireFullPermission= */ true, /* checkShell= */ false,
16218                "delete application cache files");
16219
16220        final PackageParser.Package pkg;
16221        synchronized (mPackages) {
16222            pkg = mPackages.get(packageName);
16223        }
16224
16225        // Queue up an async operation since the package deletion may take a little while.
16226        mHandler.post(new Runnable() {
16227            public void run() {
16228                synchronized (mInstallLock) {
16229                    final int flags = StorageManager.FLAG_STORAGE_DE
16230                            | StorageManager.FLAG_STORAGE_CE;
16231                    // We're only clearing cache files, so we don't care if the
16232                    // app is unfrozen and still able to run
16233                    clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CACHE_ONLY);
16234                    clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
16235                }
16236                clearExternalStorageDataSync(packageName, userId, false);
16237                if (observer != null) {
16238                    try {
16239                        observer.onRemoveCompleted(packageName, true);
16240                    } catch (RemoteException e) {
16241                        Log.i(TAG, "Observer no longer exists.");
16242                    }
16243                }
16244            }
16245        });
16246    }
16247
16248    @Override
16249    public void getPackageSizeInfo(final String packageName, int userHandle,
16250            final IPackageStatsObserver observer) {
16251        mContext.enforceCallingOrSelfPermission(
16252                android.Manifest.permission.GET_PACKAGE_SIZE, null);
16253        if (packageName == null) {
16254            throw new IllegalArgumentException("Attempt to get size of null packageName");
16255        }
16256
16257        PackageStats stats = new PackageStats(packageName, userHandle);
16258
16259        /*
16260         * Queue up an async operation since the package measurement may take a
16261         * little while.
16262         */
16263        Message msg = mHandler.obtainMessage(INIT_COPY);
16264        msg.obj = new MeasureParams(stats, observer);
16265        mHandler.sendMessage(msg);
16266    }
16267
16268    private boolean getPackageSizeInfoLI(String packageName, int userId, PackageStats stats) {
16269        final PackageSetting ps;
16270        synchronized (mPackages) {
16271            ps = mSettings.mPackages.get(packageName);
16272            if (ps == null) {
16273                Slog.w(TAG, "Failed to find settings for " + packageName);
16274                return false;
16275            }
16276        }
16277        try {
16278            mInstaller.getAppSize(ps.volumeUuid, packageName, userId,
16279                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE,
16280                    ps.getCeDataInode(userId), ps.codePathString, stats);
16281        } catch (InstallerException e) {
16282            Slog.w(TAG, String.valueOf(e));
16283            return false;
16284        }
16285
16286        // For now, ignore code size of packages on system partition
16287        if (isSystemApp(ps) && !isUpdatedSystemApp(ps)) {
16288            stats.codeSize = 0;
16289        }
16290
16291        return true;
16292    }
16293
16294    private int getUidTargetSdkVersionLockedLPr(int uid) {
16295        Object obj = mSettings.getUserIdLPr(uid);
16296        if (obj instanceof SharedUserSetting) {
16297            final SharedUserSetting sus = (SharedUserSetting) obj;
16298            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
16299            final Iterator<PackageSetting> it = sus.packages.iterator();
16300            while (it.hasNext()) {
16301                final PackageSetting ps = it.next();
16302                if (ps.pkg != null) {
16303                    int v = ps.pkg.applicationInfo.targetSdkVersion;
16304                    if (v < vers) vers = v;
16305                }
16306            }
16307            return vers;
16308        } else if (obj instanceof PackageSetting) {
16309            final PackageSetting ps = (PackageSetting) obj;
16310            if (ps.pkg != null) {
16311                return ps.pkg.applicationInfo.targetSdkVersion;
16312            }
16313        }
16314        return Build.VERSION_CODES.CUR_DEVELOPMENT;
16315    }
16316
16317    @Override
16318    public void addPreferredActivity(IntentFilter filter, int match,
16319            ComponentName[] set, ComponentName activity, int userId) {
16320        addPreferredActivityInternal(filter, match, set, activity, true, userId,
16321                "Adding preferred");
16322    }
16323
16324    private void addPreferredActivityInternal(IntentFilter filter, int match,
16325            ComponentName[] set, ComponentName activity, boolean always, int userId,
16326            String opname) {
16327        // writer
16328        int callingUid = Binder.getCallingUid();
16329        enforceCrossUserPermission(callingUid, userId,
16330                true /* requireFullPermission */, false /* checkShell */, "add preferred activity");
16331        if (filter.countActions() == 0) {
16332            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
16333            return;
16334        }
16335        synchronized (mPackages) {
16336            if (mContext.checkCallingOrSelfPermission(
16337                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
16338                    != PackageManager.PERMISSION_GRANTED) {
16339                if (getUidTargetSdkVersionLockedLPr(callingUid)
16340                        < Build.VERSION_CODES.FROYO) {
16341                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
16342                            + callingUid);
16343                    return;
16344                }
16345                mContext.enforceCallingOrSelfPermission(
16346                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
16347            }
16348
16349            PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
16350            Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
16351                    + userId + ":");
16352            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
16353            pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
16354            scheduleWritePackageRestrictionsLocked(userId);
16355        }
16356    }
16357
16358    @Override
16359    public void replacePreferredActivity(IntentFilter filter, int match,
16360            ComponentName[] set, ComponentName activity, int userId) {
16361        if (filter.countActions() != 1) {
16362            throw new IllegalArgumentException(
16363                    "replacePreferredActivity expects filter to have only 1 action.");
16364        }
16365        if (filter.countDataAuthorities() != 0
16366                || filter.countDataPaths() != 0
16367                || filter.countDataSchemes() > 1
16368                || filter.countDataTypes() != 0) {
16369            throw new IllegalArgumentException(
16370                    "replacePreferredActivity expects filter to have no data authorities, " +
16371                    "paths, or types; and at most one scheme.");
16372        }
16373
16374        final int callingUid = Binder.getCallingUid();
16375        enforceCrossUserPermission(callingUid, userId,
16376                true /* requireFullPermission */, false /* checkShell */,
16377                "replace preferred activity");
16378        synchronized (mPackages) {
16379            if (mContext.checkCallingOrSelfPermission(
16380                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
16381                    != PackageManager.PERMISSION_GRANTED) {
16382                if (getUidTargetSdkVersionLockedLPr(callingUid)
16383                        < Build.VERSION_CODES.FROYO) {
16384                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
16385                            + Binder.getCallingUid());
16386                    return;
16387                }
16388                mContext.enforceCallingOrSelfPermission(
16389                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
16390            }
16391
16392            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
16393            if (pir != null) {
16394                // Get all of the existing entries that exactly match this filter.
16395                ArrayList<PreferredActivity> existing = pir.findFilters(filter);
16396                if (existing != null && existing.size() == 1) {
16397                    PreferredActivity cur = existing.get(0);
16398                    if (DEBUG_PREFERRED) {
16399                        Slog.i(TAG, "Checking replace of preferred:");
16400                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
16401                        if (!cur.mPref.mAlways) {
16402                            Slog.i(TAG, "  -- CUR; not mAlways!");
16403                        } else {
16404                            Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
16405                            Slog.i(TAG, "  -- CUR: mSet="
16406                                    + Arrays.toString(cur.mPref.mSetComponents));
16407                            Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
16408                            Slog.i(TAG, "  -- NEW: mMatch="
16409                                    + (match&IntentFilter.MATCH_CATEGORY_MASK));
16410                            Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
16411                            Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
16412                        }
16413                    }
16414                    if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
16415                            && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
16416                            && cur.mPref.sameSet(set)) {
16417                        // Setting the preferred activity to what it happens to be already
16418                        if (DEBUG_PREFERRED) {
16419                            Slog.i(TAG, "Replacing with same preferred activity "
16420                                    + cur.mPref.mShortComponent + " for user "
16421                                    + userId + ":");
16422                            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
16423                        }
16424                        return;
16425                    }
16426                }
16427
16428                if (existing != null) {
16429                    if (DEBUG_PREFERRED) {
16430                        Slog.i(TAG, existing.size() + " existing preferred matches for:");
16431                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
16432                    }
16433                    for (int i = 0; i < existing.size(); i++) {
16434                        PreferredActivity pa = existing.get(i);
16435                        if (DEBUG_PREFERRED) {
16436                            Slog.i(TAG, "Removing existing preferred activity "
16437                                    + pa.mPref.mComponent + ":");
16438                            pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
16439                        }
16440                        pir.removeFilter(pa);
16441                    }
16442                }
16443            }
16444            addPreferredActivityInternal(filter, match, set, activity, true, userId,
16445                    "Replacing preferred");
16446        }
16447    }
16448
16449    @Override
16450    public void clearPackagePreferredActivities(String packageName) {
16451        final int uid = Binder.getCallingUid();
16452        // writer
16453        synchronized (mPackages) {
16454            PackageParser.Package pkg = mPackages.get(packageName);
16455            if (pkg == null || pkg.applicationInfo.uid != uid) {
16456                if (mContext.checkCallingOrSelfPermission(
16457                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
16458                        != PackageManager.PERMISSION_GRANTED) {
16459                    if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid())
16460                            < Build.VERSION_CODES.FROYO) {
16461                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
16462                                + Binder.getCallingUid());
16463                        return;
16464                    }
16465                    mContext.enforceCallingOrSelfPermission(
16466                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
16467                }
16468            }
16469
16470            int user = UserHandle.getCallingUserId();
16471            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
16472                scheduleWritePackageRestrictionsLocked(user);
16473            }
16474        }
16475    }
16476
16477    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
16478    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
16479        ArrayList<PreferredActivity> removed = null;
16480        boolean changed = false;
16481        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
16482            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
16483            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
16484            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
16485                continue;
16486            }
16487            Iterator<PreferredActivity> it = pir.filterIterator();
16488            while (it.hasNext()) {
16489                PreferredActivity pa = it.next();
16490                // Mark entry for removal only if it matches the package name
16491                // and the entry is of type "always".
16492                if (packageName == null ||
16493                        (pa.mPref.mComponent.getPackageName().equals(packageName)
16494                                && pa.mPref.mAlways)) {
16495                    if (removed == null) {
16496                        removed = new ArrayList<PreferredActivity>();
16497                    }
16498                    removed.add(pa);
16499                }
16500            }
16501            if (removed != null) {
16502                for (int j=0; j<removed.size(); j++) {
16503                    PreferredActivity pa = removed.get(j);
16504                    pir.removeFilter(pa);
16505                }
16506                changed = true;
16507            }
16508        }
16509        return changed;
16510    }
16511
16512    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
16513    private void clearIntentFilterVerificationsLPw(int userId) {
16514        final int packageCount = mPackages.size();
16515        for (int i = 0; i < packageCount; i++) {
16516            PackageParser.Package pkg = mPackages.valueAt(i);
16517            clearIntentFilterVerificationsLPw(pkg.packageName, userId);
16518        }
16519    }
16520
16521    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
16522    void clearIntentFilterVerificationsLPw(String packageName, int userId) {
16523        if (userId == UserHandle.USER_ALL) {
16524            if (mSettings.removeIntentFilterVerificationLPw(packageName,
16525                    sUserManager.getUserIds())) {
16526                for (int oneUserId : sUserManager.getUserIds()) {
16527                    scheduleWritePackageRestrictionsLocked(oneUserId);
16528                }
16529            }
16530        } else {
16531            if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) {
16532                scheduleWritePackageRestrictionsLocked(userId);
16533            }
16534        }
16535    }
16536
16537    void clearDefaultBrowserIfNeeded(String packageName) {
16538        for (int oneUserId : sUserManager.getUserIds()) {
16539            String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId);
16540            if (TextUtils.isEmpty(defaultBrowserPackageName)) continue;
16541            if (packageName.equals(defaultBrowserPackageName)) {
16542                setDefaultBrowserPackageName(null, oneUserId);
16543            }
16544        }
16545    }
16546
16547    @Override
16548    public void resetApplicationPreferences(int userId) {
16549        mContext.enforceCallingOrSelfPermission(
16550                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
16551        // writer
16552        synchronized (mPackages) {
16553            final long identity = Binder.clearCallingIdentity();
16554            try {
16555                clearPackagePreferredActivitiesLPw(null, userId);
16556                mSettings.applyDefaultPreferredAppsLPw(this, userId);
16557                // TODO: We have to reset the default SMS and Phone. This requires
16558                // significant refactoring to keep all default apps in the package
16559                // manager (cleaner but more work) or have the services provide
16560                // callbacks to the package manager to request a default app reset.
16561                applyFactoryDefaultBrowserLPw(userId);
16562                clearIntentFilterVerificationsLPw(userId);
16563                primeDomainVerificationsLPw(userId);
16564                resetUserChangesToRuntimePermissionsAndFlagsLPw(userId);
16565                scheduleWritePackageRestrictionsLocked(userId);
16566            } finally {
16567                Binder.restoreCallingIdentity(identity);
16568            }
16569        }
16570    }
16571
16572    @Override
16573    public int getPreferredActivities(List<IntentFilter> outFilters,
16574            List<ComponentName> outActivities, String packageName) {
16575
16576        int num = 0;
16577        final int userId = UserHandle.getCallingUserId();
16578        // reader
16579        synchronized (mPackages) {
16580            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
16581            if (pir != null) {
16582                final Iterator<PreferredActivity> it = pir.filterIterator();
16583                while (it.hasNext()) {
16584                    final PreferredActivity pa = it.next();
16585                    if (packageName == null
16586                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
16587                                    && pa.mPref.mAlways)) {
16588                        if (outFilters != null) {
16589                            outFilters.add(new IntentFilter(pa));
16590                        }
16591                        if (outActivities != null) {
16592                            outActivities.add(pa.mPref.mComponent);
16593                        }
16594                    }
16595                }
16596            }
16597        }
16598
16599        return num;
16600    }
16601
16602    @Override
16603    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
16604            int userId) {
16605        int callingUid = Binder.getCallingUid();
16606        if (callingUid != Process.SYSTEM_UID) {
16607            throw new SecurityException(
16608                    "addPersistentPreferredActivity can only be run by the system");
16609        }
16610        if (filter.countActions() == 0) {
16611            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
16612            return;
16613        }
16614        synchronized (mPackages) {
16615            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
16616                    ":");
16617            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
16618            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
16619                    new PersistentPreferredActivity(filter, activity));
16620            scheduleWritePackageRestrictionsLocked(userId);
16621        }
16622    }
16623
16624    @Override
16625    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
16626        int callingUid = Binder.getCallingUid();
16627        if (callingUid != Process.SYSTEM_UID) {
16628            throw new SecurityException(
16629                    "clearPackagePersistentPreferredActivities can only be run by the system");
16630        }
16631        ArrayList<PersistentPreferredActivity> removed = null;
16632        boolean changed = false;
16633        synchronized (mPackages) {
16634            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
16635                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
16636                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
16637                        .valueAt(i);
16638                if (userId != thisUserId) {
16639                    continue;
16640                }
16641                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
16642                while (it.hasNext()) {
16643                    PersistentPreferredActivity ppa = it.next();
16644                    // Mark entry for removal only if it matches the package name.
16645                    if (ppa.mComponent.getPackageName().equals(packageName)) {
16646                        if (removed == null) {
16647                            removed = new ArrayList<PersistentPreferredActivity>();
16648                        }
16649                        removed.add(ppa);
16650                    }
16651                }
16652                if (removed != null) {
16653                    for (int j=0; j<removed.size(); j++) {
16654                        PersistentPreferredActivity ppa = removed.get(j);
16655                        ppir.removeFilter(ppa);
16656                    }
16657                    changed = true;
16658                }
16659            }
16660
16661            if (changed) {
16662                scheduleWritePackageRestrictionsLocked(userId);
16663            }
16664        }
16665    }
16666
16667    /**
16668     * Common machinery for picking apart a restored XML blob and passing
16669     * it to a caller-supplied functor to be applied to the running system.
16670     */
16671    private void restoreFromXml(XmlPullParser parser, int userId,
16672            String expectedStartTag, BlobXmlRestorer functor)
16673            throws IOException, XmlPullParserException {
16674        int type;
16675        while ((type = parser.next()) != XmlPullParser.START_TAG
16676                && type != XmlPullParser.END_DOCUMENT) {
16677        }
16678        if (type != XmlPullParser.START_TAG) {
16679            // oops didn't find a start tag?!
16680            if (DEBUG_BACKUP) {
16681                Slog.e(TAG, "Didn't find start tag during restore");
16682            }
16683            return;
16684        }
16685Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName());
16686        // this is supposed to be TAG_PREFERRED_BACKUP
16687        if (!expectedStartTag.equals(parser.getName())) {
16688            if (DEBUG_BACKUP) {
16689                Slog.e(TAG, "Found unexpected tag " + parser.getName());
16690            }
16691            return;
16692        }
16693
16694        // skip interfering stuff, then we're aligned with the backing implementation
16695        while ((type = parser.next()) == XmlPullParser.TEXT) { }
16696Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName());
16697        functor.apply(parser, userId);
16698    }
16699
16700    private interface BlobXmlRestorer {
16701        public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException;
16702    }
16703
16704    /**
16705     * Non-Binder method, support for the backup/restore mechanism: write the
16706     * full set of preferred activities in its canonical XML format.  Returns the
16707     * XML output as a byte array, or null if there is none.
16708     */
16709    @Override
16710    public byte[] getPreferredActivityBackup(int userId) {
16711        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
16712            throw new SecurityException("Only the system may call getPreferredActivityBackup()");
16713        }
16714
16715        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
16716        try {
16717            final XmlSerializer serializer = new FastXmlSerializer();
16718            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
16719            serializer.startDocument(null, true);
16720            serializer.startTag(null, TAG_PREFERRED_BACKUP);
16721
16722            synchronized (mPackages) {
16723                mSettings.writePreferredActivitiesLPr(serializer, userId, true);
16724            }
16725
16726            serializer.endTag(null, TAG_PREFERRED_BACKUP);
16727            serializer.endDocument();
16728            serializer.flush();
16729        } catch (Exception e) {
16730            if (DEBUG_BACKUP) {
16731                Slog.e(TAG, "Unable to write preferred activities for backup", e);
16732            }
16733            return null;
16734        }
16735
16736        return dataStream.toByteArray();
16737    }
16738
16739    @Override
16740    public void restorePreferredActivities(byte[] backup, int userId) {
16741        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
16742            throw new SecurityException("Only the system may call restorePreferredActivities()");
16743        }
16744
16745        try {
16746            final XmlPullParser parser = Xml.newPullParser();
16747            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
16748            restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP,
16749                    new BlobXmlRestorer() {
16750                        @Override
16751                        public void apply(XmlPullParser parser, int userId)
16752                                throws XmlPullParserException, IOException {
16753                            synchronized (mPackages) {
16754                                mSettings.readPreferredActivitiesLPw(parser, userId);
16755                            }
16756                        }
16757                    } );
16758        } catch (Exception e) {
16759            if (DEBUG_BACKUP) {
16760                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
16761            }
16762        }
16763    }
16764
16765    /**
16766     * Non-Binder method, support for the backup/restore mechanism: write the
16767     * default browser (etc) settings in its canonical XML format.  Returns the default
16768     * browser XML representation as a byte array, or null if there is none.
16769     */
16770    @Override
16771    public byte[] getDefaultAppsBackup(int userId) {
16772        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
16773            throw new SecurityException("Only the system may call getDefaultAppsBackup()");
16774        }
16775
16776        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
16777        try {
16778            final XmlSerializer serializer = new FastXmlSerializer();
16779            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
16780            serializer.startDocument(null, true);
16781            serializer.startTag(null, TAG_DEFAULT_APPS);
16782
16783            synchronized (mPackages) {
16784                mSettings.writeDefaultAppsLPr(serializer, userId);
16785            }
16786
16787            serializer.endTag(null, TAG_DEFAULT_APPS);
16788            serializer.endDocument();
16789            serializer.flush();
16790        } catch (Exception e) {
16791            if (DEBUG_BACKUP) {
16792                Slog.e(TAG, "Unable to write default apps for backup", e);
16793            }
16794            return null;
16795        }
16796
16797        return dataStream.toByteArray();
16798    }
16799
16800    @Override
16801    public void restoreDefaultApps(byte[] backup, int userId) {
16802        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
16803            throw new SecurityException("Only the system may call restoreDefaultApps()");
16804        }
16805
16806        try {
16807            final XmlPullParser parser = Xml.newPullParser();
16808            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
16809            restoreFromXml(parser, userId, TAG_DEFAULT_APPS,
16810                    new BlobXmlRestorer() {
16811                        @Override
16812                        public void apply(XmlPullParser parser, int userId)
16813                                throws XmlPullParserException, IOException {
16814                            synchronized (mPackages) {
16815                                mSettings.readDefaultAppsLPw(parser, userId);
16816                            }
16817                        }
16818                    } );
16819        } catch (Exception e) {
16820            if (DEBUG_BACKUP) {
16821                Slog.e(TAG, "Exception restoring default apps: " + e.getMessage());
16822            }
16823        }
16824    }
16825
16826    @Override
16827    public byte[] getIntentFilterVerificationBackup(int userId) {
16828        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
16829            throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()");
16830        }
16831
16832        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
16833        try {
16834            final XmlSerializer serializer = new FastXmlSerializer();
16835            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
16836            serializer.startDocument(null, true);
16837            serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION);
16838
16839            synchronized (mPackages) {
16840                mSettings.writeAllDomainVerificationsLPr(serializer, userId);
16841            }
16842
16843            serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION);
16844            serializer.endDocument();
16845            serializer.flush();
16846        } catch (Exception e) {
16847            if (DEBUG_BACKUP) {
16848                Slog.e(TAG, "Unable to write default apps for backup", e);
16849            }
16850            return null;
16851        }
16852
16853        return dataStream.toByteArray();
16854    }
16855
16856    @Override
16857    public void restoreIntentFilterVerification(byte[] backup, int userId) {
16858        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
16859            throw new SecurityException("Only the system may call restorePreferredActivities()");
16860        }
16861
16862        try {
16863            final XmlPullParser parser = Xml.newPullParser();
16864            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
16865            restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION,
16866                    new BlobXmlRestorer() {
16867                        @Override
16868                        public void apply(XmlPullParser parser, int userId)
16869                                throws XmlPullParserException, IOException {
16870                            synchronized (mPackages) {
16871                                mSettings.readAllDomainVerificationsLPr(parser, userId);
16872                                mSettings.writeLPr();
16873                            }
16874                        }
16875                    } );
16876        } catch (Exception e) {
16877            if (DEBUG_BACKUP) {
16878                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
16879            }
16880        }
16881    }
16882
16883    @Override
16884    public byte[] getPermissionGrantBackup(int userId) {
16885        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
16886            throw new SecurityException("Only the system may call getPermissionGrantBackup()");
16887        }
16888
16889        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
16890        try {
16891            final XmlSerializer serializer = new FastXmlSerializer();
16892            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
16893            serializer.startDocument(null, true);
16894            serializer.startTag(null, TAG_PERMISSION_BACKUP);
16895
16896            synchronized (mPackages) {
16897                serializeRuntimePermissionGrantsLPr(serializer, userId);
16898            }
16899
16900            serializer.endTag(null, TAG_PERMISSION_BACKUP);
16901            serializer.endDocument();
16902            serializer.flush();
16903        } catch (Exception e) {
16904            if (DEBUG_BACKUP) {
16905                Slog.e(TAG, "Unable to write default apps for backup", e);
16906            }
16907            return null;
16908        }
16909
16910        return dataStream.toByteArray();
16911    }
16912
16913    @Override
16914    public void restorePermissionGrants(byte[] backup, int userId) {
16915        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
16916            throw new SecurityException("Only the system may call restorePermissionGrants()");
16917        }
16918
16919        try {
16920            final XmlPullParser parser = Xml.newPullParser();
16921            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
16922            restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP,
16923                    new BlobXmlRestorer() {
16924                        @Override
16925                        public void apply(XmlPullParser parser, int userId)
16926                                throws XmlPullParserException, IOException {
16927                            synchronized (mPackages) {
16928                                processRestoredPermissionGrantsLPr(parser, userId);
16929                            }
16930                        }
16931                    } );
16932        } catch (Exception e) {
16933            if (DEBUG_BACKUP) {
16934                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
16935            }
16936        }
16937    }
16938
16939    private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId)
16940            throws IOException {
16941        serializer.startTag(null, TAG_ALL_GRANTS);
16942
16943        final int N = mSettings.mPackages.size();
16944        for (int i = 0; i < N; i++) {
16945            final PackageSetting ps = mSettings.mPackages.valueAt(i);
16946            boolean pkgGrantsKnown = false;
16947
16948            PermissionsState packagePerms = ps.getPermissionsState();
16949
16950            for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) {
16951                final int grantFlags = state.getFlags();
16952                // only look at grants that are not system/policy fixed
16953                if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) {
16954                    final boolean isGranted = state.isGranted();
16955                    // And only back up the user-twiddled state bits
16956                    if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) {
16957                        final String packageName = mSettings.mPackages.keyAt(i);
16958                        if (!pkgGrantsKnown) {
16959                            serializer.startTag(null, TAG_GRANT);
16960                            serializer.attribute(null, ATTR_PACKAGE_NAME, packageName);
16961                            pkgGrantsKnown = true;
16962                        }
16963
16964                        final boolean userSet =
16965                                (grantFlags & FLAG_PERMISSION_USER_SET) != 0;
16966                        final boolean userFixed =
16967                                (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0;
16968                        final boolean revoke =
16969                                (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0;
16970
16971                        serializer.startTag(null, TAG_PERMISSION);
16972                        serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName());
16973                        if (isGranted) {
16974                            serializer.attribute(null, ATTR_IS_GRANTED, "true");
16975                        }
16976                        if (userSet) {
16977                            serializer.attribute(null, ATTR_USER_SET, "true");
16978                        }
16979                        if (userFixed) {
16980                            serializer.attribute(null, ATTR_USER_FIXED, "true");
16981                        }
16982                        if (revoke) {
16983                            serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true");
16984                        }
16985                        serializer.endTag(null, TAG_PERMISSION);
16986                    }
16987                }
16988            }
16989
16990            if (pkgGrantsKnown) {
16991                serializer.endTag(null, TAG_GRANT);
16992            }
16993        }
16994
16995        serializer.endTag(null, TAG_ALL_GRANTS);
16996    }
16997
16998    private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId)
16999            throws XmlPullParserException, IOException {
17000        String pkgName = null;
17001        int outerDepth = parser.getDepth();
17002        int type;
17003        while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
17004                && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
17005            if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
17006                continue;
17007            }
17008
17009            final String tagName = parser.getName();
17010            if (tagName.equals(TAG_GRANT)) {
17011                pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME);
17012                if (DEBUG_BACKUP) {
17013                    Slog.v(TAG, "+++ Restoring grants for package " + pkgName);
17014                }
17015            } else if (tagName.equals(TAG_PERMISSION)) {
17016
17017                final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED));
17018                final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME);
17019
17020                int newFlagSet = 0;
17021                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) {
17022                    newFlagSet |= FLAG_PERMISSION_USER_SET;
17023                }
17024                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) {
17025                    newFlagSet |= FLAG_PERMISSION_USER_FIXED;
17026                }
17027                if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) {
17028                    newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE;
17029                }
17030                if (DEBUG_BACKUP) {
17031                    Slog.v(TAG, "  + Restoring grant: pkg=" + pkgName + " perm=" + permName
17032                            + " granted=" + isGranted + " bits=0x" + Integer.toHexString(newFlagSet));
17033                }
17034                final PackageSetting ps = mSettings.mPackages.get(pkgName);
17035                if (ps != null) {
17036                    // Already installed so we apply the grant immediately
17037                    if (DEBUG_BACKUP) {
17038                        Slog.v(TAG, "        + already installed; applying");
17039                    }
17040                    PermissionsState perms = ps.getPermissionsState();
17041                    BasePermission bp = mSettings.mPermissions.get(permName);
17042                    if (bp != null) {
17043                        if (isGranted) {
17044                            perms.grantRuntimePermission(bp, userId);
17045                        }
17046                        if (newFlagSet != 0) {
17047                            perms.updatePermissionFlags(bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet);
17048                        }
17049                    }
17050                } else {
17051                    // Need to wait for post-restore install to apply the grant
17052                    if (DEBUG_BACKUP) {
17053                        Slog.v(TAG, "        - not yet installed; saving for later");
17054                    }
17055                    mSettings.processRestoredPermissionGrantLPr(pkgName, permName,
17056                            isGranted, newFlagSet, userId);
17057                }
17058            } else {
17059                PackageManagerService.reportSettingsProblem(Log.WARN,
17060                        "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName);
17061                XmlUtils.skipCurrentTag(parser);
17062            }
17063        }
17064
17065        scheduleWriteSettingsLocked();
17066        mSettings.writeRuntimePermissionsForUserLPr(userId, false);
17067    }
17068
17069    @Override
17070    public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
17071            int sourceUserId, int targetUserId, int flags) {
17072        mContext.enforceCallingOrSelfPermission(
17073                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
17074        int callingUid = Binder.getCallingUid();
17075        enforceOwnerRights(ownerPackage, callingUid);
17076        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
17077        if (intentFilter.countActions() == 0) {
17078            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
17079            return;
17080        }
17081        synchronized (mPackages) {
17082            CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter,
17083                    ownerPackage, targetUserId, flags);
17084            CrossProfileIntentResolver resolver =
17085                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
17086            ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter);
17087            // We have all those whose filter is equal. Now checking if the rest is equal as well.
17088            if (existing != null) {
17089                int size = existing.size();
17090                for (int i = 0; i < size; i++) {
17091                    if (newFilter.equalsIgnoreFilter(existing.get(i))) {
17092                        return;
17093                    }
17094                }
17095            }
17096            resolver.addFilter(newFilter);
17097            scheduleWritePackageRestrictionsLocked(sourceUserId);
17098        }
17099    }
17100
17101    @Override
17102    public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) {
17103        mContext.enforceCallingOrSelfPermission(
17104                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
17105        int callingUid = Binder.getCallingUid();
17106        enforceOwnerRights(ownerPackage, callingUid);
17107        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
17108        synchronized (mPackages) {
17109            CrossProfileIntentResolver resolver =
17110                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
17111            ArraySet<CrossProfileIntentFilter> set =
17112                    new ArraySet<CrossProfileIntentFilter>(resolver.filterSet());
17113            for (CrossProfileIntentFilter filter : set) {
17114                if (filter.getOwnerPackage().equals(ownerPackage)) {
17115                    resolver.removeFilter(filter);
17116                }
17117            }
17118            scheduleWritePackageRestrictionsLocked(sourceUserId);
17119        }
17120    }
17121
17122    // Enforcing that callingUid is owning pkg on userId
17123    private void enforceOwnerRights(String pkg, int callingUid) {
17124        // The system owns everything.
17125        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
17126            return;
17127        }
17128        int callingUserId = UserHandle.getUserId(callingUid);
17129        PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
17130        if (pi == null) {
17131            throw new IllegalArgumentException("Unknown package " + pkg + " on user "
17132                    + callingUserId);
17133        }
17134        if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
17135            throw new SecurityException("Calling uid " + callingUid
17136                    + " does not own package " + pkg);
17137        }
17138    }
17139
17140    @Override
17141    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
17142        return getHomeActivitiesAsUser(allHomeCandidates, UserHandle.getCallingUserId());
17143    }
17144
17145    private Intent getHomeIntent() {
17146        Intent intent = new Intent(Intent.ACTION_MAIN);
17147        intent.addCategory(Intent.CATEGORY_HOME);
17148        return intent;
17149    }
17150
17151    private IntentFilter getHomeFilter() {
17152        IntentFilter filter = new IntentFilter(Intent.ACTION_MAIN);
17153        filter.addCategory(Intent.CATEGORY_HOME);
17154        filter.addCategory(Intent.CATEGORY_DEFAULT);
17155        return filter;
17156    }
17157
17158    ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
17159            int userId) {
17160        Intent intent  = getHomeIntent();
17161        List<ResolveInfo> list = queryIntentActivitiesInternal(intent, null,
17162                PackageManager.GET_META_DATA, userId);
17163        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
17164                true, false, false, userId);
17165
17166        allHomeCandidates.clear();
17167        if (list != null) {
17168            for (ResolveInfo ri : list) {
17169                allHomeCandidates.add(ri);
17170            }
17171        }
17172        return (preferred == null || preferred.activityInfo == null)
17173                ? null
17174                : new ComponentName(preferred.activityInfo.packageName,
17175                        preferred.activityInfo.name);
17176    }
17177
17178    @Override
17179    public void setHomeActivity(ComponentName comp, int userId) {
17180        ArrayList<ResolveInfo> homeActivities = new ArrayList<>();
17181        getHomeActivitiesAsUser(homeActivities, userId);
17182
17183        boolean found = false;
17184
17185        final int size = homeActivities.size();
17186        final ComponentName[] set = new ComponentName[size];
17187        for (int i = 0; i < size; i++) {
17188            final ResolveInfo candidate = homeActivities.get(i);
17189            final ActivityInfo info = candidate.activityInfo;
17190            final ComponentName activityName = new ComponentName(info.packageName, info.name);
17191            set[i] = activityName;
17192            if (!found && activityName.equals(comp)) {
17193                found = true;
17194            }
17195        }
17196        if (!found) {
17197            throw new IllegalArgumentException("Component " + comp + " cannot be home on user "
17198                    + userId);
17199        }
17200        replacePreferredActivity(getHomeFilter(), IntentFilter.MATCH_CATEGORY_EMPTY,
17201                set, comp, userId);
17202    }
17203
17204    private @Nullable String getSetupWizardPackageName() {
17205        final Intent intent = new Intent(Intent.ACTION_MAIN);
17206        intent.addCategory(Intent.CATEGORY_SETUP_WIZARD);
17207
17208        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
17209                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
17210                        | MATCH_DISABLED_COMPONENTS,
17211                UserHandle.myUserId());
17212        if (matches.size() == 1) {
17213            return matches.get(0).getComponentInfo().packageName;
17214        } else {
17215            Slog.e(TAG, "There should probably be exactly one setup wizard; found " + matches.size()
17216                    + ": matches=" + matches);
17217            return null;
17218        }
17219    }
17220
17221    @Override
17222    public void setApplicationEnabledSetting(String appPackageName,
17223            int newState, int flags, int userId, String callingPackage) {
17224        if (!sUserManager.exists(userId)) return;
17225        if (callingPackage == null) {
17226            callingPackage = Integer.toString(Binder.getCallingUid());
17227        }
17228        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
17229    }
17230
17231    @Override
17232    public void setComponentEnabledSetting(ComponentName componentName,
17233            int newState, int flags, int userId) {
17234        if (!sUserManager.exists(userId)) return;
17235        setEnabledSetting(componentName.getPackageName(),
17236                componentName.getClassName(), newState, flags, userId, null);
17237    }
17238
17239    private void setEnabledSetting(final String packageName, String className, int newState,
17240            final int flags, int userId, String callingPackage) {
17241        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
17242              || newState == COMPONENT_ENABLED_STATE_ENABLED
17243              || newState == COMPONENT_ENABLED_STATE_DISABLED
17244              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
17245              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
17246            throw new IllegalArgumentException("Invalid new component state: "
17247                    + newState);
17248        }
17249        PackageSetting pkgSetting;
17250        final int uid = Binder.getCallingUid();
17251        final int permission;
17252        if (uid == Process.SYSTEM_UID) {
17253            permission = PackageManager.PERMISSION_GRANTED;
17254        } else {
17255            permission = mContext.checkCallingOrSelfPermission(
17256                    android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
17257        }
17258        enforceCrossUserPermission(uid, userId,
17259                false /* requireFullPermission */, true /* checkShell */, "set enabled");
17260        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
17261        boolean sendNow = false;
17262        boolean isApp = (className == null);
17263        String componentName = isApp ? packageName : className;
17264        int packageUid = -1;
17265        ArrayList<String> components;
17266
17267        // writer
17268        synchronized (mPackages) {
17269            pkgSetting = mSettings.mPackages.get(packageName);
17270            if (pkgSetting == null) {
17271                if (className == null) {
17272                    throw new IllegalArgumentException("Unknown package: " + packageName);
17273                }
17274                throw new IllegalArgumentException(
17275                        "Unknown component: " + packageName + "/" + className);
17276            }
17277            // Allow root and verify that userId is not being specified by a different user
17278            if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) {
17279                throw new SecurityException(
17280                        "Permission Denial: attempt to change component state from pid="
17281                        + Binder.getCallingPid()
17282                        + ", uid=" + uid + ", package uid=" + pkgSetting.appId);
17283            }
17284            if (className == null) {
17285                // We're dealing with an application/package level state change
17286                if (pkgSetting.getEnabled(userId) == newState) {
17287                    // Nothing to do
17288                    return;
17289                }
17290                if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
17291                    || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
17292                    // Don't care about who enables an app.
17293                    callingPackage = null;
17294                }
17295                pkgSetting.setEnabled(newState, userId, callingPackage);
17296                // pkgSetting.pkg.mSetEnabled = newState;
17297            } else {
17298                // We're dealing with a component level state change
17299                // First, verify that this is a valid class name.
17300                PackageParser.Package pkg = pkgSetting.pkg;
17301                if (pkg == null || !pkg.hasComponentClassName(className)) {
17302                    if (pkg != null &&
17303                            pkg.applicationInfo.targetSdkVersion >=
17304                                    Build.VERSION_CODES.JELLY_BEAN) {
17305                        throw new IllegalArgumentException("Component class " + className
17306                                + " does not exist in " + packageName);
17307                    } else {
17308                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
17309                                + className + " does not exist in " + packageName);
17310                    }
17311                }
17312                switch (newState) {
17313                case COMPONENT_ENABLED_STATE_ENABLED:
17314                    if (!pkgSetting.enableComponentLPw(className, userId)) {
17315                        return;
17316                    }
17317                    break;
17318                case COMPONENT_ENABLED_STATE_DISABLED:
17319                    if (!pkgSetting.disableComponentLPw(className, userId)) {
17320                        return;
17321                    }
17322                    break;
17323                case COMPONENT_ENABLED_STATE_DEFAULT:
17324                    if (!pkgSetting.restoreComponentLPw(className, userId)) {
17325                        return;
17326                    }
17327                    break;
17328                default:
17329                    Slog.e(TAG, "Invalid new component state: " + newState);
17330                    return;
17331                }
17332            }
17333            scheduleWritePackageRestrictionsLocked(userId);
17334            components = mPendingBroadcasts.get(userId, packageName);
17335            final boolean newPackage = components == null;
17336            if (newPackage) {
17337                components = new ArrayList<String>();
17338            }
17339            if (!components.contains(componentName)) {
17340                components.add(componentName);
17341            }
17342            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
17343                sendNow = true;
17344                // Purge entry from pending broadcast list if another one exists already
17345                // since we are sending one right away.
17346                mPendingBroadcasts.remove(userId, packageName);
17347            } else {
17348                if (newPackage) {
17349                    mPendingBroadcasts.put(userId, packageName, components);
17350                }
17351                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
17352                    // Schedule a message
17353                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
17354                }
17355            }
17356        }
17357
17358        long callingId = Binder.clearCallingIdentity();
17359        try {
17360            if (sendNow) {
17361                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
17362                sendPackageChangedBroadcast(packageName,
17363                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
17364            }
17365        } finally {
17366            Binder.restoreCallingIdentity(callingId);
17367        }
17368    }
17369
17370    @Override
17371    public void flushPackageRestrictionsAsUser(int userId) {
17372        if (!sUserManager.exists(userId)) {
17373            return;
17374        }
17375        enforceCrossUserPermission(Binder.getCallingUid(), userId, false /* requireFullPermission*/,
17376                false /* checkShell */, "flushPackageRestrictions");
17377        synchronized (mPackages) {
17378            mSettings.writePackageRestrictionsLPr(userId);
17379            mDirtyUsers.remove(userId);
17380            if (mDirtyUsers.isEmpty()) {
17381                mHandler.removeMessages(WRITE_PACKAGE_RESTRICTIONS);
17382            }
17383        }
17384    }
17385
17386    private void sendPackageChangedBroadcast(String packageName,
17387            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
17388        if (DEBUG_INSTALL)
17389            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
17390                    + componentNames);
17391        Bundle extras = new Bundle(4);
17392        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
17393        String nameList[] = new String[componentNames.size()];
17394        componentNames.toArray(nameList);
17395        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
17396        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
17397        extras.putInt(Intent.EXTRA_UID, packageUid);
17398        // If this is not reporting a change of the overall package, then only send it
17399        // to registered receivers.  We don't want to launch a swath of apps for every
17400        // little component state change.
17401        final int flags = !componentNames.contains(packageName)
17402                ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0;
17403        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, flags, null, null,
17404                new int[] {UserHandle.getUserId(packageUid)});
17405    }
17406
17407    @Override
17408    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
17409        if (!sUserManager.exists(userId)) return;
17410        final int uid = Binder.getCallingUid();
17411        final int permission = mContext.checkCallingOrSelfPermission(
17412                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
17413        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
17414        enforceCrossUserPermission(uid, userId,
17415                true /* requireFullPermission */, true /* checkShell */, "stop package");
17416        // writer
17417        synchronized (mPackages) {
17418            if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped,
17419                    allowedByPermission, uid, userId)) {
17420                scheduleWritePackageRestrictionsLocked(userId);
17421            }
17422        }
17423    }
17424
17425    @Override
17426    public String getInstallerPackageName(String packageName) {
17427        // reader
17428        synchronized (mPackages) {
17429            return mSettings.getInstallerPackageNameLPr(packageName);
17430        }
17431    }
17432
17433    @Override
17434    public int getApplicationEnabledSetting(String packageName, int userId) {
17435        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
17436        int uid = Binder.getCallingUid();
17437        enforceCrossUserPermission(uid, userId,
17438                false /* requireFullPermission */, false /* checkShell */, "get enabled");
17439        // reader
17440        synchronized (mPackages) {
17441            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
17442        }
17443    }
17444
17445    @Override
17446    public int getComponentEnabledSetting(ComponentName componentName, int userId) {
17447        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
17448        int uid = Binder.getCallingUid();
17449        enforceCrossUserPermission(uid, userId,
17450                false /* requireFullPermission */, false /* checkShell */, "get component enabled");
17451        // reader
17452        synchronized (mPackages) {
17453            return mSettings.getComponentEnabledSettingLPr(componentName, userId);
17454        }
17455    }
17456
17457    @Override
17458    public void enterSafeMode() {
17459        enforceSystemOrRoot("Only the system can request entering safe mode");
17460
17461        if (!mSystemReady) {
17462            mSafeMode = true;
17463        }
17464    }
17465
17466    @Override
17467    public void systemReady() {
17468        mSystemReady = true;
17469
17470        // Read the compatibilty setting when the system is ready.
17471        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
17472                mContext.getContentResolver(),
17473                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
17474        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
17475        if (DEBUG_SETTINGS) {
17476            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
17477        }
17478
17479        int[] grantPermissionsUserIds = EMPTY_INT_ARRAY;
17480
17481        synchronized (mPackages) {
17482            // Verify that all of the preferred activity components actually
17483            // exist.  It is possible for applications to be updated and at
17484            // that point remove a previously declared activity component that
17485            // had been set as a preferred activity.  We try to clean this up
17486            // the next time we encounter that preferred activity, but it is
17487            // possible for the user flow to never be able to return to that
17488            // situation so here we do a sanity check to make sure we haven't
17489            // left any junk around.
17490            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
17491            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
17492                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
17493                removed.clear();
17494                for (PreferredActivity pa : pir.filterSet()) {
17495                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
17496                        removed.add(pa);
17497                    }
17498                }
17499                if (removed.size() > 0) {
17500                    for (int r=0; r<removed.size(); r++) {
17501                        PreferredActivity pa = removed.get(r);
17502                        Slog.w(TAG, "Removing dangling preferred activity: "
17503                                + pa.mPref.mComponent);
17504                        pir.removeFilter(pa);
17505                    }
17506                    mSettings.writePackageRestrictionsLPr(
17507                            mSettings.mPreferredActivities.keyAt(i));
17508                }
17509            }
17510
17511            for (int userId : UserManagerService.getInstance().getUserIds()) {
17512                if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) {
17513                    grantPermissionsUserIds = ArrayUtils.appendInt(
17514                            grantPermissionsUserIds, userId);
17515                }
17516            }
17517        }
17518        sUserManager.systemReady();
17519
17520        // If we upgraded grant all default permissions before kicking off.
17521        for (int userId : grantPermissionsUserIds) {
17522            mDefaultPermissionPolicy.grantDefaultPermissions(userId);
17523        }
17524
17525        // Kick off any messages waiting for system ready
17526        if (mPostSystemReadyMessages != null) {
17527            for (Message msg : mPostSystemReadyMessages) {
17528                msg.sendToTarget();
17529            }
17530            mPostSystemReadyMessages = null;
17531        }
17532
17533        // Watch for external volumes that come and go over time
17534        final StorageManager storage = mContext.getSystemService(StorageManager.class);
17535        storage.registerListener(mStorageListener);
17536
17537        mInstallerService.systemReady();
17538        mPackageDexOptimizer.systemReady();
17539
17540        MountServiceInternal mountServiceInternal = LocalServices.getService(
17541                MountServiceInternal.class);
17542        mountServiceInternal.addExternalStoragePolicy(
17543                new MountServiceInternal.ExternalStorageMountPolicy() {
17544            @Override
17545            public int getMountMode(int uid, String packageName) {
17546                if (Process.isIsolated(uid)) {
17547                    return Zygote.MOUNT_EXTERNAL_NONE;
17548                }
17549                if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) {
17550                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
17551                }
17552                if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
17553                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
17554                }
17555                if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
17556                    return Zygote.MOUNT_EXTERNAL_READ;
17557                }
17558                return Zygote.MOUNT_EXTERNAL_WRITE;
17559            }
17560
17561            @Override
17562            public boolean hasExternalStorage(int uid, String packageName) {
17563                return true;
17564            }
17565        });
17566
17567        // Now that we're mostly running, clean up stale users and apps
17568        reconcileUsers(StorageManager.UUID_PRIVATE_INTERNAL);
17569        reconcileApps(StorageManager.UUID_PRIVATE_INTERNAL);
17570    }
17571
17572    @Override
17573    public boolean isSafeMode() {
17574        return mSafeMode;
17575    }
17576
17577    @Override
17578    public boolean hasSystemUidErrors() {
17579        return mHasSystemUidErrors;
17580    }
17581
17582    static String arrayToString(int[] array) {
17583        StringBuffer buf = new StringBuffer(128);
17584        buf.append('[');
17585        if (array != null) {
17586            for (int i=0; i<array.length; i++) {
17587                if (i > 0) buf.append(", ");
17588                buf.append(array[i]);
17589            }
17590        }
17591        buf.append(']');
17592        return buf.toString();
17593    }
17594
17595    static class DumpState {
17596        public static final int DUMP_LIBS = 1 << 0;
17597        public static final int DUMP_FEATURES = 1 << 1;
17598        public static final int DUMP_ACTIVITY_RESOLVERS = 1 << 2;
17599        public static final int DUMP_SERVICE_RESOLVERS = 1 << 3;
17600        public static final int DUMP_RECEIVER_RESOLVERS = 1 << 4;
17601        public static final int DUMP_CONTENT_RESOLVERS = 1 << 5;
17602        public static final int DUMP_PERMISSIONS = 1 << 6;
17603        public static final int DUMP_PACKAGES = 1 << 7;
17604        public static final int DUMP_SHARED_USERS = 1 << 8;
17605        public static final int DUMP_MESSAGES = 1 << 9;
17606        public static final int DUMP_PROVIDERS = 1 << 10;
17607        public static final int DUMP_VERIFIERS = 1 << 11;
17608        public static final int DUMP_PREFERRED = 1 << 12;
17609        public static final int DUMP_PREFERRED_XML = 1 << 13;
17610        public static final int DUMP_KEYSETS = 1 << 14;
17611        public static final int DUMP_VERSION = 1 << 15;
17612        public static final int DUMP_INSTALLS = 1 << 16;
17613        public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 17;
17614        public static final int DUMP_DOMAIN_PREFERRED = 1 << 18;
17615        public static final int DUMP_FROZEN = 1 << 19;
17616
17617        public static final int OPTION_SHOW_FILTERS = 1 << 0;
17618
17619        private int mTypes;
17620
17621        private int mOptions;
17622
17623        private boolean mTitlePrinted;
17624
17625        private SharedUserSetting mSharedUser;
17626
17627        public boolean isDumping(int type) {
17628            if (mTypes == 0 && type != DUMP_PREFERRED_XML) {
17629                return true;
17630            }
17631
17632            return (mTypes & type) != 0;
17633        }
17634
17635        public void setDump(int type) {
17636            mTypes |= type;
17637        }
17638
17639        public boolean isOptionEnabled(int option) {
17640            return (mOptions & option) != 0;
17641        }
17642
17643        public void setOptionEnabled(int option) {
17644            mOptions |= option;
17645        }
17646
17647        public boolean onTitlePrinted() {
17648            final boolean printed = mTitlePrinted;
17649            mTitlePrinted = true;
17650            return printed;
17651        }
17652
17653        public boolean getTitlePrinted() {
17654            return mTitlePrinted;
17655        }
17656
17657        public void setTitlePrinted(boolean enabled) {
17658            mTitlePrinted = enabled;
17659        }
17660
17661        public SharedUserSetting getSharedUser() {
17662            return mSharedUser;
17663        }
17664
17665        public void setSharedUser(SharedUserSetting user) {
17666            mSharedUser = user;
17667        }
17668    }
17669
17670    @Override
17671    public void onShellCommand(FileDescriptor in, FileDescriptor out,
17672            FileDescriptor err, String[] args, ResultReceiver resultReceiver) {
17673        (new PackageManagerShellCommand(this)).exec(
17674                this, in, out, err, args, resultReceiver);
17675    }
17676
17677    @Override
17678    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
17679        if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
17680                != PackageManager.PERMISSION_GRANTED) {
17681            pw.println("Permission Denial: can't dump ActivityManager from from pid="
17682                    + Binder.getCallingPid()
17683                    + ", uid=" + Binder.getCallingUid()
17684                    + " without permission "
17685                    + android.Manifest.permission.DUMP);
17686            return;
17687        }
17688
17689        DumpState dumpState = new DumpState();
17690        boolean fullPreferred = false;
17691        boolean checkin = false;
17692
17693        String packageName = null;
17694        ArraySet<String> permissionNames = null;
17695
17696        int opti = 0;
17697        while (opti < args.length) {
17698            String opt = args[opti];
17699            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
17700                break;
17701            }
17702            opti++;
17703
17704            if ("-a".equals(opt)) {
17705                // Right now we only know how to print all.
17706            } else if ("-h".equals(opt)) {
17707                pw.println("Package manager dump options:");
17708                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
17709                pw.println("    --checkin: dump for a checkin");
17710                pw.println("    -f: print details of intent filters");
17711                pw.println("    -h: print this help");
17712                pw.println("  cmd may be one of:");
17713                pw.println("    l[ibraries]: list known shared libraries");
17714                pw.println("    f[eatures]: list device features");
17715                pw.println("    k[eysets]: print known keysets");
17716                pw.println("    r[esolvers] [activity|service|receiver|content]: dump intent resolvers");
17717                pw.println("    perm[issions]: dump permissions");
17718                pw.println("    permission [name ...]: dump declaration and use of given permission");
17719                pw.println("    pref[erred]: print preferred package settings");
17720                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
17721                pw.println("    prov[iders]: dump content providers");
17722                pw.println("    p[ackages]: dump installed packages");
17723                pw.println("    s[hared-users]: dump shared user IDs");
17724                pw.println("    m[essages]: print collected runtime messages");
17725                pw.println("    v[erifiers]: print package verifier info");
17726                pw.println("    d[omain-preferred-apps]: print domains preferred apps");
17727                pw.println("    i[ntent-filter-verifiers]|ifv: print intent filter verifier info");
17728                pw.println("    version: print database version info");
17729                pw.println("    write: write current settings now");
17730                pw.println("    installs: details about install sessions");
17731                pw.println("    check-permission <permission> <package> [<user>]: does pkg hold perm?");
17732                pw.println("    <package.name>: info about given package");
17733                return;
17734            } else if ("--checkin".equals(opt)) {
17735                checkin = true;
17736            } else if ("-f".equals(opt)) {
17737                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
17738            } else {
17739                pw.println("Unknown argument: " + opt + "; use -h for help");
17740            }
17741        }
17742
17743        // Is the caller requesting to dump a particular piece of data?
17744        if (opti < args.length) {
17745            String cmd = args[opti];
17746            opti++;
17747            // Is this a package name?
17748            if ("android".equals(cmd) || cmd.contains(".")) {
17749                packageName = cmd;
17750                // When dumping a single package, we always dump all of its
17751                // filter information since the amount of data will be reasonable.
17752                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
17753            } else if ("check-permission".equals(cmd)) {
17754                if (opti >= args.length) {
17755                    pw.println("Error: check-permission missing permission argument");
17756                    return;
17757                }
17758                String perm = args[opti];
17759                opti++;
17760                if (opti >= args.length) {
17761                    pw.println("Error: check-permission missing package argument");
17762                    return;
17763                }
17764                String pkg = args[opti];
17765                opti++;
17766                int user = UserHandle.getUserId(Binder.getCallingUid());
17767                if (opti < args.length) {
17768                    try {
17769                        user = Integer.parseInt(args[opti]);
17770                    } catch (NumberFormatException e) {
17771                        pw.println("Error: check-permission user argument is not a number: "
17772                                + args[opti]);
17773                        return;
17774                    }
17775                }
17776                pw.println(checkPermission(perm, pkg, user));
17777                return;
17778            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
17779                dumpState.setDump(DumpState.DUMP_LIBS);
17780            } else if ("f".equals(cmd) || "features".equals(cmd)) {
17781                dumpState.setDump(DumpState.DUMP_FEATURES);
17782            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
17783                if (opti >= args.length) {
17784                    dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS
17785                            | DumpState.DUMP_SERVICE_RESOLVERS
17786                            | DumpState.DUMP_RECEIVER_RESOLVERS
17787                            | DumpState.DUMP_CONTENT_RESOLVERS);
17788                } else {
17789                    while (opti < args.length) {
17790                        String name = args[opti];
17791                        if ("a".equals(name) || "activity".equals(name)) {
17792                            dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS);
17793                        } else if ("s".equals(name) || "service".equals(name)) {
17794                            dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS);
17795                        } else if ("r".equals(name) || "receiver".equals(name)) {
17796                            dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS);
17797                        } else if ("c".equals(name) || "content".equals(name)) {
17798                            dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS);
17799                        } else {
17800                            pw.println("Error: unknown resolver table type: " + name);
17801                            return;
17802                        }
17803                        opti++;
17804                    }
17805                }
17806            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
17807                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
17808            } else if ("permission".equals(cmd)) {
17809                if (opti >= args.length) {
17810                    pw.println("Error: permission requires permission name");
17811                    return;
17812                }
17813                permissionNames = new ArraySet<>();
17814                while (opti < args.length) {
17815                    permissionNames.add(args[opti]);
17816                    opti++;
17817                }
17818                dumpState.setDump(DumpState.DUMP_PERMISSIONS
17819                        | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS);
17820            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
17821                dumpState.setDump(DumpState.DUMP_PREFERRED);
17822            } else if ("preferred-xml".equals(cmd)) {
17823                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
17824                if (opti < args.length && "--full".equals(args[opti])) {
17825                    fullPreferred = true;
17826                    opti++;
17827                }
17828            } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) {
17829                dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED);
17830            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
17831                dumpState.setDump(DumpState.DUMP_PACKAGES);
17832            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
17833                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
17834            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
17835                dumpState.setDump(DumpState.DUMP_PROVIDERS);
17836            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
17837                dumpState.setDump(DumpState.DUMP_MESSAGES);
17838            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
17839                dumpState.setDump(DumpState.DUMP_VERIFIERS);
17840            } else if ("i".equals(cmd) || "ifv".equals(cmd)
17841                    || "intent-filter-verifiers".equals(cmd)) {
17842                dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS);
17843            } else if ("version".equals(cmd)) {
17844                dumpState.setDump(DumpState.DUMP_VERSION);
17845            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
17846                dumpState.setDump(DumpState.DUMP_KEYSETS);
17847            } else if ("installs".equals(cmd)) {
17848                dumpState.setDump(DumpState.DUMP_INSTALLS);
17849            } else if ("frozen".equals(cmd)) {
17850                dumpState.setDump(DumpState.DUMP_FROZEN);
17851            } else if ("write".equals(cmd)) {
17852                synchronized (mPackages) {
17853                    mSettings.writeLPr();
17854                    pw.println("Settings written.");
17855                    return;
17856                }
17857            }
17858        }
17859
17860        if (checkin) {
17861            pw.println("vers,1");
17862        }
17863
17864        // reader
17865        synchronized (mPackages) {
17866            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
17867                if (!checkin) {
17868                    if (dumpState.onTitlePrinted())
17869                        pw.println();
17870                    pw.println("Database versions:");
17871                    mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, "  "));
17872                }
17873            }
17874
17875            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
17876                if (!checkin) {
17877                    if (dumpState.onTitlePrinted())
17878                        pw.println();
17879                    pw.println("Verifiers:");
17880                    pw.print("  Required: ");
17881                    pw.print(mRequiredVerifierPackage);
17882                    pw.print(" (uid=");
17883                    pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
17884                            UserHandle.USER_SYSTEM));
17885                    pw.println(")");
17886                } else if (mRequiredVerifierPackage != null) {
17887                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
17888                    pw.print(",");
17889                    pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
17890                            UserHandle.USER_SYSTEM));
17891                }
17892            }
17893
17894            if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) &&
17895                    packageName == null) {
17896                if (mIntentFilterVerifierComponent != null) {
17897                    String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
17898                    if (!checkin) {
17899                        if (dumpState.onTitlePrinted())
17900                            pw.println();
17901                        pw.println("Intent Filter Verifier:");
17902                        pw.print("  Using: ");
17903                        pw.print(verifierPackageName);
17904                        pw.print(" (uid=");
17905                        pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
17906                                UserHandle.USER_SYSTEM));
17907                        pw.println(")");
17908                    } else if (verifierPackageName != null) {
17909                        pw.print("ifv,"); pw.print(verifierPackageName);
17910                        pw.print(",");
17911                        pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
17912                                UserHandle.USER_SYSTEM));
17913                    }
17914                } else {
17915                    pw.println();
17916                    pw.println("No Intent Filter Verifier available!");
17917                }
17918            }
17919
17920            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
17921                boolean printedHeader = false;
17922                final Iterator<String> it = mSharedLibraries.keySet().iterator();
17923                while (it.hasNext()) {
17924                    String name = it.next();
17925                    SharedLibraryEntry ent = mSharedLibraries.get(name);
17926                    if (!checkin) {
17927                        if (!printedHeader) {
17928                            if (dumpState.onTitlePrinted())
17929                                pw.println();
17930                            pw.println("Libraries:");
17931                            printedHeader = true;
17932                        }
17933                        pw.print("  ");
17934                    } else {
17935                        pw.print("lib,");
17936                    }
17937                    pw.print(name);
17938                    if (!checkin) {
17939                        pw.print(" -> ");
17940                    }
17941                    if (ent.path != null) {
17942                        if (!checkin) {
17943                            pw.print("(jar) ");
17944                            pw.print(ent.path);
17945                        } else {
17946                            pw.print(",jar,");
17947                            pw.print(ent.path);
17948                        }
17949                    } else {
17950                        if (!checkin) {
17951                            pw.print("(apk) ");
17952                            pw.print(ent.apk);
17953                        } else {
17954                            pw.print(",apk,");
17955                            pw.print(ent.apk);
17956                        }
17957                    }
17958                    pw.println();
17959                }
17960            }
17961
17962            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
17963                if (dumpState.onTitlePrinted())
17964                    pw.println();
17965                if (!checkin) {
17966                    pw.println("Features:");
17967                }
17968
17969                for (FeatureInfo feat : mAvailableFeatures.values()) {
17970                    if (checkin) {
17971                        pw.print("feat,");
17972                        pw.print(feat.name);
17973                        pw.print(",");
17974                        pw.println(feat.version);
17975                    } else {
17976                        pw.print("  ");
17977                        pw.print(feat.name);
17978                        if (feat.version > 0) {
17979                            pw.print(" version=");
17980                            pw.print(feat.version);
17981                        }
17982                        pw.println();
17983                    }
17984                }
17985            }
17986
17987            if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) {
17988                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
17989                        : "Activity Resolver Table:", "  ", packageName,
17990                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
17991                    dumpState.setTitlePrinted(true);
17992                }
17993            }
17994            if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) {
17995                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
17996                        : "Receiver Resolver Table:", "  ", packageName,
17997                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
17998                    dumpState.setTitlePrinted(true);
17999                }
18000            }
18001            if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) {
18002                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
18003                        : "Service Resolver Table:", "  ", packageName,
18004                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
18005                    dumpState.setTitlePrinted(true);
18006                }
18007            }
18008            if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) {
18009                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
18010                        : "Provider Resolver Table:", "  ", packageName,
18011                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
18012                    dumpState.setTitlePrinted(true);
18013                }
18014            }
18015
18016            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
18017                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
18018                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
18019                    int user = mSettings.mPreferredActivities.keyAt(i);
18020                    if (pir.dump(pw,
18021                            dumpState.getTitlePrinted()
18022                                ? "\nPreferred Activities User " + user + ":"
18023                                : "Preferred Activities User " + user + ":", "  ",
18024                            packageName, true, false)) {
18025                        dumpState.setTitlePrinted(true);
18026                    }
18027                }
18028            }
18029
18030            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
18031                pw.flush();
18032                FileOutputStream fout = new FileOutputStream(fd);
18033                BufferedOutputStream str = new BufferedOutputStream(fout);
18034                XmlSerializer serializer = new FastXmlSerializer();
18035                try {
18036                    serializer.setOutput(str, StandardCharsets.UTF_8.name());
18037                    serializer.startDocument(null, true);
18038                    serializer.setFeature(
18039                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
18040                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
18041                    serializer.endDocument();
18042                    serializer.flush();
18043                } catch (IllegalArgumentException e) {
18044                    pw.println("Failed writing: " + e);
18045                } catch (IllegalStateException e) {
18046                    pw.println("Failed writing: " + e);
18047                } catch (IOException e) {
18048                    pw.println("Failed writing: " + e);
18049                }
18050            }
18051
18052            if (!checkin
18053                    && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)
18054                    && packageName == null) {
18055                pw.println();
18056                int count = mSettings.mPackages.size();
18057                if (count == 0) {
18058                    pw.println("No applications!");
18059                    pw.println();
18060                } else {
18061                    final String prefix = "  ";
18062                    Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values();
18063                    if (allPackageSettings.size() == 0) {
18064                        pw.println("No domain preferred apps!");
18065                        pw.println();
18066                    } else {
18067                        pw.println("App verification status:");
18068                        pw.println();
18069                        count = 0;
18070                        for (PackageSetting ps : allPackageSettings) {
18071                            IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
18072                            if (ivi == null || ivi.getPackageName() == null) continue;
18073                            pw.println(prefix + "Package: " + ivi.getPackageName());
18074                            pw.println(prefix + "Domains: " + ivi.getDomainsString());
18075                            pw.println(prefix + "Status:  " + ivi.getStatusString());
18076                            pw.println();
18077                            count++;
18078                        }
18079                        if (count == 0) {
18080                            pw.println(prefix + "No app verification established.");
18081                            pw.println();
18082                        }
18083                        for (int userId : sUserManager.getUserIds()) {
18084                            pw.println("App linkages for user " + userId + ":");
18085                            pw.println();
18086                            count = 0;
18087                            for (PackageSetting ps : allPackageSettings) {
18088                                final long status = ps.getDomainVerificationStatusForUser(userId);
18089                                if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
18090                                    continue;
18091                                }
18092                                pw.println(prefix + "Package: " + ps.name);
18093                                pw.println(prefix + "Domains: " + dumpDomainString(ps.name));
18094                                String statusStr = IntentFilterVerificationInfo.
18095                                        getStatusStringFromValue(status);
18096                                pw.println(prefix + "Status:  " + statusStr);
18097                                pw.println();
18098                                count++;
18099                            }
18100                            if (count == 0) {
18101                                pw.println(prefix + "No configured app linkages.");
18102                                pw.println();
18103                            }
18104                        }
18105                    }
18106                }
18107            }
18108
18109            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
18110                mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState);
18111                if (packageName == null && permissionNames == null) {
18112                    for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) {
18113                        if (iperm == 0) {
18114                            if (dumpState.onTitlePrinted())
18115                                pw.println();
18116                            pw.println("AppOp Permissions:");
18117                        }
18118                        pw.print("  AppOp Permission ");
18119                        pw.print(mAppOpPermissionPackages.keyAt(iperm));
18120                        pw.println(":");
18121                        ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm);
18122                        for (int ipkg=0; ipkg<pkgs.size(); ipkg++) {
18123                            pw.print("    "); pw.println(pkgs.valueAt(ipkg));
18124                        }
18125                    }
18126                }
18127            }
18128
18129            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
18130                boolean printedSomething = false;
18131                for (PackageParser.Provider p : mProviders.mProviders.values()) {
18132                    if (packageName != null && !packageName.equals(p.info.packageName)) {
18133                        continue;
18134                    }
18135                    if (!printedSomething) {
18136                        if (dumpState.onTitlePrinted())
18137                            pw.println();
18138                        pw.println("Registered ContentProviders:");
18139                        printedSomething = true;
18140                    }
18141                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
18142                    pw.print("    "); pw.println(p.toString());
18143                }
18144                printedSomething = false;
18145                for (Map.Entry<String, PackageParser.Provider> entry :
18146                        mProvidersByAuthority.entrySet()) {
18147                    PackageParser.Provider p = entry.getValue();
18148                    if (packageName != null && !packageName.equals(p.info.packageName)) {
18149                        continue;
18150                    }
18151                    if (!printedSomething) {
18152                        if (dumpState.onTitlePrinted())
18153                            pw.println();
18154                        pw.println("ContentProvider Authorities:");
18155                        printedSomething = true;
18156                    }
18157                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
18158                    pw.print("    "); pw.println(p.toString());
18159                    if (p.info != null && p.info.applicationInfo != null) {
18160                        final String appInfo = p.info.applicationInfo.toString();
18161                        pw.print("      applicationInfo="); pw.println(appInfo);
18162                    }
18163                }
18164            }
18165
18166            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
18167                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
18168            }
18169
18170            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
18171                mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin);
18172            }
18173
18174            if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
18175                mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin);
18176            }
18177
18178            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) {
18179                mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState);
18180            }
18181
18182            if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
18183                // XXX should handle packageName != null by dumping only install data that
18184                // the given package is involved with.
18185                if (dumpState.onTitlePrinted()) pw.println();
18186                mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
18187            }
18188
18189            if (!checkin && dumpState.isDumping(DumpState.DUMP_FROZEN) && packageName == null) {
18190                // XXX should handle packageName != null by dumping only install data that
18191                // the given package is involved with.
18192                if (dumpState.onTitlePrinted()) pw.println();
18193
18194                final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
18195                ipw.println();
18196                ipw.println("Frozen packages:");
18197                ipw.increaseIndent();
18198                if (mFrozenPackages.size() == 0) {
18199                    ipw.println("(none)");
18200                } else {
18201                    for (int i = 0; i < mFrozenPackages.size(); i++) {
18202                        ipw.println(mFrozenPackages.valueAt(i));
18203                    }
18204                }
18205                ipw.decreaseIndent();
18206            }
18207
18208            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
18209                if (dumpState.onTitlePrinted()) pw.println();
18210                mSettings.dumpReadMessagesLPr(pw, dumpState);
18211
18212                pw.println();
18213                pw.println("Package warning messages:");
18214                BufferedReader in = null;
18215                String line = null;
18216                try {
18217                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
18218                    while ((line = in.readLine()) != null) {
18219                        if (line.contains("ignored: updated version")) continue;
18220                        pw.println(line);
18221                    }
18222                } catch (IOException ignored) {
18223                } finally {
18224                    IoUtils.closeQuietly(in);
18225                }
18226            }
18227
18228            if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) {
18229                BufferedReader in = null;
18230                String line = null;
18231                try {
18232                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
18233                    while ((line = in.readLine()) != null) {
18234                        if (line.contains("ignored: updated version")) continue;
18235                        pw.print("msg,");
18236                        pw.println(line);
18237                    }
18238                } catch (IOException ignored) {
18239                } finally {
18240                    IoUtils.closeQuietly(in);
18241                }
18242            }
18243        }
18244    }
18245
18246    private String dumpDomainString(String packageName) {
18247        List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName)
18248                .getList();
18249        List<IntentFilter> filters = getAllIntentFilters(packageName).getList();
18250
18251        ArraySet<String> result = new ArraySet<>();
18252        if (iviList.size() > 0) {
18253            for (IntentFilterVerificationInfo ivi : iviList) {
18254                for (String host : ivi.getDomains()) {
18255                    result.add(host);
18256                }
18257            }
18258        }
18259        if (filters != null && filters.size() > 0) {
18260            for (IntentFilter filter : filters) {
18261                if (filter.hasCategory(Intent.CATEGORY_BROWSABLE)
18262                        && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
18263                                filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) {
18264                    result.addAll(filter.getHostsList());
18265                }
18266            }
18267        }
18268
18269        StringBuilder sb = new StringBuilder(result.size() * 16);
18270        for (String domain : result) {
18271            if (sb.length() > 0) sb.append(" ");
18272            sb.append(domain);
18273        }
18274        return sb.toString();
18275    }
18276
18277    // ------- apps on sdcard specific code -------
18278    static final boolean DEBUG_SD_INSTALL = false;
18279
18280    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
18281
18282    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
18283
18284    private boolean mMediaMounted = false;
18285
18286    static String getEncryptKey() {
18287        try {
18288            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
18289                    SD_ENCRYPTION_KEYSTORE_NAME);
18290            if (sdEncKey == null) {
18291                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
18292                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
18293                if (sdEncKey == null) {
18294                    Slog.e(TAG, "Failed to create encryption keys");
18295                    return null;
18296                }
18297            }
18298            return sdEncKey;
18299        } catch (NoSuchAlgorithmException nsae) {
18300            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
18301            return null;
18302        } catch (IOException ioe) {
18303            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
18304            return null;
18305        }
18306    }
18307
18308    /*
18309     * Update media status on PackageManager.
18310     */
18311    @Override
18312    public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
18313        int callingUid = Binder.getCallingUid();
18314        if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
18315            throw new SecurityException("Media status can only be updated by the system");
18316        }
18317        // reader; this apparently protects mMediaMounted, but should probably
18318        // be a different lock in that case.
18319        synchronized (mPackages) {
18320            Log.i(TAG, "Updating external media status from "
18321                    + (mMediaMounted ? "mounted" : "unmounted") + " to "
18322                    + (mediaStatus ? "mounted" : "unmounted"));
18323            if (DEBUG_SD_INSTALL)
18324                Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
18325                        + ", mMediaMounted=" + mMediaMounted);
18326            if (mediaStatus == mMediaMounted) {
18327                final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
18328                        : 0, -1);
18329                mHandler.sendMessage(msg);
18330                return;
18331            }
18332            mMediaMounted = mediaStatus;
18333        }
18334        // Queue up an async operation since the package installation may take a
18335        // little while.
18336        mHandler.post(new Runnable() {
18337            public void run() {
18338                updateExternalMediaStatusInner(mediaStatus, reportStatus, true);
18339            }
18340        });
18341    }
18342
18343    /**
18344     * Called by MountService when the initial ASECs to scan are available.
18345     * Should block until all the ASEC containers are finished being scanned.
18346     */
18347    public void scanAvailableAsecs() {
18348        updateExternalMediaStatusInner(true, false, false);
18349    }
18350
18351    /*
18352     * Collect information of applications on external media, map them against
18353     * existing containers and update information based on current mount status.
18354     * Please note that we always have to report status if reportStatus has been
18355     * set to true especially when unloading packages.
18356     */
18357    private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus,
18358            boolean externalStorage) {
18359        ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>();
18360        int[] uidArr = EmptyArray.INT;
18361
18362        final String[] list = PackageHelper.getSecureContainerList();
18363        if (ArrayUtils.isEmpty(list)) {
18364            Log.i(TAG, "No secure containers found");
18365        } else {
18366            // Process list of secure containers and categorize them
18367            // as active or stale based on their package internal state.
18368
18369            // reader
18370            synchronized (mPackages) {
18371                for (String cid : list) {
18372                    // Leave stages untouched for now; installer service owns them
18373                    if (PackageInstallerService.isStageName(cid)) continue;
18374
18375                    if (DEBUG_SD_INSTALL)
18376                        Log.i(TAG, "Processing container " + cid);
18377                    String pkgName = getAsecPackageName(cid);
18378                    if (pkgName == null) {
18379                        Slog.i(TAG, "Found stale container " + cid + " with no package name");
18380                        continue;
18381                    }
18382                    if (DEBUG_SD_INSTALL)
18383                        Log.i(TAG, "Looking for pkg : " + pkgName);
18384
18385                    final PackageSetting ps = mSettings.mPackages.get(pkgName);
18386                    if (ps == null) {
18387                        Slog.i(TAG, "Found stale container " + cid + " with no matching settings");
18388                        continue;
18389                    }
18390
18391                    /*
18392                     * Skip packages that are not external if we're unmounting
18393                     * external storage.
18394                     */
18395                    if (externalStorage && !isMounted && !isExternal(ps)) {
18396                        continue;
18397                    }
18398
18399                    final AsecInstallArgs args = new AsecInstallArgs(cid,
18400                            getAppDexInstructionSets(ps), ps.isForwardLocked());
18401                    // The package status is changed only if the code path
18402                    // matches between settings and the container id.
18403                    if (ps.codePathString != null
18404                            && ps.codePathString.startsWith(args.getCodePath())) {
18405                        if (DEBUG_SD_INSTALL) {
18406                            Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
18407                                    + " at code path: " + ps.codePathString);
18408                        }
18409
18410                        // We do have a valid package installed on sdcard
18411                        processCids.put(args, ps.codePathString);
18412                        final int uid = ps.appId;
18413                        if (uid != -1) {
18414                            uidArr = ArrayUtils.appendInt(uidArr, uid);
18415                        }
18416                    } else {
18417                        Slog.i(TAG, "Found stale container " + cid + ": expected codePath="
18418                                + ps.codePathString);
18419                    }
18420                }
18421            }
18422
18423            Arrays.sort(uidArr);
18424        }
18425
18426        // Process packages with valid entries.
18427        if (isMounted) {
18428            if (DEBUG_SD_INSTALL)
18429                Log.i(TAG, "Loading packages");
18430            loadMediaPackages(processCids, uidArr, externalStorage);
18431            startCleaningPackages();
18432            mInstallerService.onSecureContainersAvailable();
18433        } else {
18434            if (DEBUG_SD_INSTALL)
18435                Log.i(TAG, "Unloading packages");
18436            unloadMediaPackages(processCids, uidArr, reportStatus);
18437        }
18438    }
18439
18440    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
18441            ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) {
18442        final int size = infos.size();
18443        final String[] packageNames = new String[size];
18444        final int[] packageUids = new int[size];
18445        for (int i = 0; i < size; i++) {
18446            final ApplicationInfo info = infos.get(i);
18447            packageNames[i] = info.packageName;
18448            packageUids[i] = info.uid;
18449        }
18450        sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids,
18451                finishedReceiver);
18452    }
18453
18454    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
18455            ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
18456        sendResourcesChangedBroadcast(mediaStatus, replacing,
18457                pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver);
18458    }
18459
18460    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
18461            String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
18462        int size = pkgList.length;
18463        if (size > 0) {
18464            // Send broadcasts here
18465            Bundle extras = new Bundle();
18466            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
18467            if (uidArr != null) {
18468                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
18469            }
18470            if (replacing) {
18471                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
18472            }
18473            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
18474                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
18475            sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null);
18476        }
18477    }
18478
18479   /*
18480     * Look at potentially valid container ids from processCids If package
18481     * information doesn't match the one on record or package scanning fails,
18482     * the cid is added to list of removeCids. We currently don't delete stale
18483     * containers.
18484     */
18485    private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr,
18486            boolean externalStorage) {
18487        ArrayList<String> pkgList = new ArrayList<String>();
18488        Set<AsecInstallArgs> keys = processCids.keySet();
18489
18490        for (AsecInstallArgs args : keys) {
18491            String codePath = processCids.get(args);
18492            if (DEBUG_SD_INSTALL)
18493                Log.i(TAG, "Loading container : " + args.cid);
18494            int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
18495            try {
18496                // Make sure there are no container errors first.
18497                if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
18498                    Slog.e(TAG, "Failed to mount cid : " + args.cid
18499                            + " when installing from sdcard");
18500                    continue;
18501                }
18502                // Check code path here.
18503                if (codePath == null || !codePath.startsWith(args.getCodePath())) {
18504                    Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
18505                            + " does not match one in settings " + codePath);
18506                    continue;
18507                }
18508                // Parse package
18509                int parseFlags = mDefParseFlags;
18510                if (args.isExternalAsec()) {
18511                    parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE;
18512                }
18513                if (args.isFwdLocked()) {
18514                    parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
18515                }
18516
18517                synchronized (mInstallLock) {
18518                    PackageParser.Package pkg = null;
18519                    try {
18520                        // Sadly we don't know the package name yet to freeze it
18521                        pkg = scanPackageTracedLI(new File(codePath), parseFlags,
18522                                SCAN_IGNORE_FROZEN, 0, null);
18523                    } catch (PackageManagerException e) {
18524                        Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage());
18525                    }
18526                    // Scan the package
18527                    if (pkg != null) {
18528                        /*
18529                         * TODO why is the lock being held? doPostInstall is
18530                         * called in other places without the lock. This needs
18531                         * to be straightened out.
18532                         */
18533                        // writer
18534                        synchronized (mPackages) {
18535                            retCode = PackageManager.INSTALL_SUCCEEDED;
18536                            pkgList.add(pkg.packageName);
18537                            // Post process args
18538                            args.doPostInstall(PackageManager.INSTALL_SUCCEEDED,
18539                                    pkg.applicationInfo.uid);
18540                        }
18541                    } else {
18542                        Slog.i(TAG, "Failed to install pkg from  " + codePath + " from sdcard");
18543                    }
18544                }
18545
18546            } finally {
18547                if (retCode != PackageManager.INSTALL_SUCCEEDED) {
18548                    Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode);
18549                }
18550            }
18551        }
18552        // writer
18553        synchronized (mPackages) {
18554            // If the platform SDK has changed since the last time we booted,
18555            // we need to re-grant app permission to catch any new ones that
18556            // appear. This is really a hack, and means that apps can in some
18557            // cases get permissions that the user didn't initially explicitly
18558            // allow... it would be nice to have some better way to handle
18559            // this situation.
18560            final VersionInfo ver = externalStorage ? mSettings.getExternalVersion()
18561                    : mSettings.getInternalVersion();
18562            final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL
18563                    : StorageManager.UUID_PRIVATE_INTERNAL;
18564
18565            int updateFlags = UPDATE_PERMISSIONS_ALL;
18566            if (ver.sdkVersion != mSdkVersion) {
18567                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
18568                        + mSdkVersion + "; regranting permissions for external");
18569                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
18570            }
18571            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
18572
18573            // Yay, everything is now upgraded
18574            ver.forceCurrent();
18575
18576            // can downgrade to reader
18577            // Persist settings
18578            mSettings.writeLPr();
18579        }
18580        // Send a broadcast to let everyone know we are done processing
18581        if (pkgList.size() > 0) {
18582            sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
18583        }
18584    }
18585
18586   /*
18587     * Utility method to unload a list of specified containers
18588     */
18589    private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) {
18590        // Just unmount all valid containers.
18591        for (AsecInstallArgs arg : cidArgs) {
18592            synchronized (mInstallLock) {
18593                arg.doPostDeleteLI(false);
18594           }
18595       }
18596   }
18597
18598    /*
18599     * Unload packages mounted on external media. This involves deleting package
18600     * data from internal structures, sending broadcasts about disabled packages,
18601     * gc'ing to free up references, unmounting all secure containers
18602     * corresponding to packages on external media, and posting a
18603     * UPDATED_MEDIA_STATUS message if status has been requested. Please note
18604     * that we always have to post this message if status has been requested no
18605     * matter what.
18606     */
18607    private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[],
18608            final boolean reportStatus) {
18609        if (DEBUG_SD_INSTALL)
18610            Log.i(TAG, "unloading media packages");
18611        ArrayList<String> pkgList = new ArrayList<String>();
18612        ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>();
18613        final Set<AsecInstallArgs> keys = processCids.keySet();
18614        for (AsecInstallArgs args : keys) {
18615            String pkgName = args.getPackageName();
18616            if (DEBUG_SD_INSTALL)
18617                Log.i(TAG, "Trying to unload pkg : " + pkgName);
18618            // Delete package internally
18619            PackageRemovedInfo outInfo = new PackageRemovedInfo();
18620            synchronized (mInstallLock) {
18621                final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
18622                final boolean res;
18623                try (PackageFreezer freezer = freezePackageForDelete(pkgName, deleteFlags,
18624                        "unloadMediaPackages")) {
18625                    res = deletePackageLIF(pkgName, null, false, null, deleteFlags, outInfo, false,
18626                            null);
18627                }
18628                if (res) {
18629                    pkgList.add(pkgName);
18630                } else {
18631                    Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
18632                    failedList.add(args);
18633                }
18634            }
18635        }
18636
18637        // reader
18638        synchronized (mPackages) {
18639            // We didn't update the settings after removing each package;
18640            // write them now for all packages.
18641            mSettings.writeLPr();
18642        }
18643
18644        // We have to absolutely send UPDATED_MEDIA_STATUS only
18645        // after confirming that all the receivers processed the ordered
18646        // broadcast when packages get disabled, force a gc to clean things up.
18647        // and unload all the containers.
18648        if (pkgList.size() > 0) {
18649            sendResourcesChangedBroadcast(false, false, pkgList, uidArr,
18650                    new IIntentReceiver.Stub() {
18651                public void performReceive(Intent intent, int resultCode, String data,
18652                        Bundle extras, boolean ordered, boolean sticky,
18653                        int sendingUser) throws RemoteException {
18654                    Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
18655                            reportStatus ? 1 : 0, 1, keys);
18656                    mHandler.sendMessage(msg);
18657                }
18658            });
18659        } else {
18660            Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
18661                    keys);
18662            mHandler.sendMessage(msg);
18663        }
18664    }
18665
18666    private void loadPrivatePackages(final VolumeInfo vol) {
18667        mHandler.post(new Runnable() {
18668            @Override
18669            public void run() {
18670                loadPrivatePackagesInner(vol);
18671            }
18672        });
18673    }
18674
18675    private void loadPrivatePackagesInner(VolumeInfo vol) {
18676        final String volumeUuid = vol.fsUuid;
18677        if (TextUtils.isEmpty(volumeUuid)) {
18678            Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring");
18679            return;
18680        }
18681
18682        final ArrayList<PackageFreezer> freezers = new ArrayList<>();
18683        final ArrayList<ApplicationInfo> loaded = new ArrayList<>();
18684        final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE;
18685
18686        final VersionInfo ver;
18687        final List<PackageSetting> packages;
18688        synchronized (mPackages) {
18689            ver = mSettings.findOrCreateVersion(volumeUuid);
18690            packages = mSettings.getVolumePackagesLPr(volumeUuid);
18691        }
18692
18693        for (PackageSetting ps : packages) {
18694            freezers.add(freezePackage(ps.name, "loadPrivatePackagesInner"));
18695            synchronized (mInstallLock) {
18696                final PackageParser.Package pkg;
18697                try {
18698                    pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null);
18699                    loaded.add(pkg.applicationInfo);
18700
18701                } catch (PackageManagerException e) {
18702                    Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage());
18703                }
18704
18705                if (!Build.FINGERPRINT.equals(ver.fingerprint)) {
18706                    clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
18707                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
18708                                    | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
18709                }
18710            }
18711        }
18712
18713        // Reconcile app data for all started/unlocked users
18714        final StorageManager sm = mContext.getSystemService(StorageManager.class);
18715        final UserManager um = mContext.getSystemService(UserManager.class);
18716        for (UserInfo user : um.getUsers()) {
18717            final int flags;
18718            if (um.isUserUnlocked(user.id)) {
18719                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
18720            } else if (um.isUserRunning(user.id)) {
18721                flags = StorageManager.FLAG_STORAGE_DE;
18722            } else {
18723                continue;
18724            }
18725
18726            sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags);
18727            synchronized (mInstallLock) {
18728                reconcileAppsDataLI(volumeUuid, user.id, flags);
18729            }
18730        }
18731
18732        synchronized (mPackages) {
18733            int updateFlags = UPDATE_PERMISSIONS_ALL;
18734            if (ver.sdkVersion != mSdkVersion) {
18735                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
18736                        + mSdkVersion + "; regranting permissions for " + volumeUuid);
18737                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
18738            }
18739            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
18740
18741            // Yay, everything is now upgraded
18742            ver.forceCurrent();
18743
18744            mSettings.writeLPr();
18745        }
18746
18747        for (PackageFreezer freezer : freezers) {
18748            freezer.close();
18749        }
18750
18751        if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded);
18752        sendResourcesChangedBroadcast(true, false, loaded, null);
18753    }
18754
18755    private void unloadPrivatePackages(final VolumeInfo vol) {
18756        mHandler.post(new Runnable() {
18757            @Override
18758            public void run() {
18759                unloadPrivatePackagesInner(vol);
18760            }
18761        });
18762    }
18763
18764    private void unloadPrivatePackagesInner(VolumeInfo vol) {
18765        final String volumeUuid = vol.fsUuid;
18766        if (TextUtils.isEmpty(volumeUuid)) {
18767            Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring");
18768            return;
18769        }
18770
18771        final ArrayList<ApplicationInfo> unloaded = new ArrayList<>();
18772        synchronized (mInstallLock) {
18773        synchronized (mPackages) {
18774            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid);
18775            for (PackageSetting ps : packages) {
18776                if (ps.pkg == null) continue;
18777
18778                final ApplicationInfo info = ps.pkg.applicationInfo;
18779                final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
18780                final PackageRemovedInfo outInfo = new PackageRemovedInfo();
18781
18782                try (PackageFreezer freezer = freezePackageForDelete(ps.name, deleteFlags,
18783                        "unloadPrivatePackagesInner")) {
18784                    if (deletePackageLIF(ps.name, null, false, null, deleteFlags, outInfo,
18785                            false, null)) {
18786                        unloaded.add(info);
18787                    } else {
18788                        Slog.w(TAG, "Failed to unload " + ps.codePath);
18789                    }
18790                }
18791            }
18792
18793            mSettings.writeLPr();
18794        }
18795        }
18796
18797        if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded);
18798        sendResourcesChangedBroadcast(false, false, unloaded, null);
18799    }
18800
18801    /**
18802     * Prepare storage areas for given user on all mounted devices.
18803     */
18804    void prepareUserData(int userId, int userSerial, int flags) {
18805        synchronized (mInstallLock) {
18806            final StorageManager storage = mContext.getSystemService(StorageManager.class);
18807            for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
18808                final String volumeUuid = vol.getFsUuid();
18809                prepareUserDataLI(volumeUuid, userId, userSerial, flags, true);
18810            }
18811        }
18812    }
18813
18814    private void prepareUserDataLI(String volumeUuid, int userId, int userSerial, int flags,
18815            boolean allowRecover) {
18816        // Prepare storage and verify that serial numbers are consistent; if
18817        // there's a mismatch we need to destroy to avoid leaking data
18818        final StorageManager storage = mContext.getSystemService(StorageManager.class);
18819        try {
18820            storage.prepareUserStorage(volumeUuid, userId, userSerial, flags);
18821
18822            if ((flags & StorageManager.FLAG_STORAGE_DE) != 0 && !mOnlyCore) {
18823                UserManagerService.enforceSerialNumber(
18824                        Environment.getDataUserDeDirectory(volumeUuid, userId), userSerial);
18825            }
18826            if ((flags & StorageManager.FLAG_STORAGE_CE) != 0 && !mOnlyCore) {
18827                UserManagerService.enforceSerialNumber(
18828                        Environment.getDataUserCeDirectory(volumeUuid, userId), userSerial);
18829            }
18830
18831            synchronized (mInstallLock) {
18832                mInstaller.createUserData(volumeUuid, userId, userSerial, flags);
18833            }
18834        } catch (Exception e) {
18835            logCriticalInfo(Log.WARN, "Destroying user " + userId + " on volume " + volumeUuid
18836                    + " because we failed to prepare: " + e);
18837            destroyUserDataLI(volumeUuid, userId,
18838                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
18839
18840            if (allowRecover) {
18841                // Try one last time; if we fail again we're really in trouble
18842                prepareUserDataLI(volumeUuid, userId, userSerial, flags, false);
18843            }
18844        }
18845    }
18846
18847    /**
18848     * Destroy storage areas for given user on all mounted devices.
18849     */
18850    void destroyUserData(int userId, int flags) {
18851        synchronized (mInstallLock) {
18852            final StorageManager storage = mContext.getSystemService(StorageManager.class);
18853            for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
18854                final String volumeUuid = vol.getFsUuid();
18855                destroyUserDataLI(volumeUuid, userId, flags);
18856            }
18857        }
18858    }
18859
18860    private void destroyUserDataLI(String volumeUuid, int userId, int flags) {
18861        final StorageManager storage = mContext.getSystemService(StorageManager.class);
18862        try {
18863            // Clean up app data, profile data, and media data
18864            mInstaller.destroyUserData(volumeUuid, userId, flags);
18865
18866            // Clean up system data
18867            if (Objects.equals(volumeUuid, StorageManager.UUID_PRIVATE_INTERNAL)) {
18868                if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) {
18869                    FileUtils.deleteContentsAndDir(Environment.getUserSystemDirectory(userId));
18870                    FileUtils.deleteContentsAndDir(Environment.getDataSystemDeDirectory(userId));
18871                }
18872                if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
18873                    FileUtils.deleteContentsAndDir(Environment.getDataSystemCeDirectory(userId));
18874                }
18875            }
18876
18877            // Data with special labels is now gone, so finish the job
18878            storage.destroyUserStorage(volumeUuid, userId, flags);
18879
18880        } catch (Exception e) {
18881            logCriticalInfo(Log.WARN,
18882                    "Failed to destroy user " + userId + " on volume " + volumeUuid + ": " + e);
18883        }
18884    }
18885
18886    /**
18887     * Examine all users present on given mounted volume, and destroy data
18888     * belonging to users that are no longer valid, or whose user ID has been
18889     * recycled.
18890     */
18891    private void reconcileUsers(String volumeUuid) {
18892        final List<File> files = new ArrayList<>();
18893        Collections.addAll(files, FileUtils
18894                .listFilesOrEmpty(Environment.getDataUserDeDirectory(volumeUuid)));
18895        Collections.addAll(files, FileUtils
18896                .listFilesOrEmpty(Environment.getDataUserCeDirectory(volumeUuid)));
18897        for (File file : files) {
18898            if (!file.isDirectory()) continue;
18899
18900            final int userId;
18901            final UserInfo info;
18902            try {
18903                userId = Integer.parseInt(file.getName());
18904                info = sUserManager.getUserInfo(userId);
18905            } catch (NumberFormatException e) {
18906                Slog.w(TAG, "Invalid user directory " + file);
18907                continue;
18908            }
18909
18910            boolean destroyUser = false;
18911            if (info == null) {
18912                logCriticalInfo(Log.WARN, "Destroying user directory " + file
18913                        + " because no matching user was found");
18914                destroyUser = true;
18915            } else if (!mOnlyCore) {
18916                try {
18917                    UserManagerService.enforceSerialNumber(file, info.serialNumber);
18918                } catch (IOException e) {
18919                    logCriticalInfo(Log.WARN, "Destroying user directory " + file
18920                            + " because we failed to enforce serial number: " + e);
18921                    destroyUser = true;
18922                }
18923            }
18924
18925            if (destroyUser) {
18926                synchronized (mInstallLock) {
18927                    destroyUserDataLI(volumeUuid, userId,
18928                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
18929                }
18930            }
18931        }
18932    }
18933
18934    private void assertPackageKnown(String volumeUuid, String packageName)
18935            throws PackageManagerException {
18936        synchronized (mPackages) {
18937            final PackageSetting ps = mSettings.mPackages.get(packageName);
18938            if (ps == null) {
18939                throw new PackageManagerException("Package " + packageName + " is unknown");
18940            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
18941                throw new PackageManagerException(
18942                        "Package " + packageName + " found on unknown volume " + volumeUuid
18943                                + "; expected volume " + ps.volumeUuid);
18944            }
18945        }
18946    }
18947
18948    private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId)
18949            throws PackageManagerException {
18950        synchronized (mPackages) {
18951            final PackageSetting ps = mSettings.mPackages.get(packageName);
18952            if (ps == null) {
18953                throw new PackageManagerException("Package " + packageName + " is unknown");
18954            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
18955                throw new PackageManagerException(
18956                        "Package " + packageName + " found on unknown volume " + volumeUuid
18957                                + "; expected volume " + ps.volumeUuid);
18958            } else if (!ps.getInstalled(userId)) {
18959                throw new PackageManagerException(
18960                        "Package " + packageName + " not installed for user " + userId);
18961            }
18962        }
18963    }
18964
18965    /**
18966     * Examine all apps present on given mounted volume, and destroy apps that
18967     * aren't expected, either due to uninstallation or reinstallation on
18968     * another volume.
18969     */
18970    private void reconcileApps(String volumeUuid) {
18971        final File[] files = FileUtils
18972                .listFilesOrEmpty(Environment.getDataAppDirectory(volumeUuid));
18973        for (File file : files) {
18974            final boolean isPackage = (isApkFile(file) || file.isDirectory())
18975                    && !PackageInstallerService.isStageName(file.getName());
18976            if (!isPackage) {
18977                // Ignore entries which are not packages
18978                continue;
18979            }
18980
18981            try {
18982                final PackageLite pkg = PackageParser.parsePackageLite(file,
18983                        PackageParser.PARSE_MUST_BE_APK);
18984                assertPackageKnown(volumeUuid, pkg.packageName);
18985
18986            } catch (PackageParserException | PackageManagerException e) {
18987                logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
18988                synchronized (mInstallLock) {
18989                    removeCodePathLI(file);
18990                }
18991            }
18992        }
18993    }
18994
18995    /**
18996     * Reconcile all app data for the given user.
18997     * <p>
18998     * Verifies that directories exist and that ownership and labeling is
18999     * correct for all installed apps on all mounted volumes.
19000     */
19001    void reconcileAppsData(int userId, int flags) {
19002        final StorageManager storage = mContext.getSystemService(StorageManager.class);
19003        for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
19004            final String volumeUuid = vol.getFsUuid();
19005            synchronized (mInstallLock) {
19006                reconcileAppsDataLI(volumeUuid, userId, flags);
19007            }
19008        }
19009    }
19010
19011    /**
19012     * Reconcile all app data on given mounted volume.
19013     * <p>
19014     * Destroys app data that isn't expected, either due to uninstallation or
19015     * reinstallation on another volume.
19016     * <p>
19017     * Verifies that directories exist and that ownership and labeling is
19018     * correct for all installed apps.
19019     */
19020    private void reconcileAppsDataLI(String volumeUuid, int userId, int flags) {
19021        Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x"
19022                + Integer.toHexString(flags));
19023
19024        final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId);
19025        final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId);
19026
19027        boolean restoreconNeeded = false;
19028
19029        // First look for stale data that doesn't belong, and check if things
19030        // have changed since we did our last restorecon
19031        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
19032            if (!isUserKeyUnlocked(userId)) {
19033                throw new RuntimeException(
19034                        "Yikes, someone asked us to reconcile CE storage while " + userId
19035                                + " was still locked; this would have caused massive data loss!");
19036            }
19037
19038            restoreconNeeded |= SELinuxMMAC.isRestoreconNeeded(ceDir);
19039
19040            final File[] files = FileUtils.listFilesOrEmpty(ceDir);
19041            for (File file : files) {
19042                final String packageName = file.getName();
19043                try {
19044                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
19045                } catch (PackageManagerException e) {
19046                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
19047                    try {
19048                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
19049                                StorageManager.FLAG_STORAGE_CE, 0);
19050                    } catch (InstallerException e2) {
19051                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
19052                    }
19053                }
19054            }
19055        }
19056        if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) {
19057            restoreconNeeded |= SELinuxMMAC.isRestoreconNeeded(deDir);
19058
19059            final File[] files = FileUtils.listFilesOrEmpty(deDir);
19060            for (File file : files) {
19061                final String packageName = file.getName();
19062                try {
19063                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
19064                } catch (PackageManagerException e) {
19065                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
19066                    try {
19067                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
19068                                StorageManager.FLAG_STORAGE_DE, 0);
19069                    } catch (InstallerException e2) {
19070                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
19071                    }
19072                }
19073            }
19074        }
19075
19076        // Ensure that data directories are ready to roll for all packages
19077        // installed for this volume and user
19078        final List<PackageSetting> packages;
19079        synchronized (mPackages) {
19080            packages = mSettings.getVolumePackagesLPr(volumeUuid);
19081        }
19082        int preparedCount = 0;
19083        for (PackageSetting ps : packages) {
19084            final String packageName = ps.name;
19085            if (ps.pkg == null) {
19086                Slog.w(TAG, "Odd, missing scanned package " + packageName);
19087                // TODO: might be due to legacy ASEC apps; we should circle back
19088                // and reconcile again once they're scanned
19089                continue;
19090            }
19091
19092            if (ps.getInstalled(userId)) {
19093                prepareAppDataLIF(ps.pkg, userId, flags, restoreconNeeded);
19094
19095                if (maybeMigrateAppDataLIF(ps.pkg, userId)) {
19096                    // We may have just shuffled around app data directories, so
19097                    // prepare them one more time
19098                    prepareAppDataLIF(ps.pkg, userId, flags, restoreconNeeded);
19099                }
19100
19101                preparedCount++;
19102            }
19103        }
19104
19105        if (restoreconNeeded) {
19106            if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
19107                SELinuxMMAC.setRestoreconDone(ceDir);
19108            }
19109            if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) {
19110                SELinuxMMAC.setRestoreconDone(deDir);
19111            }
19112        }
19113
19114        Slog.v(TAG, "reconcileAppsData finished " + preparedCount
19115                + " packages; restoreconNeeded was " + restoreconNeeded);
19116    }
19117
19118    /**
19119     * Prepare app data for the given app just after it was installed or
19120     * upgraded. This method carefully only touches users that it's installed
19121     * for, and it forces a restorecon to handle any seinfo changes.
19122     * <p>
19123     * Verifies that directories exist and that ownership and labeling is
19124     * correct for all installed apps. If there is an ownership mismatch, it
19125     * will try recovering system apps by wiping data; third-party app data is
19126     * left intact.
19127     * <p>
19128     * <em>Note: To avoid a deadlock, do not call this method with {@code mPackages} lock held</em>
19129     */
19130    private void prepareAppDataAfterInstallLIF(PackageParser.Package pkg) {
19131        final PackageSetting ps;
19132        synchronized (mPackages) {
19133            ps = mSettings.mPackages.get(pkg.packageName);
19134            mSettings.writeKernelMappingLPr(ps);
19135        }
19136
19137        final UserManager um = mContext.getSystemService(UserManager.class);
19138        for (UserInfo user : um.getUsers()) {
19139            final int flags;
19140            if (um.isUserUnlocked(user.id)) {
19141                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
19142            } else if (um.isUserRunning(user.id)) {
19143                flags = StorageManager.FLAG_STORAGE_DE;
19144            } else {
19145                continue;
19146            }
19147
19148            if (ps.getInstalled(user.id)) {
19149                // Whenever an app changes, force a restorecon of its data
19150                // TODO: when user data is locked, mark that we're still dirty
19151                prepareAppDataLIF(pkg, user.id, flags, true);
19152            }
19153        }
19154    }
19155
19156    /**
19157     * Prepare app data for the given app.
19158     * <p>
19159     * Verifies that directories exist and that ownership and labeling is
19160     * correct for all installed apps. If there is an ownership mismatch, this
19161     * will try recovering system apps by wiping data; third-party app data is
19162     * left intact.
19163     */
19164    private void prepareAppDataLIF(PackageParser.Package pkg, int userId, int flags,
19165            boolean restoreconNeeded) {
19166        if (pkg == null) {
19167            Slog.wtf(TAG, "Package was null!", new Throwable());
19168            return;
19169        }
19170        prepareAppDataLeafLIF(pkg, userId, flags, restoreconNeeded);
19171        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
19172        for (int i = 0; i < childCount; i++) {
19173            prepareAppDataLeafLIF(pkg.childPackages.get(i), userId, flags, restoreconNeeded);
19174        }
19175    }
19176
19177    private void prepareAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags,
19178            boolean restoreconNeeded) {
19179        if (DEBUG_APP_DATA) {
19180            Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x"
19181                    + Integer.toHexString(flags) + (restoreconNeeded ? " restoreconNeeded" : ""));
19182        }
19183
19184        final String volumeUuid = pkg.volumeUuid;
19185        final String packageName = pkg.packageName;
19186        final ApplicationInfo app = pkg.applicationInfo;
19187        final int appId = UserHandle.getAppId(app.uid);
19188
19189        Preconditions.checkNotNull(app.seinfo);
19190
19191        try {
19192            mInstaller.createAppData(volumeUuid, packageName, userId, flags,
19193                    appId, app.seinfo, app.targetSdkVersion);
19194        } catch (InstallerException e) {
19195            if (app.isSystemApp()) {
19196                logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName
19197                        + ", but trying to recover: " + e);
19198                destroyAppDataLeafLIF(pkg, userId, flags);
19199                try {
19200                    mInstaller.createAppData(volumeUuid, packageName, userId, flags,
19201                            appId, app.seinfo, app.targetSdkVersion);
19202                    logCriticalInfo(Log.DEBUG, "Recovery succeeded!");
19203                } catch (InstallerException e2) {
19204                    logCriticalInfo(Log.DEBUG, "Recovery failed!");
19205                }
19206            } else {
19207                Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e);
19208            }
19209        }
19210
19211        if (restoreconNeeded) {
19212            try {
19213                mInstaller.restoreconAppData(volumeUuid, packageName, userId, flags, appId,
19214                        app.seinfo);
19215            } catch (InstallerException e) {
19216                Slog.e(TAG, "Failed to restorecon for " + packageName + ": " + e);
19217            }
19218        }
19219
19220        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
19221            try {
19222                // CE storage is unlocked right now, so read out the inode and
19223                // remember for use later when it's locked
19224                // TODO: mark this structure as dirty so we persist it!
19225                final long ceDataInode = mInstaller.getAppDataInode(volumeUuid, packageName, userId,
19226                        StorageManager.FLAG_STORAGE_CE);
19227                synchronized (mPackages) {
19228                    final PackageSetting ps = mSettings.mPackages.get(packageName);
19229                    if (ps != null) {
19230                        ps.setCeDataInode(ceDataInode, userId);
19231                    }
19232                }
19233            } catch (InstallerException e) {
19234                Slog.e(TAG, "Failed to find inode for " + packageName + ": " + e);
19235            }
19236        }
19237
19238        prepareAppDataContentsLeafLIF(pkg, userId, flags);
19239    }
19240
19241    private void prepareAppDataContentsLIF(PackageParser.Package pkg, int userId, int flags) {
19242        if (pkg == null) {
19243            Slog.wtf(TAG, "Package was null!", new Throwable());
19244            return;
19245        }
19246        prepareAppDataContentsLeafLIF(pkg, userId, flags);
19247        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
19248        for (int i = 0; i < childCount; i++) {
19249            prepareAppDataContentsLeafLIF(pkg.childPackages.get(i), userId, flags);
19250        }
19251    }
19252
19253    private void prepareAppDataContentsLeafLIF(PackageParser.Package pkg, int userId, int flags) {
19254        final String volumeUuid = pkg.volumeUuid;
19255        final String packageName = pkg.packageName;
19256        final ApplicationInfo app = pkg.applicationInfo;
19257
19258        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
19259            // Create a native library symlink only if we have native libraries
19260            // and if the native libraries are 32 bit libraries. We do not provide
19261            // this symlink for 64 bit libraries.
19262            if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) {
19263                final String nativeLibPath = app.nativeLibraryDir;
19264                try {
19265                    mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName,
19266                            nativeLibPath, userId);
19267                } catch (InstallerException e) {
19268                    Slog.e(TAG, "Failed to link native for " + packageName + ": " + e);
19269                }
19270            }
19271        }
19272    }
19273
19274    /**
19275     * For system apps on non-FBE devices, this method migrates any existing
19276     * CE/DE data to match the {@code defaultToDeviceProtectedStorage} flag
19277     * requested by the app.
19278     */
19279    private boolean maybeMigrateAppDataLIF(PackageParser.Package pkg, int userId) {
19280        if (pkg.isSystemApp() && !StorageManager.isFileEncryptedNativeOrEmulated()
19281                && PackageManager.APPLY_DEFAULT_TO_DEVICE_PROTECTED_STORAGE) {
19282            final int storageTarget = pkg.applicationInfo.isDefaultToDeviceProtectedStorage()
19283                    ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE;
19284            try {
19285                mInstaller.migrateAppData(pkg.volumeUuid, pkg.packageName, userId,
19286                        storageTarget);
19287            } catch (InstallerException e) {
19288                logCriticalInfo(Log.WARN,
19289                        "Failed to migrate " + pkg.packageName + ": " + e.getMessage());
19290            }
19291            return true;
19292        } else {
19293            return false;
19294        }
19295    }
19296
19297    public PackageFreezer freezePackage(String packageName, String killReason) {
19298        return new PackageFreezer(packageName, killReason);
19299    }
19300
19301    public PackageFreezer freezePackageForInstall(String packageName, int installFlags,
19302            String killReason) {
19303        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
19304            return new PackageFreezer();
19305        } else {
19306            return freezePackage(packageName, killReason);
19307        }
19308    }
19309
19310    public PackageFreezer freezePackageForDelete(String packageName, int deleteFlags,
19311            String killReason) {
19312        if ((deleteFlags & PackageManager.DELETE_DONT_KILL_APP) != 0) {
19313            return new PackageFreezer();
19314        } else {
19315            return freezePackage(packageName, killReason);
19316        }
19317    }
19318
19319    /**
19320     * Class that freezes and kills the given package upon creation, and
19321     * unfreezes it upon closing. This is typically used when doing surgery on
19322     * app code/data to prevent the app from running while you're working.
19323     */
19324    private class PackageFreezer implements AutoCloseable {
19325        private final String mPackageName;
19326        private final PackageFreezer[] mChildren;
19327
19328        private final boolean mWeFroze;
19329
19330        private final AtomicBoolean mClosed = new AtomicBoolean();
19331        private final CloseGuard mCloseGuard = CloseGuard.get();
19332
19333        /**
19334         * Create and return a stub freezer that doesn't actually do anything,
19335         * typically used when someone requested
19336         * {@link PackageManager#INSTALL_DONT_KILL_APP} or
19337         * {@link PackageManager#DELETE_DONT_KILL_APP}.
19338         */
19339        public PackageFreezer() {
19340            mPackageName = null;
19341            mChildren = null;
19342            mWeFroze = false;
19343            mCloseGuard.open("close");
19344        }
19345
19346        public PackageFreezer(String packageName, String killReason) {
19347            synchronized (mPackages) {
19348                mPackageName = packageName;
19349                mWeFroze = mFrozenPackages.add(mPackageName);
19350
19351                final PackageSetting ps = mSettings.mPackages.get(mPackageName);
19352                if (ps != null) {
19353                    killApplication(ps.name, ps.appId, killReason);
19354                }
19355
19356                final PackageParser.Package p = mPackages.get(packageName);
19357                if (p != null && p.childPackages != null) {
19358                    final int N = p.childPackages.size();
19359                    mChildren = new PackageFreezer[N];
19360                    for (int i = 0; i < N; i++) {
19361                        mChildren[i] = new PackageFreezer(p.childPackages.get(i).packageName,
19362                                killReason);
19363                    }
19364                } else {
19365                    mChildren = null;
19366                }
19367            }
19368            mCloseGuard.open("close");
19369        }
19370
19371        @Override
19372        protected void finalize() throws Throwable {
19373            try {
19374                mCloseGuard.warnIfOpen();
19375                close();
19376            } finally {
19377                super.finalize();
19378            }
19379        }
19380
19381        @Override
19382        public void close() {
19383            mCloseGuard.close();
19384            if (mClosed.compareAndSet(false, true)) {
19385                synchronized (mPackages) {
19386                    if (mWeFroze) {
19387                        mFrozenPackages.remove(mPackageName);
19388                    }
19389
19390                    if (mChildren != null) {
19391                        for (PackageFreezer freezer : mChildren) {
19392                            freezer.close();
19393                        }
19394                    }
19395                }
19396            }
19397        }
19398    }
19399
19400    /**
19401     * Verify that given package is currently frozen.
19402     */
19403    private void checkPackageFrozen(String packageName) {
19404        synchronized (mPackages) {
19405            if (!mFrozenPackages.contains(packageName)) {
19406                Slog.wtf(TAG, "Expected " + packageName + " to be frozen!", new Throwable());
19407            }
19408        }
19409    }
19410
19411    @Override
19412    public int movePackage(final String packageName, final String volumeUuid) {
19413        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
19414
19415        final UserHandle user = new UserHandle(UserHandle.getCallingUserId());
19416        final int moveId = mNextMoveId.getAndIncrement();
19417        mHandler.post(new Runnable() {
19418            @Override
19419            public void run() {
19420                try {
19421                    movePackageInternal(packageName, volumeUuid, moveId, user);
19422                } catch (PackageManagerException e) {
19423                    Slog.w(TAG, "Failed to move " + packageName, e);
19424                    mMoveCallbacks.notifyStatusChanged(moveId,
19425                            PackageManager.MOVE_FAILED_INTERNAL_ERROR);
19426                }
19427            }
19428        });
19429        return moveId;
19430    }
19431
19432    private void movePackageInternal(final String packageName, final String volumeUuid,
19433            final int moveId, UserHandle user) throws PackageManagerException {
19434        final StorageManager storage = mContext.getSystemService(StorageManager.class);
19435        final PackageManager pm = mContext.getPackageManager();
19436
19437        final boolean currentAsec;
19438        final String currentVolumeUuid;
19439        final File codeFile;
19440        final String installerPackageName;
19441        final String packageAbiOverride;
19442        final int appId;
19443        final String seinfo;
19444        final String label;
19445        final int targetSdkVersion;
19446        final PackageFreezer freezer;
19447
19448        // reader
19449        synchronized (mPackages) {
19450            final PackageParser.Package pkg = mPackages.get(packageName);
19451            final PackageSetting ps = mSettings.mPackages.get(packageName);
19452            if (pkg == null || ps == null) {
19453                throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package");
19454            }
19455
19456            if (pkg.applicationInfo.isSystemApp()) {
19457                throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE,
19458                        "Cannot move system application");
19459            }
19460
19461            if (pkg.applicationInfo.isExternalAsec()) {
19462                currentAsec = true;
19463                currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL;
19464            } else if (pkg.applicationInfo.isForwardLocked()) {
19465                currentAsec = true;
19466                currentVolumeUuid = "forward_locked";
19467            } else {
19468                currentAsec = false;
19469                currentVolumeUuid = ps.volumeUuid;
19470
19471                final File probe = new File(pkg.codePath);
19472                final File probeOat = new File(probe, "oat");
19473                if (!probe.isDirectory() || !probeOat.isDirectory()) {
19474                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
19475                            "Move only supported for modern cluster style installs");
19476                }
19477            }
19478
19479            if (Objects.equals(currentVolumeUuid, volumeUuid)) {
19480                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
19481                        "Package already moved to " + volumeUuid);
19482            }
19483            if (pkg.applicationInfo.isInternal() && isPackageDeviceAdminOnAnyUser(packageName)) {
19484                throw new PackageManagerException(MOVE_FAILED_DEVICE_ADMIN,
19485                        "Device admin cannot be moved");
19486            }
19487
19488            if (mFrozenPackages.contains(packageName)) {
19489                throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING,
19490                        "Failed to move already frozen package");
19491            }
19492
19493            codeFile = new File(pkg.codePath);
19494            installerPackageName = ps.installerPackageName;
19495            packageAbiOverride = ps.cpuAbiOverrideString;
19496            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
19497            seinfo = pkg.applicationInfo.seinfo;
19498            label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo));
19499            targetSdkVersion = pkg.applicationInfo.targetSdkVersion;
19500            freezer = new PackageFreezer(packageName, "movePackageInternal");
19501        }
19502
19503        final Bundle extras = new Bundle();
19504        extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName);
19505        extras.putString(Intent.EXTRA_TITLE, label);
19506        mMoveCallbacks.notifyCreated(moveId, extras);
19507
19508        int installFlags;
19509        final boolean moveCompleteApp;
19510        final File measurePath;
19511
19512        if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) {
19513            installFlags = INSTALL_INTERNAL;
19514            moveCompleteApp = !currentAsec;
19515            measurePath = Environment.getDataAppDirectory(volumeUuid);
19516        } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) {
19517            installFlags = INSTALL_EXTERNAL;
19518            moveCompleteApp = false;
19519            measurePath = storage.getPrimaryPhysicalVolume().getPath();
19520        } else {
19521            final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid);
19522            if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE
19523                    || !volume.isMountedWritable()) {
19524                freezer.close();
19525                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
19526                        "Move location not mounted private volume");
19527            }
19528
19529            Preconditions.checkState(!currentAsec);
19530
19531            installFlags = INSTALL_INTERNAL;
19532            moveCompleteApp = true;
19533            measurePath = Environment.getDataAppDirectory(volumeUuid);
19534        }
19535
19536        final PackageStats stats = new PackageStats(null, -1);
19537        synchronized (mInstaller) {
19538            if (!getPackageSizeInfoLI(packageName, -1, stats)) {
19539                freezer.close();
19540                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
19541                        "Failed to measure package size");
19542            }
19543        }
19544
19545        if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size "
19546                + stats.dataSize);
19547
19548        final long startFreeBytes = measurePath.getFreeSpace();
19549        final long sizeBytes;
19550        if (moveCompleteApp) {
19551            sizeBytes = stats.codeSize + stats.dataSize;
19552        } else {
19553            sizeBytes = stats.codeSize;
19554        }
19555
19556        if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) {
19557            freezer.close();
19558            throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
19559                    "Not enough free space to move");
19560        }
19561
19562        mMoveCallbacks.notifyStatusChanged(moveId, 10);
19563
19564        final CountDownLatch installedLatch = new CountDownLatch(1);
19565        final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
19566            @Override
19567            public void onUserActionRequired(Intent intent) throws RemoteException {
19568                throw new IllegalStateException();
19569            }
19570
19571            @Override
19572            public void onPackageInstalled(String basePackageName, int returnCode, String msg,
19573                    Bundle extras) throws RemoteException {
19574                if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: "
19575                        + PackageManager.installStatusToString(returnCode, msg));
19576
19577                installedLatch.countDown();
19578                freezer.close();
19579
19580                final int status = PackageManager.installStatusToPublicStatus(returnCode);
19581                switch (status) {
19582                    case PackageInstaller.STATUS_SUCCESS:
19583                        mMoveCallbacks.notifyStatusChanged(moveId,
19584                                PackageManager.MOVE_SUCCEEDED);
19585                        break;
19586                    case PackageInstaller.STATUS_FAILURE_STORAGE:
19587                        mMoveCallbacks.notifyStatusChanged(moveId,
19588                                PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
19589                        break;
19590                    default:
19591                        mMoveCallbacks.notifyStatusChanged(moveId,
19592                                PackageManager.MOVE_FAILED_INTERNAL_ERROR);
19593                        break;
19594                }
19595            }
19596        };
19597
19598        final MoveInfo move;
19599        if (moveCompleteApp) {
19600            // Kick off a thread to report progress estimates
19601            new Thread() {
19602                @Override
19603                public void run() {
19604                    while (true) {
19605                        try {
19606                            if (installedLatch.await(1, TimeUnit.SECONDS)) {
19607                                break;
19608                            }
19609                        } catch (InterruptedException ignored) {
19610                        }
19611
19612                        final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace();
19613                        final int progress = 10 + (int) MathUtils.constrain(
19614                                ((deltaFreeBytes * 80) / sizeBytes), 0, 80);
19615                        mMoveCallbacks.notifyStatusChanged(moveId, progress);
19616                    }
19617                }
19618            }.start();
19619
19620            final String dataAppName = codeFile.getName();
19621            move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName,
19622                    dataAppName, appId, seinfo, targetSdkVersion);
19623        } else {
19624            move = null;
19625        }
19626
19627        installFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
19628
19629        final Message msg = mHandler.obtainMessage(INIT_COPY);
19630        final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
19631        final InstallParams params = new InstallParams(origin, move, installObserver, installFlags,
19632                installerPackageName, volumeUuid, null /*verificationInfo*/, user,
19633                packageAbiOverride, null /*grantedPermissions*/, null /*certificates*/);
19634        params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params));
19635        msg.obj = params;
19636
19637        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage",
19638                System.identityHashCode(msg.obj));
19639        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
19640                System.identityHashCode(msg.obj));
19641
19642        mHandler.sendMessage(msg);
19643    }
19644
19645    @Override
19646    public int movePrimaryStorage(String volumeUuid) throws RemoteException {
19647        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
19648
19649        final int realMoveId = mNextMoveId.getAndIncrement();
19650        final Bundle extras = new Bundle();
19651        extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid);
19652        mMoveCallbacks.notifyCreated(realMoveId, extras);
19653
19654        final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() {
19655            @Override
19656            public void onCreated(int moveId, Bundle extras) {
19657                // Ignored
19658            }
19659
19660            @Override
19661            public void onStatusChanged(int moveId, int status, long estMillis) {
19662                mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis);
19663            }
19664        };
19665
19666        final StorageManager storage = mContext.getSystemService(StorageManager.class);
19667        storage.setPrimaryStorageUuid(volumeUuid, callback);
19668        return realMoveId;
19669    }
19670
19671    @Override
19672    public int getMoveStatus(int moveId) {
19673        mContext.enforceCallingOrSelfPermission(
19674                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
19675        return mMoveCallbacks.mLastStatus.get(moveId);
19676    }
19677
19678    @Override
19679    public void registerMoveCallback(IPackageMoveObserver callback) {
19680        mContext.enforceCallingOrSelfPermission(
19681                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
19682        mMoveCallbacks.register(callback);
19683    }
19684
19685    @Override
19686    public void unregisterMoveCallback(IPackageMoveObserver callback) {
19687        mContext.enforceCallingOrSelfPermission(
19688                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
19689        mMoveCallbacks.unregister(callback);
19690    }
19691
19692    @Override
19693    public boolean setInstallLocation(int loc) {
19694        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
19695                null);
19696        if (getInstallLocation() == loc) {
19697            return true;
19698        }
19699        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
19700                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
19701            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
19702                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
19703            return true;
19704        }
19705        return false;
19706   }
19707
19708    @Override
19709    public int getInstallLocation() {
19710        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
19711                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
19712                PackageHelper.APP_INSTALL_AUTO);
19713    }
19714
19715    /** Called by UserManagerService */
19716    void cleanUpUser(UserManagerService userManager, int userHandle) {
19717        synchronized (mPackages) {
19718            mDirtyUsers.remove(userHandle);
19719            mUserNeedsBadging.delete(userHandle);
19720            mSettings.removeUserLPw(userHandle);
19721            mPendingBroadcasts.remove(userHandle);
19722            mEphemeralApplicationRegistry.onUserRemovedLPw(userHandle);
19723            removeUnusedPackagesLPw(userManager, userHandle);
19724        }
19725    }
19726
19727    /**
19728     * We're removing userHandle and would like to remove any downloaded packages
19729     * that are no longer in use by any other user.
19730     * @param userHandle the user being removed
19731     */
19732    private void removeUnusedPackagesLPw(UserManagerService userManager, final int userHandle) {
19733        final boolean DEBUG_CLEAN_APKS = false;
19734        int [] users = userManager.getUserIds();
19735        Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
19736        while (psit.hasNext()) {
19737            PackageSetting ps = psit.next();
19738            if (ps.pkg == null) {
19739                continue;
19740            }
19741            final String packageName = ps.pkg.packageName;
19742            // Skip over if system app
19743            if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
19744                continue;
19745            }
19746            if (DEBUG_CLEAN_APKS) {
19747                Slog.i(TAG, "Checking package " + packageName);
19748            }
19749            boolean keep = shouldKeepUninstalledPackageLPr(packageName);
19750            if (keep) {
19751                if (DEBUG_CLEAN_APKS) {
19752                    Slog.i(TAG, "  Keeping package " + packageName + " - requested by DO");
19753                }
19754            } else {
19755                for (int i = 0; i < users.length; i++) {
19756                    if (users[i] != userHandle && ps.getInstalled(users[i])) {
19757                        keep = true;
19758                        if (DEBUG_CLEAN_APKS) {
19759                            Slog.i(TAG, "  Keeping package " + packageName + " for user "
19760                                    + users[i]);
19761                        }
19762                        break;
19763                    }
19764                }
19765            }
19766            if (!keep) {
19767                if (DEBUG_CLEAN_APKS) {
19768                    Slog.i(TAG, "  Removing package " + packageName);
19769                }
19770                mHandler.post(new Runnable() {
19771                    public void run() {
19772                        deletePackageX(packageName, userHandle, 0);
19773                    } //end run
19774                });
19775            }
19776        }
19777    }
19778
19779    /** Called by UserManagerService */
19780    void createNewUser(int userHandle) {
19781        synchronized (mInstallLock) {
19782            mSettings.createNewUserLI(this, mInstaller, userHandle);
19783        }
19784        synchronized (mPackages) {
19785            applyFactoryDefaultBrowserLPw(userHandle);
19786            primeDomainVerificationsLPw(userHandle);
19787        }
19788    }
19789
19790    void newUserCreated(final int userHandle) {
19791        mDefaultPermissionPolicy.grantDefaultPermissions(userHandle);
19792        // If permission review for legacy apps is required, we represent
19793        // dagerous permissions for such apps as always granted runtime
19794        // permissions to keep per user flag state whether review is needed.
19795        // Hence, if a new user is added we have to propagate dangerous
19796        // permission grants for these legacy apps.
19797        if (Build.PERMISSIONS_REVIEW_REQUIRED) {
19798            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
19799                    | UPDATE_PERMISSIONS_REPLACE_ALL);
19800        }
19801    }
19802
19803    @Override
19804    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
19805        mContext.enforceCallingOrSelfPermission(
19806                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
19807                "Only package verification agents can read the verifier device identity");
19808
19809        synchronized (mPackages) {
19810            return mSettings.getVerifierDeviceIdentityLPw();
19811        }
19812    }
19813
19814    @Override
19815    public void setPermissionEnforced(String permission, boolean enforced) {
19816        // TODO: Now that we no longer change GID for storage, this should to away.
19817        mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
19818                "setPermissionEnforced");
19819        if (READ_EXTERNAL_STORAGE.equals(permission)) {
19820            synchronized (mPackages) {
19821                if (mSettings.mReadExternalStorageEnforced == null
19822                        || mSettings.mReadExternalStorageEnforced != enforced) {
19823                    mSettings.mReadExternalStorageEnforced = enforced;
19824                    mSettings.writeLPr();
19825                }
19826            }
19827            // kill any non-foreground processes so we restart them and
19828            // grant/revoke the GID.
19829            final IActivityManager am = ActivityManagerNative.getDefault();
19830            if (am != null) {
19831                final long token = Binder.clearCallingIdentity();
19832                try {
19833                    am.killProcessesBelowForeground("setPermissionEnforcement");
19834                } catch (RemoteException e) {
19835                } finally {
19836                    Binder.restoreCallingIdentity(token);
19837                }
19838            }
19839        } else {
19840            throw new IllegalArgumentException("No selective enforcement for " + permission);
19841        }
19842    }
19843
19844    @Override
19845    @Deprecated
19846    public boolean isPermissionEnforced(String permission) {
19847        return true;
19848    }
19849
19850    @Override
19851    public boolean isStorageLow() {
19852        final long token = Binder.clearCallingIdentity();
19853        try {
19854            final DeviceStorageMonitorInternal
19855                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
19856            if (dsm != null) {
19857                return dsm.isMemoryLow();
19858            } else {
19859                return false;
19860            }
19861        } finally {
19862            Binder.restoreCallingIdentity(token);
19863        }
19864    }
19865
19866    @Override
19867    public IPackageInstaller getPackageInstaller() {
19868        return mInstallerService;
19869    }
19870
19871    private boolean userNeedsBadging(int userId) {
19872        int index = mUserNeedsBadging.indexOfKey(userId);
19873        if (index < 0) {
19874            final UserInfo userInfo;
19875            final long token = Binder.clearCallingIdentity();
19876            try {
19877                userInfo = sUserManager.getUserInfo(userId);
19878            } finally {
19879                Binder.restoreCallingIdentity(token);
19880            }
19881            final boolean b;
19882            if (userInfo != null && userInfo.isManagedProfile()) {
19883                b = true;
19884            } else {
19885                b = false;
19886            }
19887            mUserNeedsBadging.put(userId, b);
19888            return b;
19889        }
19890        return mUserNeedsBadging.valueAt(index);
19891    }
19892
19893    @Override
19894    public KeySet getKeySetByAlias(String packageName, String alias) {
19895        if (packageName == null || alias == null) {
19896            return null;
19897        }
19898        synchronized(mPackages) {
19899            final PackageParser.Package pkg = mPackages.get(packageName);
19900            if (pkg == null) {
19901                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
19902                throw new IllegalArgumentException("Unknown package: " + packageName);
19903            }
19904            KeySetManagerService ksms = mSettings.mKeySetManagerService;
19905            return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
19906        }
19907    }
19908
19909    @Override
19910    public KeySet getSigningKeySet(String packageName) {
19911        if (packageName == null) {
19912            return null;
19913        }
19914        synchronized(mPackages) {
19915            final PackageParser.Package pkg = mPackages.get(packageName);
19916            if (pkg == null) {
19917                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
19918                throw new IllegalArgumentException("Unknown package: " + packageName);
19919            }
19920            if (pkg.applicationInfo.uid != Binder.getCallingUid()
19921                    && Process.SYSTEM_UID != Binder.getCallingUid()) {
19922                throw new SecurityException("May not access signing KeySet of other apps.");
19923            }
19924            KeySetManagerService ksms = mSettings.mKeySetManagerService;
19925            return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
19926        }
19927    }
19928
19929    @Override
19930    public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
19931        if (packageName == null || ks == null) {
19932            return false;
19933        }
19934        synchronized(mPackages) {
19935            final PackageParser.Package pkg = mPackages.get(packageName);
19936            if (pkg == null) {
19937                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
19938                throw new IllegalArgumentException("Unknown package: " + packageName);
19939            }
19940            IBinder ksh = ks.getToken();
19941            if (ksh instanceof KeySetHandle) {
19942                KeySetManagerService ksms = mSettings.mKeySetManagerService;
19943                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
19944            }
19945            return false;
19946        }
19947    }
19948
19949    @Override
19950    public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
19951        if (packageName == null || ks == null) {
19952            return false;
19953        }
19954        synchronized(mPackages) {
19955            final PackageParser.Package pkg = mPackages.get(packageName);
19956            if (pkg == null) {
19957                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
19958                throw new IllegalArgumentException("Unknown package: " + packageName);
19959            }
19960            IBinder ksh = ks.getToken();
19961            if (ksh instanceof KeySetHandle) {
19962                KeySetManagerService ksms = mSettings.mKeySetManagerService;
19963                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
19964            }
19965            return false;
19966        }
19967    }
19968
19969    private void deletePackageIfUnusedLPr(final String packageName) {
19970        PackageSetting ps = mSettings.mPackages.get(packageName);
19971        if (ps == null) {
19972            return;
19973        }
19974        if (!ps.isAnyInstalled(sUserManager.getUserIds())) {
19975            // TODO Implement atomic delete if package is unused
19976            // It is currently possible that the package will be deleted even if it is installed
19977            // after this method returns.
19978            mHandler.post(new Runnable() {
19979                public void run() {
19980                    deletePackageX(packageName, 0, PackageManager.DELETE_ALL_USERS);
19981                }
19982            });
19983        }
19984    }
19985
19986    /**
19987     * Check and throw if the given before/after packages would be considered a
19988     * downgrade.
19989     */
19990    private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after)
19991            throws PackageManagerException {
19992        if (after.versionCode < before.mVersionCode) {
19993            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
19994                    "Update version code " + after.versionCode + " is older than current "
19995                    + before.mVersionCode);
19996        } else if (after.versionCode == before.mVersionCode) {
19997            if (after.baseRevisionCode < before.baseRevisionCode) {
19998                throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
19999                        "Update base revision code " + after.baseRevisionCode
20000                        + " is older than current " + before.baseRevisionCode);
20001            }
20002
20003            if (!ArrayUtils.isEmpty(after.splitNames)) {
20004                for (int i = 0; i < after.splitNames.length; i++) {
20005                    final String splitName = after.splitNames[i];
20006                    final int j = ArrayUtils.indexOf(before.splitNames, splitName);
20007                    if (j != -1) {
20008                        if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) {
20009                            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
20010                                    "Update split " + splitName + " revision code "
20011                                    + after.splitRevisionCodes[i] + " is older than current "
20012                                    + before.splitRevisionCodes[j]);
20013                        }
20014                    }
20015                }
20016            }
20017        }
20018    }
20019
20020    private static class MoveCallbacks extends Handler {
20021        private static final int MSG_CREATED = 1;
20022        private static final int MSG_STATUS_CHANGED = 2;
20023
20024        private final RemoteCallbackList<IPackageMoveObserver>
20025                mCallbacks = new RemoteCallbackList<>();
20026
20027        private final SparseIntArray mLastStatus = new SparseIntArray();
20028
20029        public MoveCallbacks(Looper looper) {
20030            super(looper);
20031        }
20032
20033        public void register(IPackageMoveObserver callback) {
20034            mCallbacks.register(callback);
20035        }
20036
20037        public void unregister(IPackageMoveObserver callback) {
20038            mCallbacks.unregister(callback);
20039        }
20040
20041        @Override
20042        public void handleMessage(Message msg) {
20043            final SomeArgs args = (SomeArgs) msg.obj;
20044            final int n = mCallbacks.beginBroadcast();
20045            for (int i = 0; i < n; i++) {
20046                final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i);
20047                try {
20048                    invokeCallback(callback, msg.what, args);
20049                } catch (RemoteException ignored) {
20050                }
20051            }
20052            mCallbacks.finishBroadcast();
20053            args.recycle();
20054        }
20055
20056        private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args)
20057                throws RemoteException {
20058            switch (what) {
20059                case MSG_CREATED: {
20060                    callback.onCreated(args.argi1, (Bundle) args.arg2);
20061                    break;
20062                }
20063                case MSG_STATUS_CHANGED: {
20064                    callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3);
20065                    break;
20066                }
20067            }
20068        }
20069
20070        private void notifyCreated(int moveId, Bundle extras) {
20071            Slog.v(TAG, "Move " + moveId + " created " + extras.toString());
20072
20073            final SomeArgs args = SomeArgs.obtain();
20074            args.argi1 = moveId;
20075            args.arg2 = extras;
20076            obtainMessage(MSG_CREATED, args).sendToTarget();
20077        }
20078
20079        private void notifyStatusChanged(int moveId, int status) {
20080            notifyStatusChanged(moveId, status, -1);
20081        }
20082
20083        private void notifyStatusChanged(int moveId, int status, long estMillis) {
20084            Slog.v(TAG, "Move " + moveId + " status " + status);
20085
20086            final SomeArgs args = SomeArgs.obtain();
20087            args.argi1 = moveId;
20088            args.argi2 = status;
20089            args.arg3 = estMillis;
20090            obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget();
20091
20092            synchronized (mLastStatus) {
20093                mLastStatus.put(moveId, status);
20094            }
20095        }
20096    }
20097
20098    private final static class OnPermissionChangeListeners extends Handler {
20099        private static final int MSG_ON_PERMISSIONS_CHANGED = 1;
20100
20101        private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners =
20102                new RemoteCallbackList<>();
20103
20104        public OnPermissionChangeListeners(Looper looper) {
20105            super(looper);
20106        }
20107
20108        @Override
20109        public void handleMessage(Message msg) {
20110            switch (msg.what) {
20111                case MSG_ON_PERMISSIONS_CHANGED: {
20112                    final int uid = msg.arg1;
20113                    handleOnPermissionsChanged(uid);
20114                } break;
20115            }
20116        }
20117
20118        public void addListenerLocked(IOnPermissionsChangeListener listener) {
20119            mPermissionListeners.register(listener);
20120
20121        }
20122
20123        public void removeListenerLocked(IOnPermissionsChangeListener listener) {
20124            mPermissionListeners.unregister(listener);
20125        }
20126
20127        public void onPermissionsChanged(int uid) {
20128            if (mPermissionListeners.getRegisteredCallbackCount() > 0) {
20129                obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget();
20130            }
20131        }
20132
20133        private void handleOnPermissionsChanged(int uid) {
20134            final int count = mPermissionListeners.beginBroadcast();
20135            try {
20136                for (int i = 0; i < count; i++) {
20137                    IOnPermissionsChangeListener callback = mPermissionListeners
20138                            .getBroadcastItem(i);
20139                    try {
20140                        callback.onPermissionsChanged(uid);
20141                    } catch (RemoteException e) {
20142                        Log.e(TAG, "Permission listener is dead", e);
20143                    }
20144                }
20145            } finally {
20146                mPermissionListeners.finishBroadcast();
20147            }
20148        }
20149    }
20150
20151    private class PackageManagerInternalImpl extends PackageManagerInternal {
20152        @Override
20153        public void setLocationPackagesProvider(PackagesProvider provider) {
20154            synchronized (mPackages) {
20155                mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider);
20156            }
20157        }
20158
20159        @Override
20160        public void setVoiceInteractionPackagesProvider(PackagesProvider provider) {
20161            synchronized (mPackages) {
20162                mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider);
20163            }
20164        }
20165
20166        @Override
20167        public void setSmsAppPackagesProvider(PackagesProvider provider) {
20168            synchronized (mPackages) {
20169                mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider);
20170            }
20171        }
20172
20173        @Override
20174        public void setDialerAppPackagesProvider(PackagesProvider provider) {
20175            synchronized (mPackages) {
20176                mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider);
20177            }
20178        }
20179
20180        @Override
20181        public void setSimCallManagerPackagesProvider(PackagesProvider provider) {
20182            synchronized (mPackages) {
20183                mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider);
20184            }
20185        }
20186
20187        @Override
20188        public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) {
20189            synchronized (mPackages) {
20190                mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider);
20191            }
20192        }
20193
20194        @Override
20195        public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) {
20196            synchronized (mPackages) {
20197                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr(
20198                        packageName, userId);
20199            }
20200        }
20201
20202        @Override
20203        public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) {
20204            synchronized (mPackages) {
20205                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr(
20206                        packageName, userId);
20207            }
20208        }
20209
20210        @Override
20211        public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) {
20212            synchronized (mPackages) {
20213                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr(
20214                        packageName, userId);
20215            }
20216        }
20217
20218        @Override
20219        public void setKeepUninstalledPackages(final List<String> packageList) {
20220            Preconditions.checkNotNull(packageList);
20221            List<String> removedFromList = null;
20222            synchronized (mPackages) {
20223                if (mKeepUninstalledPackages != null) {
20224                    final int packagesCount = mKeepUninstalledPackages.size();
20225                    for (int i = 0; i < packagesCount; i++) {
20226                        String oldPackage = mKeepUninstalledPackages.get(i);
20227                        if (packageList != null && packageList.contains(oldPackage)) {
20228                            continue;
20229                        }
20230                        if (removedFromList == null) {
20231                            removedFromList = new ArrayList<>();
20232                        }
20233                        removedFromList.add(oldPackage);
20234                    }
20235                }
20236                mKeepUninstalledPackages = new ArrayList<>(packageList);
20237                if (removedFromList != null) {
20238                    final int removedCount = removedFromList.size();
20239                    for (int i = 0; i < removedCount; i++) {
20240                        deletePackageIfUnusedLPr(removedFromList.get(i));
20241                    }
20242                }
20243            }
20244        }
20245
20246        @Override
20247        public boolean isPermissionsReviewRequired(String packageName, int userId) {
20248            synchronized (mPackages) {
20249                // If we do not support permission review, done.
20250                if (!Build.PERMISSIONS_REVIEW_REQUIRED) {
20251                    return false;
20252                }
20253
20254                PackageSetting packageSetting = mSettings.mPackages.get(packageName);
20255                if (packageSetting == null) {
20256                    return false;
20257                }
20258
20259                // Permission review applies only to apps not supporting the new permission model.
20260                if (packageSetting.pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.M) {
20261                    return false;
20262                }
20263
20264                // Legacy apps have the permission and get user consent on launch.
20265                PermissionsState permissionsState = packageSetting.getPermissionsState();
20266                return permissionsState.isPermissionReviewRequired(userId);
20267            }
20268        }
20269
20270        @Override
20271        public ApplicationInfo getApplicationInfo(String packageName, int userId) {
20272            return PackageManagerService.this.getApplicationInfo(packageName, 0 /*flags*/, userId);
20273        }
20274
20275        @Override
20276        public ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
20277                int userId) {
20278            return PackageManagerService.this.getHomeActivitiesAsUser(allHomeCandidates, userId);
20279        }
20280    }
20281
20282    @Override
20283    public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) {
20284        enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps");
20285        synchronized (mPackages) {
20286            final long identity = Binder.clearCallingIdentity();
20287            try {
20288                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr(
20289                        packageNames, userId);
20290            } finally {
20291                Binder.restoreCallingIdentity(identity);
20292            }
20293        }
20294    }
20295
20296    private static void enforceSystemOrPhoneCaller(String tag) {
20297        int callingUid = Binder.getCallingUid();
20298        if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) {
20299            throw new SecurityException(
20300                    "Cannot call " + tag + " from UID " + callingUid);
20301        }
20302    }
20303
20304    boolean isHistoricalPackageUsageAvailable() {
20305        return mPackageUsage.isHistoricalPackageUsageAvailable();
20306    }
20307
20308    /**
20309     * Return a <b>copy</b> of the collection of packages known to the package manager.
20310     * @return A copy of the values of mPackages.
20311     */
20312    Collection<PackageParser.Package> getPackages() {
20313        synchronized (mPackages) {
20314            return new ArrayList<>(mPackages.values());
20315        }
20316    }
20317
20318    /**
20319     * Logs process start information (including base APK hash) to the security log.
20320     * @hide
20321     */
20322    public void logAppProcessStartIfNeeded(String processName, int uid, String seinfo,
20323            String apkFile, int pid) {
20324        if (!SecurityLog.isLoggingEnabled()) {
20325            return;
20326        }
20327        Bundle data = new Bundle();
20328        data.putLong("startTimestamp", System.currentTimeMillis());
20329        data.putString("processName", processName);
20330        data.putInt("uid", uid);
20331        data.putString("seinfo", seinfo);
20332        data.putString("apkFile", apkFile);
20333        data.putInt("pid", pid);
20334        Message msg = mProcessLoggingHandler.obtainMessage(
20335                ProcessLoggingHandler.LOG_APP_PROCESS_START_MSG);
20336        msg.setData(data);
20337        mProcessLoggingHandler.sendMessage(msg);
20338    }
20339}
20340